[#6] 修改web页面

This commit is contained in:
xiuting.xu 2025-09-24 14:45:30 +08:00
parent 4fff1af27c
commit e5fb0a280a
31 changed files with 1130 additions and 722 deletions

36
src/web/Dockerfile Normal file
View File

@ -0,0 +1,36 @@
# ---- 1. 构建阶段 ----
FROM node:20-alpine AS build
# 设置工作目录
WORKDIR /app
# 复制依赖清单
COPY package*.json ./
# 安装依赖
RUN npm install
# 复制全部源码
COPY . .
# 构建生产环境代码
RUN npm run build
# ---- 2. 部署阶段 ----
FROM nginx:alpine
# 删除默认配置
RUN rm /etc/nginx/conf.d/default.conf
# 复制你自己的 nginx 配置
COPY build_tools/front_end/nginx.conf /etc/nginx/conf.d/default.conf
# 将打包好的 dist 文件放到 nginx 的静态目录
COPY --from=build /app/dist /usr/share/nginx/html
# 暴露 80 端口
EXPOSE 80
# 启动 Nginx
CMD ["nginx", "-g", "daemon off;"]

View File

@ -1,39 +0,0 @@
from flask import Flask, jsonify
import requests
app = Flask(__name__)
EXTERNAL_APIS = {
"nodes": "http://master.argus.com/api/v1/nodes",
"alerts": "http://alertmanager.argus.com/api/v2/alerts"
}
def fetch_external(api_name):
"""通用的外部接口请求函数"""
try:
url = EXTERNAL_APIS[api_name]
response = requests.get(url, timeout=5)
response.raise_for_status()
return {"status": "success", "data": response.json()}
except requests.exceptions.RequestException as e:
return {"status": "error", "message": str(e)}
@app.route("/api/v1/web/health", methods=["GET"])
def get_health():
return jsonify(fetch_external("health"))
@app.route("/api/v1/web/nodes", methods=["GET"])
def get_nodes():
return jsonify(fetch_external("nodes"))
@app.route("/api/v1/web/alerts", methods=["GET"])
def get_alerts():
return jsonify(fetch_external("alerts"))
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)

View File

@ -0,0 +1,5 @@
docker pull node:20-alpine
docker pull nginx:alpine
cd ../..
docker build -t portal-frontend .
rm -f portal-frontend.tar.gz && sudo docker image save portal-frontend:latest | gzip > portal-frontend.tar.gz

View File

@ -0,0 +1,13 @@
server {
listen 80;
server_name web.argus.com;
root /usr/share/nginx/html;
index index.html;
# React 前端路由兼容
location / {
try_files $uri /index.html;
}
}

View File

@ -0,0 +1,17 @@
# 使用轻量级 Nginx 基础镜像
FROM nginx:1.25-alpine
# 删除默认配置
RUN rm -rf /etc/nginx/conf.d/*
# 复制自定义 Proxy 配置
# 可以在构建时直接COPY进去也可以运行时挂载
COPY conf.d/ /etc/nginx/conf.d/
# 日志目录(可选)
VOLUME ["/var/log/nginx"]
# 暴露端口
EXPOSE 80 443
CMD ["nginx", "-g", "daemon off;"]

Binary file not shown.

View File

@ -0,0 +1,71 @@
# 门户前端 (React 静态资源通过内网 Nginx 或 Node.js 服务暴露)
server {
listen 80;
server_name web.argus.com;
location / {
proxy_pass http://web.argus.com; # 门户前端内部服务
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
# Grafana
server {
listen 80;
server_name grafana.metric.argus.com;
location / {
proxy_pass http://grafana.metric.argus.com;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
# Prometheus
server {
listen 80;
server_name prometheus.metric.argus.com;
location / {
proxy_pass http://prometheus.metric.argus.com;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
# Elasticsearch
server {
listen 80;
server_name es.log.argus.com;
location / {
proxy_pass http://es.log.argus.com;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
# Kibana
server {
listen 80;
server_name kibana.log.argus.com;
location / {
proxy_pass http://kibana.log.argus.com;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
# Alertmanager
server {
listen 80;
server_name alertmanager.alert.argus.com;
location / {
proxy_pass http://alertmanager.alert.argus.com;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}

View File

@ -0,0 +1,2 @@
docker build -t argus-proxy:latest .
rm -f argus-proxy.tar.gz && sudo docker image save argus-proxy:latest | gzip > argus-proxy.tar.gz

View File

@ -0,0 +1,78 @@
server {
listen 80;
server_name web.argus.com;
# 门户网站React 前端),通过 proxy 转发到内部服务
location / {
proxy_pass http://portal-frontend:80;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
server {
listen 80;
server_name grafana.metric.argus.com;
location / {
proxy_pass http://grafana.metric.argus.com;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
server {
listen 80;
server_name prometheus.metric.argus.com;
location / {
proxy_pass http://prometheus.metric.argus.com;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
server {
listen 80;
server_name es.log.argus.com;
location / {
proxy_pass http://es.log.argus.com;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
server {
listen 80;
server_name kibana.log.argus.com;
location / {
proxy_pass http://kibana.log.argus.com;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
server {
listen 80;
server_name alertmanager.alert.argus.com;
location / {
proxy_pass http://alertmanager.alert.argus.com;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}

Binary file not shown.

View File

@ -1,29 +0,0 @@
import { Card, Group, Text, Anchor } from "@mantine/core";
export function AlertCard({ alerts, link }) {
const alertTypes = [
{ label: "严重告警", count: alerts.critical_alerts, color: "red" },
{ label: "主要告警", count: alerts.major_alerts, color: "yellow" },
{ label: "次要告警", count: alerts.minor_alerts, color: "blue" },
];
return (
<Card shadow="sm" radius="md" p="lg">
<Text fw={700} size="lg" mb="sm">告警监控</Text>
<Anchor href={link} target="_blank" size="xl" fw={700} mb="md" display="block">
{alerts.total_alerts} 待处理告警
</Anchor>
{alertTypes.map((a) => (
<Group position="apart" mb="xs" key={a.label}>
<Group spacing="xs">
<span style={{ display: "inline-block", width: 10, height: 10, borderRadius: "50%", backgroundColor: a.color }} />
<Text size="sm">{a.label}</Text>
</Group>
<Anchor href={link} target="_blank" fw={700} color={a.color}>{a.count}</Anchor>
</Group>
))}
</Card>
);
}

View File

@ -0,0 +1,38 @@
import { Group, Select } from "@mantine/core";
export function AlertFilters({ filters, setFilters, nodeOptions }) {
return (
<Group spacing="md">
<Select
label="严重性"
value={filters.severity}
onChange={(value) => setFilters((f) => ({ ...f, severity: value }))}
data={[
{ value: "all", label: "全部" },
{ value: "critical", label: "严重" },
{ value: "warning", label: "警告" },
{ value: "info", label: "信息" },
]}
w={150}
/>
<Select
label="状态"
value={filters.state}
onChange={(value) => setFilters((f) => ({ ...f, state: value }))}
data={[
{ value: "all", label: "全部" },
{ value: "active", label: "Active" },
{ value: "resolved", label: "Resolved" },
]}
w={150}
/>
<Select
label="节点"
value={filters.instance}
onChange={(value) => setFilters((f) => ({ ...f, instance: value }))}
data={nodeOptions}
w={150}
/>
</Group>
);
}

View File

@ -0,0 +1,47 @@
import { Card, Group, Text, Badge, Stack, Anchor } from "@mantine/core";
import { Link } from "react-router-dom";
export function AlertStats({ stats, layout = "row", title, link }) {
const Wrapper = layout === "row" ? Group : Stack;
return (
<Card withBorder radius="md" shadow="sm" p="md" mb="md">
{(title || link) && (
<Group position="apart" mb="sm">
{title && <Text fw={700} size="lg">{title}</Text>}
{link && (
<Anchor component={Link} to={link} size="sm" underline>
查看更多
</Anchor>
)}
</Group>
)}
<Wrapper spacing="xl" grow>
<Group spacing="xs">
<Badge color="gray" radius="sm" variant="filled"></Badge>
<Text size="sm" fw={500}>总数</Text>
<Text fw={700} color="gray">{stats.total || 0}</Text>
</Group>
<Group spacing="xs">
<Badge color="red" radius="sm" variant="filled"></Badge>
<Text size="sm" fw={500}>严重</Text>
<Text fw={700} color="red">{stats.critical || 0}</Text>
</Group>
<Group spacing="xs">
<Badge color="orange" radius="sm" variant="filled"></Badge>
<Text size="sm" fw={500}>警告</Text>
<Text fw={700} color="orange">{stats.warning || 0}</Text>
</Group>
<Group spacing="xs">
<Badge color="blue" radius="sm" variant="filled"></Badge>
<Text size="sm" fw={500}>信息</Text>
<Text fw={700} color="blue">{stats.info || 0}</Text>
</Group>
</Wrapper>
</Card>
);
}

View File

@ -0,0 +1,96 @@
import { Table, Group, ActionIcon, Button } from "@mantine/core";
import { IconChevronUp, IconChevronDown } from "@tabler/icons-react";
export function AlertTable({
alerts,
paginatedAlerts,
page,
setPage,
pageSize,
sortedAlerts,
sortConfig,
handleSort,
getRowColor,
getSeverityColor,
getStateBadge,
formatRelativeTime,
}) {
const totalPages = Math.ceil(sortedAlerts.length / pageSize);
return (
<>
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
{[
{ key: "alertname", label: "名称" },
{ key: "instance", label: "节点" },
{ key: "severity", label: "严重性" },
{ key: "state", label: "状态" },
{ key: "startsAt", label: "开始时间" },
{ key: "endsAt", label: "结束时间" },
{ key: "updatedAt", label: "更新时间" },
{ key: "summary", label: "描述" },
].map((col) => (
<Table.Th key={col.key}>
<Group spacing={4}>
{col.label}
{["severity", "startsAt", "instance"].includes(col.key) && (
<ActionIcon size="xs" onClick={() => handleSort(col.key)}>
{sortConfig.key === col.key && sortConfig.direction === "asc" ? (
<IconChevronUp size={14} />
) : (
<IconChevronDown size={14} />
)}
</ActionIcon>
)}
</Group>
</Table.Th>
))}
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{paginatedAlerts.map((alert, i) => (
<Table.Tr key={i} style={{ backgroundColor: getRowColor(alert) }}>
<Table.Td>{alert.labels?.alertname || "-"}</Table.Td>
<Table.Td>{alert.labels?.instance || "-"}</Table.Td>
<Table.Td style={{ color: getSeverityColor(alert.labels?.severity) }}>
{alert.labels?.severity || "info"}
</Table.Td>
<Table.Td>{getStateBadge(alert.status?.state)}</Table.Td>
<Table.Td title={alert.startsAt || "-"}>{formatRelativeTime(alert.startsAt)}</Table.Td>
<Table.Td title={alert.endsAt || "-"}>
{alert.endsAt ? new Date(alert.endsAt).toLocaleString() : "-"}
</Table.Td>
<Table.Td title={alert.updatedAt || "-"}>{formatRelativeTime(alert.updatedAt)}</Table.Td>
<Table.Td>{alert.annotations?.summary || "-"}</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
{/* 分页控件 */}
<Group position="apart" mt="sm">
<Button
disabled={page === 1}
onClick={() => setPage((p) => Math.max(1, p - 1))}
variant="outline"
size="xs"
>
上一页
</Button>
<span>
{page} / {totalPages}
</span>
<Button
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
variant="outline"
size="xs"
>
下一页
</Button>
</Group>
</>
);
}

View File

@ -1,46 +0,0 @@
import { Card, Group, Table, Text } from "@mantine/core";
import NodeStatus from "../components/NodeStatus";
import { Link } from "react-router-dom";
export function ClusterTable({ cluster }) {
const rows = cluster.nodes.map((n) => {
return (
<Table.Tr key={n.id}>
<Table.Td>{n.id}</Table.Td>
<Table.Td>{n.name}</Table.Td>
<Table.Td>
<NodeStatus status={n.status} />
</Table.Td>
<Table.Td>
<Text fw={600} c={n.load > 80 ? "red" : "blue"}>{n.load}%</Text>
</Table.Td>
</Table.Tr>
);
});
return (
<Card shadow="sm" radius="md" p="lg">
<Group position="apart" align="flex-end" mb="md">
<Text fw={700} size="lg">集群节点</Text>
{/* 链接到 /nodeInfo 页面 */}
<Link to="/nodeInfo" style={{ textDecoration: "none" }}>
<Text fw={600} size="xl" color="blue" sx={{ "&:hover": { textDecoration: "underline" } }}>
{cluster.total_nodes} 个节点
</Text>
</Link>
</Group>
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th>节点ID</Table.Th>
<Table.Th>节点名称</Table.Th>
<Table.Th>状态</Table.Th>
<Table.Th>负载</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>{rows}</Table.Tbody>
</Table>
</Card>
);
}

View File

@ -1,37 +1,60 @@
import { Card, Group, Text, RingProgress } from "@mantine/core";
// gray
const statusColors = {
healthy: "green",
warning: "yellow",
error: "red",
online: "green",
offline: "gray",
};
export function HealthCard({ health }) {
const totalNodes = health.healthy_nodes + health.warning_nodes + health.error_nodes;
const totalNodes = health?.total || 0;
const stats = health?.status_statistics || [];
// sections
const sections = stats.map((s) => ({
value: (s.count / totalNodes) * 100,
color: statusColors[s.status] || "gray",
}));
// 沿 online healthy
const mainStatus = stats.find(
(s) => s.status === "online" || s.status === "healthy"
);
const mainPercent = mainStatus
? ((mainStatus.count / totalNodes) * 100).toFixed(1)
: "0.0";
return (
<Card shadow="sm" radius="md" p="lg">
<Text fw={700} size="lg" mb="md">健康状态</Text>
<Text fw={700} size="lg" mb="md">节点健康状态</Text>
<Group spacing="xl" align="center">
<RingProgress
size={140}
thickness={14}
sections={[
{ value: (health.healthy_nodes / totalNodes) * 100, color: "green" },
{ value: (health.warning_nodes / totalNodes) * 100, color: "yellow" },
{ value: (health.error_nodes / totalNodes) * 100, color: "red" },
]}
label={<Text fw={700} ta="center" size="lg">{(health.healthy_nodes / totalNodes * 100).toFixed(1)}%</Text>}
sections={sections}
label={
<Text fw={700} ta="center" size="lg">
{mainPercent}%
</Text>
}
/>
<div style={{ display: "flex", flexDirection: "column", justifyContent: "center", gap: 8 }}>
<div style={{ display: "flex", justifyContent: "space-between", width: 120 }}>
<Text size="sm" color="green">健康节点</Text>
<Text fw={600}>{health.healthy_nodes}</Text>
</div>
<div style={{ display: "flex", justifyContent: "space-between", width: 120 }}>
<Text size="sm" color="yellow">警告节点</Text>
<Text fw={600}>{health.warning_nodes}</Text>
</div>
<div style={{ display: "flex", justifyContent: "space-between", width: 120 }}>
<Text size="sm" color="red">故障节点</Text>
<Text fw={600}>{health.error_nodes}</Text>
</div>
{stats.map((s, idx) => (
<div
key={idx}
style={{ display: "flex", justifyContent: "space-between", width: 140 }}
>
<Text size="sm" color={statusColors[s.status] || "gray"}>
{s.status}
</Text>
<Text fw={600}>{s.count}</Text>
</div>
))}
</div>
</Group>
</Card>

View File

@ -1,93 +1,132 @@
import { useState } from "react";
import {
Card,
Text,
Group,
Button,
TextInput,
Stack,
ActionIcon,
Select,
} from "@mantine/core";
import { IconEdit, IconX, IconCheck } from "@tabler/icons-react"; //
import { useState, useEffect } from "react";
import { Card, Text, Group, TextInput, Stack, ActionIcon } from "@mantine/core";
import { IconEdit, IconX, IconCheck, IconPlus, IconTrash } from "@tabler/icons-react";
import { apiRequest } from "../config/request";
import { EXTERNAL_API } from "../config/api";
export default function NodeConfigCard({ node, onSaved }) {
const [editing, setEditing] = useState(false);
const [config, setConfig] = useState(node.config || {});
const [saving, setSaving] = useState(false);
export default function NodeConfigCard({ nodeId, config = {}, onSaved }) {
const [editing, setEditing] = useState(false);
const [configList, setConfigList] = useState([]);
const [newKey, setNewKey] = useState("");
const [newValue, setNewValue] = useState("");
const [saving, setSaving] = useState(false);
const handleSave = async () => {
setSaving(true);
try {
await apiRequest(`${EXTERNAL_API.MASTER_NODES}/${node.id}`, {
method: "PUT",
body: JSON.stringify({ config }),
}, "配置已更新"); //
useEffect(() => {
const arr = Object.entries(config || {});
setConfigList(arr);
}, [config]);
setEditing(false);
onSaved && onSaved(); //
} catch (err) {
console.error("更新配置失败", err);
} finally {
setSaving(false);
}
};
const removeConfig = (index) => {
setConfigList((prev) => prev.filter((_, i) => i !== index));
};
return (
<Card shadow="sm" radius="md" withBorder>
<Group position="apart" mb="sm">
<Text fw={600}>配置信息</Text>
<Group spacing="xs">
{editing ? (
<>
<ActionIcon color="green" size="sm" loading={saving} onClick={handleSave}>
<IconCheck size={16} />
</ActionIcon>
<ActionIcon color="red" size="sm" onClick={() => setEditing(false)}>
<IconX size={16} />
</ActionIcon>
</>
) : (
<ActionIcon color="blue" size="sm" onClick={() => setEditing(true)}>
<IconEdit size={16} />
</ActionIcon>
)}
</Group>
</Group>
{editing ? (
<Stack>
<TextInput
label="最大连接数"
value={config.max_connections}
onChange={(e) =>
setConfig({ ...config, max_connections: e.target.value })
}
/>
<TextInput
label="超时时间"
value={config.timeout}
onChange={(e) =>
setConfig({ ...config, timeout: e.target.value })
}
/>
{/* 日志级别下拉框 */}
<Select
label="日志级别"
data={["trace", "debug", "info", "warn", "error", "fatal"]}
value={config.log_level}
onChange={(value) => setConfig({ ...config, log_level: value })}
/>
</Stack>
) : (
<Stack spacing="xs">
<Text size="sm">最大连接数: {config.max_connections}</Text>
<Text size="sm">超时时间: {config.timeout}</Text>
<Text size="sm">日志级别: {config.log_level}</Text>
</Stack>
)}
</Card>
const updateConfig = (index, key, value) => {
setConfigList((prev) =>
prev.map((item, i) => (i === index ? [key, value] : item))
);
};
const addConfig = () => {
if (newKey && !configList.find(([k]) => k === newKey)) {
setConfigList((prev) => [...prev, [newKey, newValue]]);
setNewKey("");
setNewValue("");
}
};
const handleSave = async () => {
setSaving(true);
try {
const configObj = Object.fromEntries(configList);
await apiRequest(`${EXTERNAL_API.MASTER_NODES}/${nodeId}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ config: configObj }),
});
setEditing(false);
onSaved && onSaved();
} finally {
setSaving(false);
}
};
return (
<Card shadow="sm" radius="md" withBorder>
<Group position="apart" mb="sm">
<Text fw={600}>配置信息</Text>
<Group spacing="xs">
{editing ? (
<>
<ActionIcon
color="green"
size="sm"
loading={saving}
onClick={handleSave}
>
<IconCheck size={16} />
</ActionIcon>
<ActionIcon color="red" size="sm" onClick={() => setEditing(false)}>
<IconX size={16} />
</ActionIcon>
</>
) : (
<ActionIcon color="blue" size="sm" onClick={() => setEditing(true)}>
<IconEdit size={16} />
</ActionIcon>
)}
</Group>
</Group>
{editing ? (
<Stack spacing="xs">
{configList.map(([key, value], idx) => (
<Group key={idx} spacing="xs">
<TextInput
placeholder="Key"
value={key}
onChange={(e) => updateConfig(idx, e.target.value, value)}
/>
<TextInput
placeholder="Value"
value={value}
onChange={(e) => updateConfig(idx, key, e.target.value)}
/>
<ActionIcon color="red" onClick={() => removeConfig(idx)}>
<IconTrash size={16} />
</ActionIcon>
</Group>
))}
<Group spacing="xs">
<TextInput
placeholder="新增 Key"
value={newKey}
onChange={(e) => setNewKey(e.target.value)}
/>
<TextInput
placeholder="新增 Value"
value={newValue}
onChange={(e) => setNewValue(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && addConfig()}
/>
<ActionIcon color="blue" onClick={addConfig}>
<IconPlus size={16} />
</ActionIcon>
</Group>
</Stack>
) : (
<Stack spacing="xs">
{configList.length > 0 ? (
configList.map(([key, value], idx) => (
<Group key={idx} spacing="xs">
<Text fw={500}>{key}:</Text>
<Text>{String(value)}</Text>
</Group>
))
) : (
<Text c="dimmed">暂无配置</Text>
)}
</Stack>
)}
</Card>
);
}

View File

@ -6,16 +6,14 @@ import {
Center,
ScrollArea,
Group,
Badge,
Stack,
Divider,
ThemeIcon,
Stack,
} from "@mantine/core";
import { healthStatus } from "../config/status";
import { apiRequest } from "../config/request";
import { EXTERNAL_API } from "../config/api";
//
import NodeConfigCard from "./NodeConfigCard";
import NodeLabelCard from "./NodeLabelCard";
import NodeMetaCard from "./NodeMetaCard";
@ -25,7 +23,6 @@ export default function NodeDetailDrawer({ opened, nodeId, onClose }) {
const [node, setNode] = useState(null);
const [loading, setLoading] = useState(false);
//
const fetchNodeDetail = async () => {
if (!nodeId) return;
setLoading(true);
@ -38,9 +35,7 @@ export default function NodeDetailDrawer({ opened, nodeId, onClose }) {
};
useEffect(() => {
if (opened && nodeId) {
fetchNodeDetail();
}
if (opened && nodeId) fetchNodeDetail();
}, [opened, nodeId]);
return (
@ -54,52 +49,69 @@ export default function NodeDetailDrawer({ opened, nodeId, onClose }) {
overlayProps={{ backgroundOpacity: 0.4, blur: 4 }}
>
{loading ? (
<Center h={200}>
<Loader size="sm" />
</Center>
) : node ? (
<div style={{ height: '90vh', display: 'flex', flexDirection: 'column' }}>
{/* 固定头部基础信息 */}
<div style={{ position: 'sticky', top: 0, background: 'white', zIndex: 10, paddingBottom: 8 }}>
<Group spacing="sm" align="center">
<ThemeIcon
size="lg"
radius="xl"
color={healthStatus(node.status).color}
variant="light"
>
{healthStatus(node.status).icon}
</ThemeIcon>
<Center h={200}>
<Loader size="sm" />
</Center>
) : node ? (
<div style={{ height: "90vh", display: "flex", flexDirection: "column" }}>
{/* 固定头部基础信息 */}
<div
style={{
position: "sticky",
top: 0,
background: "white",
zIndex: 10,
paddingBottom: 8,
}}
>
<Group spacing="sm" align="center">
<ThemeIcon
size="lg"
radius="xl"
color={healthStatus(node.status).color}
variant="light"
>
{healthStatus(node.status).icon}
</ThemeIcon>
<Text fw={700} size="xl">{node.name}</Text>
<Badge color="gray">{node.type}</Badge>
<Badge
color={healthStatus(node.status).color}
leftSection={healthStatus(node.status).icon}
>
{node.status}
</Badge>
</Group>
<Divider my="sm" />
</div>
<Text fw={700} size="xl">
{node.name}
</Text>
<Text c="dimmed">{node.type}</Text>
<Text c={healthStatus(node.status).color}>{node.status}</Text>
<Text c="dimmed" size="sm">
最后更新时间: {new Date(node.last_updated).toLocaleString()}
</Text>
</Group>
<Divider my="sm" />
</div>
{/* 滚动内容 */}
<ScrollArea style={{ flex: 1 }}>
<Stack spacing="md">
<NodeConfigCard node={node} onSaved={fetchNodeDetail} />
<NodeLabelCard node={node} onSaved={fetchNodeDetail} />
<NodeMetaCard node={node} />
<NodeHealthCard node={node} />
{/* 滚动内容 */}
<ScrollArea style={{ flex: 1 }}>
<Stack spacing="md">
{/* 配置信息 */}
<NodeConfigCard nodeId={node.id} config={node.config || {}} onSaved={fetchNodeDetail} />
<Text c="dimmed" size="sm" ta="right">
最后更新时间: {new Date(node.last_updated).toLocaleString()}
</Text>
</Stack>
</ScrollArea>
</div>
) : (
<Text c="dimmed">暂无数据</Text>
)}
{/* 标签信息 */}
<NodeLabelCard nodeId={node.id} labels={Array.isArray(node.label) ? node.label : []} onSaved={fetchNodeDetail} />
{/* 元数据 */}
<NodeMetaCard node={node} />
{/* 健康信息 */}
<NodeHealthCard node={node} />
{/* 其他基础信息展示 */}
<Stack spacing="xs">
<Text fw={500}>注册时间: <Text span c="dimmed">{new Date(node.register_time).toLocaleString()}</Text></Text>
<Text fw={500}>最近上报时间: <Text span c="dimmed">{new Date(node.last_report).toLocaleString()}</Text></Text>
</Stack>
</Stack>
</ScrollArea>
</div>
) : (
<Text c="dimmed">暂无数据</Text>
)}
</Drawer>
);
}

View File

@ -1,39 +1,14 @@
import { Card, Text, Group, Stack, Badge } from "@mantine/core";
import { IconCheck, IconAlertTriangle, IconX } from "@tabler/icons-react";
// +
const healthMap = {
activate: { color: "green", icon: IconCheck },
error: { color: "red", icon: IconX },
warning: { color: "yellow", icon: IconAlertTriangle },
inactive: { color: "gray", icon: IconX },
};
import { Card, Text, Stack } from "@mantine/core";
export default function NodeHealthCard({ node }) {
if (!node || !node.health) return null;
const items = Object.entries(node.health); // [['agent', 'activate'], ...]
const health = node.health || {};
return (
<Card shadow="sm" radius="md" withBorder>
<Text fw={600} mb="sm">健康状态</Text>
<Card shadow="xs" radius="md" withBorder>
<Text fw={600} mb="sm">健康信息</Text>
<Stack spacing="xs">
{items.map(([component, status]) => {
const { color, icon: Icon } = healthMap[status] || healthMap.inactive;
return (
<Group key={component} spacing="sm">
{/* 组件名 */}
<Text size="sm" fw={600} style={{ minWidth: 60 }}>
{component}
</Text>
{/* 状态标签 */}
<Badge color={color} leftSection={<Icon size={14} />} variant="filled">
{status}
</Badge>
</Group>
);
})}
<Text size="sm">日志: <Text span c="dimmed">{health.log || "无"}</Text></Text>
<Text size="sm">指标: <Text span c="dimmed">{health.metric || "无"}</Text></Text>
</Stack>
</Card>
);

View File

@ -1,29 +1,54 @@
import { useState } from "react";
import { Card, Text, Group, TextInput, Stack, ActionIcon } from "@mantine/core";
import { IconEdit, IconX, IconCheck } from "@tabler/icons-react";
import { useState, useEffect } from "react";
import { Card, Text, Group, TextInput, Stack, ActionIcon, Badge } from "@mantine/core";
import { IconEdit, IconX, IconCheck, IconPlus, IconTrash } from "@tabler/icons-react";
import { apiRequest } from "../config/request";
import { EXTERNAL_API } from "../config/api";
export default function NodeLabelCard({ node, onSaved }) {
export default function NodeLabelCard({ nodeId, labels = [], onSaved }) {
const [editing, setEditing] = useState(false);
const [label, setLabel] = useState(node.label || {});
const [tagList, setTagList] = useState([]);
const [tagColors, setTagColors] = useState([]);
const [newTag, setNewTag] = useState("");
const [saving, setSaving] = useState(false);
const randomColor = () => {
const colors = ["red","pink","grape","violet","indigo","blue","cyan","teal","green","lime","yellow","orange","gray"];
return colors[Math.floor(Math.random() * colors.length)];
};
useEffect(() => {
const arr = Array.isArray(labels) ? labels : [];
setTagList(arr);
setTagColors(arr.map(() => randomColor()));
}, [labels]);
const removeTag = (index) => {
setTagList((prev) => prev.filter((_, i) => i !== index));
setTagColors((prev) => prev.filter((_, i) => i !== index));
};
const updateTag = (index, value) => {
setTagList((prev) => prev.map((t, i) => (i === index ? value : t)));
};
const addTag = () => {
if (newTag && !tagList.includes(newTag)) {
setTagList((prev) => [...prev, newTag]);
setTagColors((prev) => [...prev, randomColor()]);
setNewTag("");
}
};
const handleSave = async () => {
setSaving(true);
try {
const res = await apiRequest(
`${EXTERNAL_API.MASTER_NODES}/${node.id}`,
{
method: "PUT",
body: JSON.stringify({ label }),
},
"标签已更新"
);
if (res) {
setEditing(false);
onSaved && onSaved();
}
await apiRequest(`${EXTERNAL_API.MASTER_NODES}/${nodeId}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ label: tagList }),
});
setEditing(false);
onSaved && onSaved();
} finally {
setSaving(false);
}
@ -36,31 +61,34 @@ export default function NodeLabelCard({ node, onSaved }) {
<Group spacing="xs">
{editing ? (
<>
<ActionIcon color="green" size="sm" loading={saving} onClick={handleSave}>
<IconCheck size={16} />
</ActionIcon>
<ActionIcon color="red" size="sm" onClick={() => setEditing(false)}>
<IconX size={16} />
</ActionIcon>
<ActionIcon color="green" size="sm" loading={saving} onClick={handleSave}><IconCheck size={16} /></ActionIcon>
<ActionIcon color="red" size="sm" onClick={() => setEditing(false)}><IconX size={16} /></ActionIcon>
</>
) : (
<ActionIcon color="blue" size="sm" onClick={() => setEditing(true)}>
<IconEdit size={16} />
</ActionIcon>
<ActionIcon color="blue" size="sm" onClick={() => setEditing(true)}><IconEdit size={16} /></ActionIcon>
)}
</Group>
</Group>
{editing ? (
<Stack>
<TextInput
label="标签"
value={label.tag}
onChange={(e) => setLabel({ ...label, tag: e.target.value })}
/>
<Stack spacing="xs">
{tagList.map((tag, idx) => (
<Group key={idx} spacing="xs">
<TextInput value={tag} onChange={(e) => updateTag(idx, e.target.value)} />
<ActionIcon color="red" onClick={() => removeTag(idx)}><IconTrash size={16} /></ActionIcon>
</Group>
))}
<Group spacing="xs">
<TextInput placeholder="新增标签" value={newTag} onChange={(e) => setNewTag(e.target.value)} onKeyDown={(e) => e.key === "Enter" && addTag()} />
<ActionIcon color="blue" onClick={addTag}><IconPlus size={16} /></ActionIcon>
</Group>
</Stack>
) : (
<Text size="sm">标签: {label.tag}</Text>
<Group spacing="xs" wrap="wrap">
{tagList.length > 0 ? tagList.map((tag, idx) => (
<Badge key={idx} color={tagColors[idx]} variant="light">{tag}</Badge>
)) : <Text c="dimmed">暂无标签</Text>}
</Group>
)}
</Card>
);

View File

@ -4,13 +4,17 @@ export default function NodeMetaCard({ node }) {
const meta = node.meta_data || {};
return (
<Card shadow="sm" radius="md" withBorder>
<Card shadow="xs" radius="md" withBorder>
<Text fw={600} mb="sm">元数据信息</Text>
<Stack spacing="xs">
<Text size="sm">主机: {meta.host}</Text>
<Text size="sm">IP: {meta.ip}</Text>
<Text size="sm">区域: {meta.region}</Text>
<Text size="sm">可用区: {meta.zone}</Text>
<Text size="sm">主机名: <Text span c="dimmed">{meta.hostname}</Text></Text>
<Text size="sm">IP: <Text span c="dimmed">{meta.ip}</Text></Text>
<Text size="sm">环境: <Text span c="dimmed">{meta.env}</Text></Text>
<Text size="sm">用户: <Text span c="dimmed">{meta.user}</Text></Text>
<Text size="sm">实例: <Text span c="dimmed">{meta.instance}</Text></Text>
<Text size="sm">CPU 数量: <Text span c="dimmed">{meta.cpu_number}</Text></Text>
<Text size="sm">内存: <Text span c="dimmed">{(meta.memory_in_bytes / 1024 / 1024).toFixed(2)} MB</Text></Text>
<Text size="sm">GPU 数量: <Text span c="dimmed">{meta.gpu_number}</Text></Text>
</Stack>
</Card>
);

View File

@ -1,142 +0,0 @@
import { useState, useEffect } from "react";
import { Modal, TextInput, Select, Button } from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { EXTERNAL_API } from "../config/api";
import { statusOptions } from "../config/status";
import { apiRequest } from "../config/request";
export default function NodeModal({ opened, onClose, node, onSaved }) {
const [form, setForm] = useState({ name: "", status: "healthy", load: 0 });
const [loading, setLoading] = useState(false);
const [errors, setErrors] = useState({ name: "", load: "" });
//
useEffect(() => {
setForm(node ? { ...node } : { name: "", status: "healthy", load: 0 });
setErrors({ name: "", load: "" });
}, [node]);
//
const validateField = (field, value) => {
switch (field) {
case "name":
setErrors((prev) => ({
...prev,
name: value.trim() ? "" : "名称不能为空",
}));
break;
case "load":
const loadNum = Number(value);
setErrors((prev) => ({
...prev,
load:
isNaN(loadNum) || loadNum < 0 || loadNum > 100
? "负载必须是 0~100 的数字"
: "",
}));
break;
default:
break;
}
};
const handleSave = async () => {
const name = form.name.trim();
const load = Number(form.load);
let hasError = false;
if (!name) {
setErrors((prev) => ({ ...prev, name: "名称不能为空" }));
notifications.show({
title: "校验失败",
message: "名称不能为空 ❌",
color: "red",
});
hasError = true;
}
if (isNaN(load) || load < 0 || load > 100) {
setErrors((prev) => ({ ...prev, load: "负载必须是 0~100 的数字" }));
notifications.show({
title: "校验失败",
message: "负载必须是 0~100 的数字 ❌",
color: "red",
});
hasError = true;
}
if (hasError) return;
const method = node ? "PUT" : "POST";
const url = node ? `${EXTERNAL_API.MASTER_NODES}/${node.id}` : EXTERNAL_API.MASTER_NODES;
setLoading(true);
try {
await apiRequest(url, {
method,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ...form, name, load }),
});
notifications.show({
title: "成功",
message: node ? "节点已更新 ✅" : "节点已新增 ✅",
color: "green",
autoClose: 3000,
});
setTimeout(() => {
onClose();
onSaved();
}, 3000);
} catch (err) {
notifications.show({
title: "错误",
message: `操作失败: ${err.message || "未知错误"}`,
color: "red",
});
} finally {
setLoading(false);
}
};
return (
<Modal
opened={opened}
onClose={onClose}
title={node ? "编辑节点" : "新增节点"}
>
<TextInput
label="名称"
value={form.name}
onChange={(e) => {
const value = e.target.value;
setForm((prev) => ({ ...prev, name: value }));
validateField("name", value);
}}
mb="sm"
error={errors.name}
required
/>
<Select
label="状态"
data={statusOptions}
value={form.status}
onChange={(val) => setForm((prev) => ({ ...prev, status: val }))}
mb="sm"
/>
<TextInput
label="负载"
type="number"
value={form.load}
onChange={(e) => {
const value = e.target.value;
setForm((prev) => ({ ...prev, load: value }));
validateField("load", value);
}}
mb="sm"
error={errors.load}
/>
<Button mt="md" onClick={handleSave} loading={loading}>
保存
</Button>
</Modal>
);
}

View File

@ -1,7 +1,7 @@
import { statusMap } from "../config/status";
export default function NodeStatus({ status }) {
const { color, labelCn } = statusMap[status] || { color: "gray", labelCn: "未知" };
const { color, label } = statusMap[status] || { color: "gray", label: "未知" };
return (
<span style={{ display: "flex", alignItems: "center" }}>
@ -15,7 +15,7 @@ export default function NodeStatus({ status }) {
marginRight: 8,
}}
/>
{labelCn}
{label}
</span>
);
}

View File

@ -0,0 +1,156 @@
import { useState, useEffect } from "react";
import { Card, Table, Button, Loader, Center, TextInput, Select, Group, Anchor, Text } from "@mantine/core";
import { Link } from "react-router-dom";
import NodeStatus from "./NodeStatus";
import PaginationControl from "./PaginationControl";
import { apiRequest } from "../config/request";
import { EXTERNAL_API } from "../config/api";
import { statusOptions } from "../config/status";
export function NodeTable({
withSearch = false,
withPagination = false,
withActions = false,
clusterData = null, // Dashboard
fetchDetail, // NodePage
title,
viewMoreLink,
}) {
const [nodes, setNodes] = useState([]);
const [totalCount, setTotalCount] = useState(0);
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(5);
const [loading, setLoading] = useState(false);
//
const [searchName, setSearchName] = useState("");
const [searchStatus, setSearchStatus] = useState("");
// NodePage 使
const fetchNodes = async (params = {}) => {
if (!withPagination && !withSearch) return; // Dashboard clusterData
setLoading(true);
try {
const query = new URLSearchParams({
page: params.page || page,
pageSize: params.pageSize || pageSize,
name: params.name !== undefined ? params.name : searchName,
status: params.status !== undefined ? params.status : searchStatus,
}).toString();
const result = await apiRequest(`${EXTERNAL_API.MASTER_NODES}?${query}`);
setNodes(result.data);
setTotalCount(result.total || 0);
} finally {
setLoading(false);
}
};
//
useEffect(() => {
if (withPagination || withSearch) {
fetchNodes();
} else if (clusterData) {
setNodes(clusterData.nodes || []);
setTotalCount(clusterData.total_nodes || 0);
}
}, [clusterData]);
//
const rows = nodes.map((node) => (
<Table.Tr key={node.id}>
<Table.Td>{node.id}</Table.Td>
<Table.Td>{node.name}</Table.Td>
<Table.Td><NodeStatus status={node.status} /></Table.Td>
<Table.Td>{node.type}</Table.Td>
<Table.Td>{node.version}</Table.Td>
{withActions && (
<Table.Td>
<Button
size="xs"
variant="light"
onClick={() => fetchDetail && fetchDetail(node.id)}
>
查看详情
</Button>
</Table.Td>
)}
</Table.Tr>
));
return (
<Card shadow="sm" radius="md" p="lg">
{/* 标题 + 查看更多 */}
{(title || viewMoreLink) && (
<Group position="apart" mb="sm">
{title && <Text fw={700} size="lg">{title}</Text>}
{viewMoreLink && (
<Anchor component={Link} to={viewMoreLink} size="sm" underline>
查看更多
</Anchor>
)}
</Group>
)}
{/* 搜索区域 */}
{withSearch && (
<div style={{ display: "flex", gap: 8, marginBottom: 16 }}>
<TextInput
placeholder="搜索节点名称"
value={searchName}
onChange={(e) => setSearchName(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && fetchNodes({ page: 1, name: searchName, status: searchStatus })}
style={{ width: 200 }}
/>
<Select
data={statusOptions}
value={searchStatus}
onChange={setSearchStatus}
placeholder="状态"
style={{ width: 120 }}
/>
<Button onClick={() => fetchNodes({ page: 1, name: searchName, status: searchStatus })}>搜索</Button>
<Button onClick={() => fetchNodes()} variant="outline">刷新列表</Button>
</div>
)}
{loading ? (
<Center h={200}><Loader size="lg" /></Center>
) : (
<>
<Table striped highlightOnHover withTableBorder>
<Table.Thead>
<Table.Tr>
<Table.Th>ID</Table.Th>
<Table.Th>名称</Table.Th>
<Table.Th>状态</Table.Th>
<Table.Th>类型</Table.Th>
<Table.Th>版本</Table.Th>
{withActions && <Table.Th>操作</Table.Th>}
</Table.Tr>
</Table.Thead>
<Table.Tbody>{rows}</Table.Tbody>
</Table>
{withPagination && (
<PaginationControl
totalItems={totalCount}
page={page}
pageSize={pageSize}
onPageChange={(p) => {
setPage(p);
fetchNodes({ page: p });
}}
onPageSizeChange={(size) => {
setPageSize(size);
setPage(1);
fetchNodes({ page: 1, pageSize: size });
}}
/>
)}
</>
)}
</Card>
);
}

View File

@ -1,17 +1,13 @@
export const NODES_API_URL = "http://master.argus.com/api/v1/nodes";
export const INTERNAL_API = {
CLUSTER: "/api/v1/web/cluster",
HEALTH: "/api/v1/web/health",
ALERTS: "/api/v1/web/alerts",
}
export const EXTERNAL_API = {
MASTER_NODES: "http://master.argus.com/api/v1/nodes",
MASTER_NODES: "http://master.argus.com/api/v1/master/nodes",
MASTER_NODES_STATISTICS: "http://master.argus.com/api/v1/master/nodes/statistics",
ALERTS_INFOS: "http://localhost:9093/api/v2/alerts",
}
// proxy location定位到具体位置。
// proxy需要单独的机器nginx配置。提供对外的endpoint通过算力平台映射。
export const EXTERNAL_HOST = {
ALERTS: "http://alertmanager.alert.argus.com",
ALERTS: "http://localhost:9093",
GRAFANA: "http://grafana.metric.argus.com",
PROMETHEUS: "http://prometheus.metric.argus.com",
ES: "http://es.log.argus.com",

View File

@ -34,59 +34,73 @@ export async function apiRequest(url, options = {}, successMsg) {
return data;
} catch (err) {
notifications.show({
title: "操作失败",
message: err.message || "接口调用失败",
color: "red",
});
console.log("API 请求错误:", err);
// notifications.show({
// title: "操作失败",
// message: err.message || "接口调用失败",
// color: "red",
// });
// throw err; // 继续抛出错误,方便上层处理
}
// 返回 mock 数据
if (url.includes("/api/v1/nodes")) {
if (/\/api\/v1\/nodes\/[^\/]+$/.test(url)) {
if (url.includes("/api/v1/master/nodes")) {
if (url.includes("/statistics")) {
return {
"id": "node1",
"name": "Node 1",
"total": 30,
"status_statistics": [
{ "status": "online", "count": 20 },
{ "status": "offline", "count": 10 },
]
};
}
if (/\/api\/v1\/master\/nodes\/[^\/]+$/.test(url)) {
return {
"id": "A1", // master分配的唯一ID, A代表Agent数字1开始按顺序编号c
"name": "Node 1", // agent上报时提供的hostname
"status": "online",
"config": {
// !!! 格式待定, 下发给agent用的
"max_connections": 100,
"timeout": 30,
"log_level": "info"
// !!! 预留字段KV形式非固定key, web配置下发给agent用的
"setting1": "value1",
"setting2": "value2",
"setting3": "value3",
"setting4": "value4"
},
"meta_data": {
// 元数据: host, ip,
"host": "192.168.1.1",
"ip": "192.168.1.1",
"region": "shanghai",
"zone": "shanghai-1",
// 元数据: 容器生命周期内不变
"hostname": "dev-yyrshare-nbnyx10-cp2f-pod-0",
"ip": "177.177.74.223",
"env": "dev", // 环境名, 从hostname中提取第一段
"user": "yyrshare", // 账户名从hostname中提取第二段
"instance": "nbnyx10", // 容器示例名从hostname中提取第三段
"cpu_number": 16,
"memory_in_bytes": 2015040000,
"gpu_number": 8
},
"label": {
"label": [
// 用户或运维人员绑定到节点上的标签,业务属性, tag
"tag": "value1",
"gpu", "exp001"
],
"health": { // agent收集到各端上模块的health描述文件
"log": "", //字符串,转义,防止换行、引号
"metric": ""
},
"health": {
"agent": "activate",
"log": "error",
"metric": "activate",
},
"last_updated": "2023-10-05T12:00:00Z",
"type": "worker"
"register_time": "2023-10-03T12:00:00Z", // 节点注册时间
"last_report": "2023-10-03T12:00:00Z", // 最近一次上报时间
"last_updated": "2023-10-05T12:00:00Z", // 更新NodeObject落库时间戳
"type": "agent" // 缺省为agent未来可能有新的节点类型
}
}
return {
"total": 30,
"data": [
{ id: "node1", name: "节点A", status: "healthy", type: "agent", version: "1.0.0" },
{ id: "node2", name: "节点B", status: "warning", type: "agent", version: "1.0.0"},
{ id: "node3", name: "节点C", status: "error", type: "agent", version: "1.0.0"},
{ id: "node4", name: "节点D", status: "healthy", type: "agent", version: "1.0.0"},
{ id: "node5", name: "节点E", status: "warning", type: "agent", version: "1.0.0"},
{ id: "node6", name: "节点F", status: "error", type: "agent", version: "1.0.0"},
{ id: "node7", name: "节点G", status: "healthy", type: "agent", version: "1.0.0"},
{ id: "node8", name: "节点H", status: "warning", type: "agent", version: "1.0.0"},
{ id: "node1", name: "节点A", status: "online", type: "agent", version: "1.0.0" },
{ id: "node2", name: "节点B", status: "online", type: "agent", version: "1.0.0" },
{ id: "node3", name: "节点C", status: "offline", type: "agent", version: "1.0.0" },
{ id: "node4", name: "节点D", status: "online", type: "agent", version: "1.0.0" },
{ id: "node5", name: "节点E", status: "online", type: "agent", version: "1.0.0" },
]
};
}

View File

@ -7,9 +7,8 @@ import {
} from "@tabler/icons-react";
export const statusMap = {
healthy: { label: "Healthy", color: "green", labelCn: "健康" },
warning: { label: "Warning", color: "orange", labelCn: "警告" },
error: { label: "Error", color: "red", labelCn: "错误" },
online: { label: "Online", color: "green"},
offline: { label: "Offline", color: "red"},
};
export const statusOptions = Object.entries(statusMap).map(([value, { label }]) => ({

View File

@ -0,0 +1,15 @@
export function formatRelativeTime(dateStr) {
if (!dateStr) return "-";
const date = new Date(dateStr);
const now = new Date();
const diffMs = now - date;
const diffSec = Math.floor(diffMs / 1000);
const diffMin = Math.floor(diffSec / 60);
const diffHour = Math.floor(diffMin / 60);
const diffDay = Math.floor(diffHour / 24);
if (diffSec < 60) return `${diffSec} 秒前`;
if (diffMin < 60) return `${diffMin} 分钟前`;
if (diffHour < 24) return `${diffHour} 小时前`;
return `${diffDay} 天前`;
}

View File

@ -1,18 +1,160 @@
import { Grid, Stack, Title } from "@mantine/core";
import EntryCard from "../components/EntryCard";
import { alertsEntries } from "../config/entries";
import { useEffect, useState, useMemo } from "react";
import { Stack, Title, Loader, Center, Group, Button, Badge, ActionIcon } from "@mantine/core";
import { IconRefresh } from "@tabler/icons-react";
import { apiRequest } from "../config/request";
import { EXTERNAL_API } from "../config/api";
import { AlertStats } from "../components/AlertStats";
import { AlertFilters } from "../components/AlertFilters";
import { AlertTable } from "../components/AlertTable";
import { formatRelativeTime } from "../config/utils";
import { EXTERNAL_HOST } from "../config/api";
export default function Alerts() {
const [alerts, setAlerts] = useState([]);
const [stats, setStats] = useState({ critical: 0, warning: 0, info: 0 });
const [loading, setLoading] = useState(true);
const [filters, setFilters] = useState({ severity: "all", state: "all", instance: "all" });
const [page, setPage] = useState(1);
const pageSize = 10;
const [sortConfig, setSortConfig] = useState({ key: "startsAt", direction: "desc" });
async function fetchAlerts() {
setLoading(true);
const data = await apiRequest(EXTERNAL_API.ALERTS_INFOS);
if (data && Array.isArray(data)) {
setAlerts(data);
const counts = { critical: 0, warning: 0, info: 0 };
data.forEach((alert) => {
const sev = alert.labels?.severity || "info";
if (sev === "critical") counts.critical++;
else if (sev === "warning") counts.warning++;
else counts.info++;
});
setStats(counts);
}
setLoading(false);
}
useEffect(() => {
fetchAlerts();
const timer = setInterval(fetchAlerts, 30000);
return () => clearInterval(timer);
}, []);
//
const nodeOptions = useMemo(() => {
const nodes = Array.from(new Set(alerts.map((a) => a.labels?.instance).filter(Boolean)));
return [{ value: "all", label: "全部" }, ...nodes.map((n) => ({ value: n, label: n }))];
}, [alerts]);
// & &
const filteredAlerts = useMemo(() => {
return alerts.filter((alert) => {
const sev = alert.labels?.severity || "info";
const state = alert.status?.state || "active";
const instance = alert.labels?.instance || "";
return (
(filters.severity === "all" || filters.severity === sev) &&
(filters.state === "all" || filters.state === state) &&
(filters.instance === "all" || filters.instance === instance)
);
});
}, [alerts, filters]);
const sortedAlerts = useMemo(() => {
const sorted = [...filteredAlerts];
if (sortConfig.key) {
sorted.sort((a, b) => {
let valA, valB;
if (sortConfig.key === "severity") {
const map = { critical: 3, warning: 2, info: 1 };
valA = map[a.labels?.severity] || 0;
valB = map[b.labels?.severity] || 0;
} else if (["startsAt", "endsAt", "updatedAt"].includes(sortConfig.key)) {
valA = new Date(a[sortConfig.key]).getTime() || 0;
valB = new Date(b[sortConfig.key]).getTime() || 0;
} else if (sortConfig.key === "instance") {
valA = a.labels?.instance || "";
valB = b.labels?.instance || "";
} else {
valA = a.labels?.alertname || "";
valB = b.labels?.alertname || "";
}
if (valA < valB) return sortConfig.direction === "asc" ? -1 : 1;
if (valA > valB) return sortConfig.direction === "asc" ? 1 : -1;
return 0;
});
}
return sorted;
}, [filteredAlerts, sortConfig]);
const paginatedAlerts = useMemo(() => {
const start = (page - 1) * pageSize;
return sortedAlerts.slice(start, start + pageSize);
}, [sortedAlerts, page]);
// & Badge
const getRowColor = (alert) => {
if (alert.status?.state === "resolved") return "gray.1";
const sev = alert.labels?.severity;
if (sev === "critical") return "red.0";
if (sev === "warning") return "orange.0";
if (sev === "info") return "blue.0";
return undefined;
};
const getSeverityColor = (sev) => {
if (sev === "critical") return "red";
if (sev === "warning") return "orange";
if (sev === "info") return "blue";
return "gray";
};
const getStateBadge = (state) => (
<Badge color={state === "active" ? "red" : "gray"} variant="filled" size="xs">
{state}
</Badge>
);
const handleSort = (key) => {
setSortConfig((prev) => ({
key,
direction: prev.key === key && prev.direction === "asc" ? "desc" : "asc",
}));
};
return (
<Stack spacing="lg" p="md">
<Title order={2}>告警详情</Title>
<Grid gutter="lg">
{alertsEntries.map((entry) => (
<Grid.Col key={entry.href} span={{ base: 12, sm: 4, md: 3 }}>
<EntryCard label={entry.label} href={entry.href} icon={entry.icon} />
</Grid.Col>
))}
</Grid>
<Group position="apart">
<Title order={2}>告警详情</Title>
<Button component="a" href="{EXTERNAL_HOST.ALERTS}" target="_blank" variant="outline">
打开 Alertmanager
</Button>
<ActionIcon onClick={fetchAlerts} color="blue" variant="filled" size="lg" title="刷新">
<IconRefresh size={20} />
</ActionIcon>
</Group>
<AlertStats stats={stats} />
<AlertFilters filters={filters} setFilters={setFilters} nodeOptions={nodeOptions} />
{loading ? (
<Center>
<Loader />
</Center>
) : (
<AlertTable
alerts={alerts}
paginatedAlerts={paginatedAlerts}
page={page}
setPage={setPage}
pageSize={pageSize}
sortedAlerts={sortedAlerts}
sortConfig={sortConfig}
handleSort={handleSort}
getRowColor={getRowColor}
getSeverityColor={getSeverityColor}
getStateBadge={getStateBadge}
formatRelativeTime={formatRelativeTime}
/>
)}
</Stack>
);
}

View File

@ -1,10 +1,10 @@
import { useEffect, useState } from "react";
import { Grid, Text } from "@mantine/core";
import { ClusterTable } from "../components/DashboardNodeTable";
import { NodeTable } from "../components/NodeTable";
import { HealthCard } from "../components/HealthCard";
import { AlertCard } from "../components/AlertCard";
import { AlertStats } from "../components/AlertStats";
import { apiRequest } from "../config/request";
import { INTERNAL_API, EXTERNAL_API, EXTERNAL_HOST } from "../config/api";
import { EXTERNAL_API } from "../config/api";
export default function Dashboard() {
const [cluster, setCluster] = useState(null);
@ -12,14 +12,25 @@ export default function Dashboard() {
const [alerts, setAlerts] = useState(null);
const [loading, setLoading] = useState(true);
const countAlerts = (data) => {
const stats = { critical: 0, warning: 0, info: 0 };
data?.forEach((alert) => {
const severity = alert.labels?.severity || "info";
if (severity === "critical") stats.critical++;
else if (severity === "warning") stats.warning++;
else stats.info++;
});
return stats;
};
useEffect(() => {
async function fetchData() {
setLoading(true);
try {
const [clusterRes, healthRes, alertsRes] = await Promise.all([
apiRequest(EXTERNAL_API.MASTER_NODES),
apiRequest(INTERNAL_API.HEALTH),
apiRequest(INTERNAL_API.ALERTS),
apiRequest(EXTERNAL_API.MASTER_NODES_STATISTICS),
apiRequest(EXTERNAL_API.ALERTS_INFOS),
]);
setCluster({
@ -28,17 +39,11 @@ export default function Dashboard() {
});
setHealth({
healthy_nodes: healthRes?.healthy_nodes || 0,
warning_nodes: healthRes?.warning_nodes || 0,
error_nodes: healthRes?.error_nodes || 0,
total: healthRes?.total || 0,
status_statistics: healthRes?.status_statistics || [],
});
setAlerts({
total_alerts: alertsRes?.total_alerts || 0,
critical_alerts: alertsRes?.critical_alerts || 0,
major_alerts: alertsRes?.major_alerts || 0,
minor_alerts: alertsRes?.minor_alerts || 0,
});
setAlerts(countAlerts(alertsRes?.data || []));
} catch (err) {
console.error("获取 Dashboard 数据失败:", err);
} finally {
@ -59,9 +64,12 @@ export default function Dashboard() {
return (
<Grid>
<Grid.Col span={12}><ClusterTable cluster={cluster} /></Grid.Col>
<Grid.Col span={6}><HealthCard health={health} /></Grid.Col>
<Grid.Col span={6}><AlertCard alerts={alerts} link={EXTERNAL_HOST.ALERTS} /></Grid.Col>
<Grid.Col span={6}>
<AlertStats stats={alerts} layout="column" title="告警统计" link="/alerts" />
</Grid.Col>
<Grid.Col span={12}><NodeTable clusterData={cluster} title="集群节点" viewMoreLink="/nodeInfo" /></Grid.Col>
</Grid>
);
}

View File

@ -1,58 +1,14 @@
import { useState, useEffect } from "react";
import {
Table,
Button,
TextInput,
Select,
Loader,
Center,
Text,
Grid,
} from "@mantine/core";
import { EXTERNAL_API } from "../config/api";
import PaginationControl from "../components/PaginationControl";
import NodeStatus from "../components/NodeStatus";
import NodeModal from "../components/NodeModal";
import NodeDetailDrawer from "../components/NodeDetailDrawer";
import { useState } from "react";
import { Grid } from "@mantine/core";
import { apiRequest } from "../config/request";
import { EXTERNAL_API } from "../config/api";
import { NodeTable } from "../components/NodeTable";
import NodeDetailDrawer from "../components/NodeDetailDrawer";
export default function NodePage() {
const [nodes, setNodes] = useState([]);
const [totalCount, setTotalCount] = useState(0);
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(5);
const [modalOpen, setModalOpen] = useState(false);
const [editNode, setEditNode] = useState(null);
const [loading, setLoading] = useState(false);
//
const [searchName, setSearchName] = useState("");
const [searchStatus, setSearchStatus] = useState("");
//
const [selectedNode, setSelectedNode] = useState(null);
const [detailLoading, setDetailLoading] = useState(false);
const [drawerOpen, setDrawerOpen] = useState(false);
//
const fetchNodes = async (params = {}) => {
setLoading(true);
try {
//
const query = new URLSearchParams({
page: params.page || page,
pageSize: params.pageSize || pageSize,
name: params.name !== undefined ? params.name : searchName,
status: params.status !== undefined ? params.status : searchStatus,
}).toString();
const result = await apiRequest(`${EXTERNAL_API.MASTER_NODES}?${query}`);
setNodes(result.data);
setTotalCount(result.total || 0);
} finally {
setLoading(false);
}
};
const [detailLoading, setDetailLoading] = useState(false);
//
const fetchNodeDetail = async (id) => {
@ -65,124 +21,17 @@ export default function NodePage() {
setDetailLoading(false);
}
};
useEffect(() => {
fetchNodes();
}, []);
//
const handleSearch = () => {
setPage(1); //
fetchNodes({ page: 1, name: searchName, status: searchStatus });
};
return (
<Grid gutter="lg">
{/* 左侧:表格 */}
<Grid.Col span={selectedNode ? 8 : 12}>
{/* 顶部操作区 */}
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
marginBottom: 16,
}}
>
{/* 搜索区 */}
<div style={{ display: "flex", gap: 8, alignItems: "center" }}>
<TextInput
placeholder="搜索节点名称"
value={searchName}
onChange={(e) => setSearchName(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") handleSearch();
}}
style={{ width: 200 }}
/>
<Select
data={[
{ value: "", label: "全部状态" },
{ value: "healthy", label: "Healthy" },
{ value: "warning", label: "Warning" },
{ value: "error", label: "Error" },
]}
value={searchStatus}
onChange={setSearchStatus}
placeholder="状态"
style={{ width: 120 }}
/>
<Button onClick={handleSearch}>搜索</Button>
</div>
{/* 操作按钮 */}
<div style={{ display: "flex", gap: 8 }}>
<Button
onClick={() => fetchNodes({ name: searchName, status: searchStatus })}
variant="outline"
>
刷新列表
</Button>
</div>
</div>
{loading ? (
<Center h={200}>
<Loader size="lg" />
</Center>
) : (
<>
<Table striped highlightOnHover withTableBorder>
<Table.Thead>
<Table.Tr>
<Table.Th>ID</Table.Th>
<Table.Th>名称</Table.Th>
<Table.Th>状态</Table.Th>
<Table.Th>类型</Table.Th>
<Table.Th>版本</Table.Th>
<Table.Th>操作</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{nodes.map((node) => (
<Table.Tr key={node.id}>
<Table.Td>{node.id}</Table.Td>
<Table.Td>{node.name}</Table.Td>
<Table.Td>
<NodeStatus status={node.status} />
</Table.Td>
<Table.Td>{node.type}</Table.Td>
<Table.Td>{node.version}</Table.Td>
<Table.Td>
<Button
size="xs"
variant="light"
onClick={() => fetchNodeDetail(node.id)}
>
查看详情
</Button>
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
<PaginationControl
totalItems={totalCount}
page={page}
pageSize={pageSize}
onPageChange={(p) => {
setPage(p);
fetchNodes({ page: p });
}}
onPageSizeChange={(size) => {
setPageSize(size);
setPage(1);
fetchNodes({ page: 1, pageSize: size });
}}
/>
</>
)}
{/* 左侧:节点表格 */}
<Grid.Col span={drawerOpen ? 8 : 12}>
<NodeTable
withSearch
withPagination
withActions
fetchDetail={fetchNodeDetail}
/>
</Grid.Col>
{/* 节点详情 Drawer */}
@ -190,6 +39,7 @@ export default function NodePage() {
opened={drawerOpen}
onClose={() => setDrawerOpen(false)}
nodeId={selectedNode}
loading={detailLoading}
/>
</Grid>
);