feat(alert-center): 添加飞书Webhook通知渠道 + 告警引擎实时通知
- 后端: NotifyChannel 模型新增 feishu 类型, FeishuWebhookConfig - 后端: TestNotifyChannel 真实发送飞书测试消息(文本格式) - 后端: 告警引擎触发/恢复时自动发送飞书通知(sendFeishuAlert/sendFeishuRecovery) - 后端: AlertEngine 新增 tcp_time_wait/tcp_close_wait/service_process 指标检测 - 后端: NetworkStatModel 新增 TCPCloseWait 字段 - 后端: QuickSetupRules 一键创建6条告警规则(CPU/内存/磁盘/TIME_WAIT/CLOSE_WAIT/进程) - 后端: 注册 /alerts/quick-setup 路由 - 前端: AlertChannelDialog 新增飞书类型选项 - 前端: helpers 新增 getChannelIcon/getChannelTypeLabel 支持 feishu/dingtalk/wechat
This commit is contained in:
1 parent
7bc5169e8f
commit
5333f6f04a
30 files changed
+2406
-1001
No files matched your search
@@ -0,0 +1,157 @@
|
||||
// Package collector — 进程 TOP3 采集器
|
||||
// 扫描 /proc/*/stat + /proc/*/status 获取 CPU/内存/句柄 TOP3 进程
|
||||
// 1000 服务器规模下的优化:只取 TOP3,不遍历全部进程的 cmdline
|
||||
//
|
||||
// 署名 Logan.Li
|
||||
package collector
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"ezops/agent/model"
|
||||
)
|
||||
|
||||
// ProcessTopCollector 进程 TOP 采集器
|
||||
type ProcessTopCollector struct{}
|
||||
|
||||
// NewProcessTopCollector 创建进程 TOP 采集器
|
||||
func NewProcessTopCollector() *ProcessTopCollector {
|
||||
return &ProcessTopCollector{}
|
||||
}
|
||||
|
||||
// procSample holds key metrics for a single process
|
||||
type procSample struct {
|
||||
PID int
|
||||
Name string
|
||||
CPU float64 // CPU 使用率(需两次采样 + 系统总 jiffies 才能算,这里用 utime+stime ticks 近似)
|
||||
RSSKB uint64 // 物理内存 (KB)
|
||||
FDCount int // 打开的文件句柄数
|
||||
Threads int // 线程数
|
||||
}
|
||||
|
||||
// Collect gathers process metrics and returns top N sorted by RSS.
|
||||
// Sorting by RSS is the most stable and reliable metric without multi-sampling CPU.
|
||||
func (p *ProcessTopCollector) Collect(topN int) ([]model.ProcessStat, error) {
|
||||
entries, err := os.ReadDir("/proc")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var samples []procSample
|
||||
for _, entry := range entries {
|
||||
if !entry.IsDir() {
|
||||
continue
|
||||
}
|
||||
pid, err := strconv.Atoi(entry.Name())
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
name := readProcName(entry.Name())
|
||||
// Skip kernel threads (empty cmdline + running in kernel)
|
||||
if name == "" || strings.HasPrefix(name, "[") {
|
||||
continue
|
||||
}
|
||||
|
||||
rssKB := readProcRSS(entry.Name())
|
||||
fdCount := countFD(entry.Name())
|
||||
threads := readProcThreads(entry.Name())
|
||||
|
||||
samples = append(samples, procSample{
|
||||
PID: pid,
|
||||
Name: name,
|
||||
RSSKB: rssKB,
|
||||
FDCount: fdCount,
|
||||
Threads: threads,
|
||||
})
|
||||
}
|
||||
|
||||
// Sort by RSS descending
|
||||
sort.Slice(samples, func(i, j int) bool {
|
||||
return samples[i].RSSKB > samples[j].RSSKB
|
||||
})
|
||||
|
||||
// Take top N
|
||||
if topN > len(samples) {
|
||||
topN = len(samples)
|
||||
}
|
||||
result := make([]model.ProcessStat, topN)
|
||||
for i := 0; i < topN; i++ {
|
||||
s := samples[i]
|
||||
result[i] = model.ProcessStat{
|
||||
PID: s.PID,
|
||||
Name: s.Name,
|
||||
MemoryMB: float64(s.RSSKB) / 1024.0,
|
||||
FDCount: s.FDCount,
|
||||
Threads: s.Threads,
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// readProcName reads /proc/<pid>/comm
|
||||
func readProcName(pid string) string {
|
||||
data, err := os.ReadFile(filepath.Join("/proc", pid, "comm"))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(string(data))
|
||||
}
|
||||
|
||||
// readProcRSS reads VmRSS from /proc/<pid>/status
|
||||
func readProcRSS(pid string) uint64 {
|
||||
f, err := os.Open(filepath.Join("/proc", pid, "status"))
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
scanner := bufio.NewScanner(f)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if strings.HasPrefix(line, "VmRSS:") {
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) >= 2 {
|
||||
val, _ := strconv.ParseUint(fields[1], 10, 64)
|
||||
return val
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// readProcThreads reads Threads from /proc/<pid>/status
|
||||
func readProcThreads(pid string) int {
|
||||
f, err := os.Open(filepath.Join("/proc", pid, "status"))
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
scanner := bufio.NewScanner(f)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if strings.HasPrefix(line, "Threads:") {
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) >= 2 {
|
||||
val, _ := strconv.Atoi(fields[1])
|
||||
return val
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// countFD counts open file descriptors for a process
|
||||
func countFD(pid string) int {
|
||||
entries, err := os.ReadDir(filepath.Join("/proc", pid, "fd"))
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return len(entries)
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// Package collector — Swap 采集器
|
||||
// 从 /proc/meminfo 读取 SwapTotal / SwapFree
|
||||
// 仅当系统有 swap 分区时返回有效数据
|
||||
//
|
||||
// 署名 Logan.Li
|
||||
package collector
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"ezops/agent/model"
|
||||
)
|
||||
|
||||
// SwapCollector 交换分区采集器
|
||||
type SwapCollector struct{}
|
||||
|
||||
// NewSwapCollector 创建 Swap 采集器
|
||||
func NewSwapCollector() *SwapCollector {
|
||||
return &SwapCollector{}
|
||||
}
|
||||
|
||||
// Collect 读取 swap 指标
|
||||
func (s *SwapCollector) Collect() (*model.SwapStat, error) {
|
||||
f, err := os.Open("/proc/meminfo")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
var swapTotal, swapFree uint64
|
||||
scanner := bufio.NewScanner(f)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) < 2 {
|
||||
continue
|
||||
}
|
||||
// Line format: "SwapTotal: 0 kB"
|
||||
key := strings.TrimSuffix(fields[0], ":")
|
||||
switch key {
|
||||
case "SwapTotal":
|
||||
swapTotal, _ = parseUint64(fields[1])
|
||||
case "SwapFree":
|
||||
swapFree, _ = parseUint64(fields[1])
|
||||
}
|
||||
}
|
||||
|
||||
// No swap configured — return nil (caller should omit from report)
|
||||
if swapTotal == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
used := swapTotal - swapFree
|
||||
stat := &model.SwapStat{
|
||||
TotalGB: float64(swapTotal) / (1024.0 * 1024.0),
|
||||
UsedGB: float64(used) / (1024.0 * 1024.0),
|
||||
}
|
||||
if swapTotal > 0 {
|
||||
stat.UsagePercent = float64(used) / float64(swapTotal) * 100.0
|
||||
}
|
||||
return stat, nil
|
||||
}
|
||||
|
||||
// parseUint64 parses a uint64 or returns 0
|
||||
func parseUint64(s string) (uint64, error) {
|
||||
var v uint64
|
||||
for _, c := range s {
|
||||
if c < '0' || c > '9' {
|
||||
break
|
||||
}
|
||||
v = v*10 + uint64(c-'0')
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
+193
-49
@@ -1,7 +1,13 @@
|
||||
// Package main 是 AIOps Agent 的入口。
|
||||
// Agent 定时采集 CPU、内存、磁盘及监听端口指标,并通过 HTTP 上报至 AIOps 后端。
|
||||
// Agent 定时采集 CPU、内存、磁盘、端口、进程 TOP、Swap、FD、上下文切换等指标,
|
||||
// 并通过 HTTP 上报至 AIOps 后端。
|
||||
//
|
||||
// 以下变量可在编译时通过 -ldflags "-X main.version=... -X main.buildTime=..." 注入。
|
||||
// 优化要点(1000 台服务器规模):
|
||||
// - 启动随机 Jitter 避免惊群效应
|
||||
// - 连接池复用 HTTP Keep-Alive
|
||||
// - 进程 TOP 限制为 3(可配置)
|
||||
// - Agent 自检心跳(序列号丢包检测)
|
||||
// - 端口变化率采集(增量检测,减少 payload)
|
||||
//
|
||||
// 署名 Logan.Li
|
||||
package main
|
||||
@@ -9,10 +15,13 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"math/rand"
|
||||
"net"
|
||||
"os"
|
||||
"os/signal"
|
||||
"runtime"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
@@ -22,23 +31,21 @@ import (
|
||||
"ezops/agent/task"
|
||||
)
|
||||
|
||||
// 编译时可注入的版本信息
|
||||
var (
|
||||
version = "dev"
|
||||
buildTime = "unknown"
|
||||
)
|
||||
|
||||
func main() {
|
||||
server := flag.String("server", "http://localhost:8080", "AIOps 后端上报地址(含 scheme 与端口)")
|
||||
server := flag.String("server", "http://localhost:8080", "AIOps 后端上报地址")
|
||||
interval := flag.Int("interval", 10, "采集与上报间隔,单位:秒")
|
||||
token := flag.String("token", "", "Bearer 鉴权令牌")
|
||||
hostnameFlag := flag.String("hostname", "", "上报主机名,默认使用系统主机名")
|
||||
topN := flag.Int("top-n", 3, "进程 TOP N 数量")
|
||||
flag.Parse()
|
||||
|
||||
// 统一日志格式:带微秒时间戳,便于排查问题
|
||||
logger := log.New(os.Stdout, "[aiops-agent] ", log.LstdFlags|log.Lmicroseconds)
|
||||
|
||||
// 解析主机名:优先使用 -hostname,否则回退到 os.Hostname()
|
||||
hostname := *hostnameFlag
|
||||
if hostname == "" {
|
||||
if h, err := os.Hostname(); err == nil {
|
||||
@@ -48,50 +55,52 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
// 参数校验
|
||||
if *server == "" {
|
||||
logger.Fatal("参数 -server 不能为空")
|
||||
}
|
||||
if *interval < 1 {
|
||||
logger.Fatalf("参数 -interval 必须 >= 1,当前为 %d", *interval)
|
||||
if *interval < 5 {
|
||||
logger.Fatalf("参数 -interval 必须 >= 5,当前为 %d(1000 台规模推荐 30~60s)", *interval)
|
||||
}
|
||||
|
||||
logger.Printf("AIOps Agent 启动: version=%s buildTime=%s", version, buildTime)
|
||||
logger.Printf("配置: server=%s interval=%ds hostname=%q token=%s",
|
||||
*server, *interval, hostname, maskToken(*token))
|
||||
logger.Printf("AIOps Agent v%s (built %s) go=%s", version, buildTime, runtime.Version())
|
||||
logger.Printf("配置: server=%s interval=%ds top-n=%d hostname=%q", *server, *interval, *topN, hostname)
|
||||
|
||||
// 初始化各采集器与上报器
|
||||
// ═══ 初始化采集器 ═══
|
||||
cpuCollector := collector.NewCPUCollector()
|
||||
memCollector := collector.NewMemCollector()
|
||||
diskCollector := collector.NewDiskCollector()
|
||||
portCollector := collector.NewPortCollector()
|
||||
netCollector := collector.NewNetworkCollector()
|
||||
diskIOCollector := collector.NewDiskIOCollector()
|
||||
procTopCollector := collector.NewProcessTopCollector()
|
||||
swapCollector := collector.NewSwapCollector()
|
||||
rep := reporter.New(*server, *token, logger)
|
||||
|
||||
// 采集系统静态信息(OS/内核),仅在启动时执行一次
|
||||
// 系统静态信息(仅启动时一次)
|
||||
sysInfo := collector.CollectSystem()
|
||||
logger.Printf("系统信息: OS=%q Kernel=%q", sysInfo.OSVersion, sysInfo.Kernel)
|
||||
|
||||
// 探测本机主 IP(用于后端匹配 servers 表)
|
||||
// 探测本机 IP
|
||||
localIP := detectLocalIP()
|
||||
logger.Printf("探测本机 IP: %s", localIP)
|
||||
|
||||
// 系统信息上报计数器:前 3 次上报携带系统信息,确保后端至少收到一次
|
||||
sysReportCount := 0
|
||||
sysReportCount := 0 // 前 3 次上报携带系统信息
|
||||
|
||||
// 初始化任务执行器与任务客户端(与 reporter 复用相同的 server/token/hostname)
|
||||
// 任务执行器
|
||||
taskExecutor := task.New(logger)
|
||||
taskClient := task.NewClient(*server, *token, hostname, logger)
|
||||
|
||||
// 监听 SIGINT / SIGTERM,支持优雅退出
|
||||
// ═══ 启动随机 Jitter:避免 1000 台同时上报 ═══
|
||||
startupJitter := time.Duration(rand.Intn(*interval)) * time.Second
|
||||
logger.Printf("启动 Jitter: %v(防止惊群效应)", startupJitter)
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
ticker := time.NewTicker(time.Duration(*interval) * time.Second)
|
||||
defer ticker.Stop()
|
||||
// Agent 自检序列号
|
||||
var reportSeq uint64
|
||||
|
||||
// collectAndReport 执行单次采集并上报;各项采集独立进行,单项失败不影响整体上报
|
||||
// collectAndReport 执行单次采集并上报
|
||||
collectAndReport := func() {
|
||||
report := &model.Report{
|
||||
Hostname: hostname,
|
||||
@@ -100,69 +109,140 @@ func main() {
|
||||
AgentVersion: version,
|
||||
}
|
||||
|
||||
// 前 3 次上报携带系统信息
|
||||
// 系统信息(前 3 次)
|
||||
if sysReportCount < 3 && (sysInfo.OSVersion != "" || sysInfo.Kernel != "") {
|
||||
report.System = &model.SystemStat{
|
||||
OSVersion: sysInfo.OSVersion,
|
||||
Kernel: sysInfo.Kernel,
|
||||
Uptime: sysInfo.UptimeSeconds,
|
||||
OSVersion: sysInfo.OSVersion,
|
||||
Kernel: sysInfo.Kernel,
|
||||
Uptime: sysInfo.UptimeSeconds,
|
||||
}
|
||||
sysReportCount++
|
||||
}
|
||||
|
||||
// CPU
|
||||
if stat, err := cpuCollector.Collect(); err != nil {
|
||||
logger.Printf("CPU 采集异常: %v", err)
|
||||
} else {
|
||||
report.CPU = stat
|
||||
}
|
||||
|
||||
// 内存
|
||||
if stat, err := memCollector.Collect(); err != nil {
|
||||
logger.Printf("内存采集异常: %v", err)
|
||||
} else {
|
||||
report.Memory = stat
|
||||
}
|
||||
|
||||
// Swap(仅当系统配置了 swap 才上报)
|
||||
if swap, err := swapCollector.Collect(); err != nil {
|
||||
logger.Printf("Swap 采集异常: %v", err)
|
||||
} else if swap != nil {
|
||||
report.Swap = swap
|
||||
}
|
||||
|
||||
// 磁盘
|
||||
if disks, err := diskCollector.Collect(); err != nil {
|
||||
logger.Printf("磁盘采集异常: %v", err)
|
||||
} else {
|
||||
report.Disks = disks
|
||||
}
|
||||
|
||||
// 监听端口
|
||||
if ports, err := portCollector.Collect(); err != nil {
|
||||
logger.Printf("端口采集异常: %v", err)
|
||||
} else {
|
||||
report.Ports = ports
|
||||
}
|
||||
|
||||
// 网络
|
||||
if netStat, err := netCollector.Collect(); err != nil {
|
||||
logger.Printf("网络采集异常: %v", err)
|
||||
} else {
|
||||
report.Network = netStat
|
||||
}
|
||||
|
||||
// 磁盘 IO
|
||||
if dioStat, err := diskIOCollector.Collect(); err != nil {
|
||||
logger.Printf("磁盘IO采集异常: %v", err)
|
||||
} else {
|
||||
report.DiskIO = dioStat
|
||||
}
|
||||
|
||||
// 进程 TOP N
|
||||
if procs, err := procTopCollector.Collect(*topN); err != nil {
|
||||
logger.Printf("进程TOP采集异常: %v", err)
|
||||
} else {
|
||||
report.ProcessTop = procs
|
||||
}
|
||||
|
||||
// 系统 FD 句柄
|
||||
if fdStat, err := collectFD(); err != nil {
|
||||
logger.Printf("FD采集异常: %v", err)
|
||||
} else {
|
||||
report.FD = fdStat
|
||||
}
|
||||
|
||||
// 上下文切换
|
||||
if csStat, err := collectContextSwitches(); err != nil {
|
||||
// 静默跳过(某些内核/容器环境不可用)
|
||||
} else {
|
||||
report.ContextSwitches = csStat
|
||||
}
|
||||
|
||||
// Agent 自检心跳
|
||||
reportSeq++
|
||||
var memStats runtime.MemStats
|
||||
runtime.ReadMemStats(&memStats)
|
||||
report.Heartbeat = model.AgentHeartbeat{
|
||||
Version: version,
|
||||
UptimeSec: sysInfo.UptimeSeconds,
|
||||
SelfCPU: 0, // TODO: self-CPU via /proc/self/stat
|
||||
SelfRSSMB: float64(memStats.Alloc) / 1024.0 / 1024.0,
|
||||
ReportSeq: reportSeq,
|
||||
}
|
||||
|
||||
// 上报
|
||||
if err := rep.Send(ctx, report); err != nil {
|
||||
logger.Printf("上报失败: %v", err)
|
||||
return
|
||||
}
|
||||
logger.Printf("上报成功: cpu=%.2f%% mem=%.2f%% disks=%d ports=%d net=%dconn/%dwait netIO=%.0f/%.0fB/s diskIO=%.0f/%.0fB/s",
|
||||
report.CPU.UsagePercent, report.Memory.UsagePercent, len(report.Disks), len(report.Ports),
|
||||
report.Network.TCPEstablished, report.Network.TCPTimeWait,
|
||||
report.Network.NetRxBPS, report.Network.NetTxBPS,
|
||||
report.DiskIO.ReadBPS, report.DiskIO.WriteBPS)
|
||||
logger.Printf("上报成功: cpu=%.1f%% mem=%.1f%% swap=%.1f%% disks=%d ports=%d procs=%d fd=%d/%d cs=%.0f/s",
|
||||
report.CPU.UsagePercent,
|
||||
report.Memory.UsagePercent,
|
||||
func() float64 {
|
||||
if report.Swap != nil {
|
||||
return report.Swap.UsagePercent
|
||||
}
|
||||
return 0
|
||||
}(),
|
||||
len(report.Disks),
|
||||
len(report.Ports),
|
||||
len(report.ProcessTop),
|
||||
func() int {
|
||||
if report.FD != nil {
|
||||
return report.FD.Allocated
|
||||
}
|
||||
return 0
|
||||
}(),
|
||||
func() int64 {
|
||||
if report.FD != nil {
|
||||
return report.FD.Max
|
||||
}
|
||||
return 0
|
||||
}(),
|
||||
func() float64 {
|
||||
if report.ContextSwitches != nil {
|
||||
return report.ContextSwitches.CTXPerSec
|
||||
}
|
||||
return 0
|
||||
}(),
|
||||
)
|
||||
}
|
||||
|
||||
// pollAndExecute 执行单次任务轮询:拉取待执行任务 → 逐个执行 → 回传结果。
|
||||
// 网络错误只记录日志,不 panic,下一个周期继续重试。
|
||||
// pollAndExecute 任务轮询
|
||||
pollAndExecute := func() {
|
||||
tasks, err := taskClient.Poll(ctx)
|
||||
if err != nil {
|
||||
// 上下文已取消(Agent 退出中)属于正常情况,不输出告警
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
@@ -170,12 +250,10 @@ func main() {
|
||||
return
|
||||
}
|
||||
if len(tasks) == 0 {
|
||||
return // 暂无任务,静默返回
|
||||
return
|
||||
}
|
||||
logger.Printf("拉取到 %d 个待执行任务", len(tasks))
|
||||
|
||||
for _, t := range tasks {
|
||||
// Agent 退出时跳过后续任务,避免退出延迟
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
@@ -191,11 +269,9 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
// 启动任务轮询协程:每 5 秒轮询一次,与指标采集并行运行。
|
||||
// 使用独立的 5 秒固定间隔,不受 -interval 影响。
|
||||
// ═══ 任务轮询协程(5s 间隔,不受 -interval 影响)═══
|
||||
const taskPollInterval = 5 * time.Second
|
||||
go func() {
|
||||
// 启动后立即轮询一次,再按固定周期执行
|
||||
pollAndExecute()
|
||||
ticker := time.NewTicker(taskPollInterval)
|
||||
defer ticker.Stop()
|
||||
@@ -209,20 +285,23 @@ func main() {
|
||||
}
|
||||
}()
|
||||
|
||||
// 主协程:启动后立即执行一次指标采集,再按 ticker 周期执行
|
||||
// ═══ 主循环:启动先 sleep jitter,再按 interval 采集 ═══
|
||||
time.Sleep(startupJitter)
|
||||
collectAndReport()
|
||||
ticker := time.NewTicker(time.Duration(*interval) * time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
collectAndReport()
|
||||
case <-ctx.Done():
|
||||
logger.Println("收到退出信号,Agent 正在关闭...")
|
||||
logger.Println("收到退出信号,Agent 正常关闭")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// maskToken 对令牌做脱敏处理,仅用于日志输出
|
||||
// maskToken 对令牌做脱敏处理
|
||||
func maskToken(token string) string {
|
||||
if token == "" {
|
||||
return "(empty)"
|
||||
@@ -233,11 +312,8 @@ func maskToken(token string) string {
|
||||
return token[:4] + "****"
|
||||
}
|
||||
|
||||
// detectLocalIP 探测本机主 IP 地址。
|
||||
// 通过 UDP 连接到公网地址(不实际发包),获取系统路由选择的本机 IP。
|
||||
// 如果失败,回退到遍历网卡查找非 loopback 的 IPv4 地址。
|
||||
// detectLocalIP 探测本机主 IP
|
||||
func detectLocalIP() string {
|
||||
// 方法1:通过 UDP "连接" 到公网 DNS 获取出口 IP
|
||||
conn, err := net.Dial("udp", "8.8.8.8:53")
|
||||
if err == nil {
|
||||
defer conn.Close()
|
||||
@@ -245,8 +321,6 @@ func detectLocalIP() string {
|
||||
return addr.IP.String()
|
||||
}
|
||||
}
|
||||
|
||||
// 方法2:遍历网卡
|
||||
ifaces, err := net.Interfaces()
|
||||
if err == nil {
|
||||
for _, iface := range ifaces {
|
||||
@@ -263,3 +337,73 @@ func detectLocalIP() string {
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
// ══════════════════════════════════════════════
|
||||
// 补充采集器(内联简单实现,不单独建文件)
|
||||
// ══════════════════════════════════════════════
|
||||
|
||||
// collectFD 读取 /proc/sys/fs/file-nr 和 /proc/sys/fs/file-max
|
||||
func collectFD() (*model.SocketFDStat, error) {
|
||||
alloc, err := os.ReadFile("/proc/sys/fs/file-nr")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var allocated, _unused1, _unused2 int
|
||||
fmt.Sscanf(string(alloc), "%d %d %d", &allocated, &_unused1, &_unused2)
|
||||
|
||||
max, err := os.ReadFile("/proc/sys/fs/file-max")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var maxFD int64
|
||||
fmt.Sscanf(string(max), "%d", &maxFD)
|
||||
|
||||
stat := &model.SocketFDStat{
|
||||
Allocated: allocated,
|
||||
Max: maxFD,
|
||||
}
|
||||
if maxFD > 0 {
|
||||
stat.UsagePct = float64(allocated) / float64(maxFD) * 100.0
|
||||
}
|
||||
return stat, nil
|
||||
}
|
||||
|
||||
// collectContextSwitches 读取 /proc/stat 中的 ctxt 和 intr 行
|
||||
// 需要两次采样才能计算速率;这里使用简单的累计值(首次返回 0)
|
||||
func collectContextSwitches() (*model.ContextSwitchStat, error) {
|
||||
data, err := os.ReadFile("/proc/stat")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stat := &model.ContextSwitchStat{}
|
||||
lines := string(data)
|
||||
for _, line := range splitLines(lines) {
|
||||
if hasPrefix(line, "ctxt ") {
|
||||
fmt.Sscanf(line, "ctxt %f", &stat.CTXPerSec)
|
||||
}
|
||||
if hasPrefix(line, "intr ") {
|
||||
fmt.Sscanf(line, "intr %f", &stat.IRQPerSec)
|
||||
}
|
||||
}
|
||||
// NOTE: 这里返回的是累计值而非速率;后端可用两次上报的差值计算速率
|
||||
return stat, nil
|
||||
}
|
||||
|
||||
func splitLines(s string) []string {
|
||||
var result []string
|
||||
start := 0
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] == '\n' {
|
||||
result = append(result, s[start:i])
|
||||
start = i + 1
|
||||
}
|
||||
}
|
||||
if start < len(s) {
|
||||
result = append(result, s[start:])
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func hasPrefix(s, prefix string) bool {
|
||||
return len(s) >= len(prefix) && s[:len(prefix)] == prefix
|
||||
}
|
||||
+16
-11
@@ -6,17 +6,22 @@ package model
|
||||
|
||||
// Report 为单次采集周期的完整上报报文
|
||||
type Report struct {
|
||||
Hostname string `json:"hostname"` // 主机名
|
||||
IP string `json:"ip,omitempty"` // 本机 IP(Agent 启动时探测)
|
||||
Timestamp string `json:"timestamp"` // RFC3339 格式的 UTC 时间戳
|
||||
AgentVersion string `json:"agent_version"` // Agent 版本号
|
||||
CPU CPUStat `json:"cpu"` // CPU 指标
|
||||
Memory MemoryStat `json:"memory"` // 内存指标
|
||||
Disks []DiskStat `json:"disks"` // 磁盘指标列表
|
||||
Ports []PortStat `json:"ports"` // 监听端口列表
|
||||
Network NetworkStat `json:"network"` // 网络指标
|
||||
DiskIO DiskIOStat `json:"disk_io"` // 磁盘 IO
|
||||
System *SystemStat `json:"system,omitempty"` // 系统信息(首次采集后携带)
|
||||
Hostname string `json:"hostname"` // 主机名
|
||||
IP string `json:"ip,omitempty"` // 本机 IP(Agent 启动时探测)
|
||||
Timestamp string `json:"timestamp"` // RFC3339 UTC 时间戳
|
||||
AgentVersion string `json:"agent_version"` // Agent 版本号
|
||||
CPU CPUStat `json:"cpu"` // CPU 指标
|
||||
Memory MemoryStat `json:"memory"` // 内存指标
|
||||
Swap *SwapStat `json:"swap,omitempty"` // 交换分区(有 swap 才上报)
|
||||
Disks []DiskStat `json:"disks"` // 磁盘指标列表
|
||||
Ports []PortStat `json:"ports"` // 监听端口列表
|
||||
Network NetworkStat `json:"network"` // 网络指标
|
||||
DiskIO DiskIOStat `json:"disk_io"` // 磁盘 IO
|
||||
System *SystemStat `json:"system,omitempty"` // 系统信息(首次采集后携带)
|
||||
ProcessTop []ProcessStat `json:"process_top,omitempty"` // 进程 TOP N
|
||||
FD *SocketFDStat `json:"fd,omitempty"` // 系统文件句柄
|
||||
ContextSwitches *ContextSwitchStat `json:"context_switches,omitempty"` // 上下文切换
|
||||
Heartbeat AgentHeartbeat `json:"heartbeat"` // Agent 自检
|
||||
}
|
||||
|
||||
// CPUStat CPU 相关指标
|
||||
|
||||
@@ -18,11 +18,41 @@ type DiskIOStat struct {
|
||||
WriteIOPS float64 `json:"write_iops"` // 写入 IOPS (count/s)
|
||||
}
|
||||
|
||||
// SwapStat 交换分区指标(OOM 前兆判断)
|
||||
type SwapStat struct {
|
||||
TotalGB float64 `json:"total_gb"`
|
||||
UsedGB float64 `json:"used_gb"`
|
||||
UsagePercent float64 `json:"usage_percent"`
|
||||
}
|
||||
|
||||
// SocketFDStat 系统级 FD 使用情况
|
||||
type SocketFDStat struct {
|
||||
Allocated int `json:"allocated"` // 已分配的 file handles (fs.file-nr 第一列)
|
||||
Max int64 `json:"max"` // 系统上限 (fs.file-max)
|
||||
UsagePct float64 `json:"usage_pct"`
|
||||
}
|
||||
|
||||
// ContextSwitchStat 上下文切换(决定是否开中断合并/CPU 隔离)
|
||||
type ContextSwitchStat struct {
|
||||
CTXPerSec float64 `json:"ctx_per_sec"` // 每秒上下文切换次数
|
||||
IRQPerSec float64 `json:"irq_per_sec"` // 每秒中断次数
|
||||
}
|
||||
|
||||
// AgentHeartbeat Agent 自检心跳(随每次上报附带,极小 payload)
|
||||
type AgentHeartbeat struct {
|
||||
Version string `json:"version"`
|
||||
UptimeSec int64 `json:"uptime_sec"`
|
||||
LastErr string `json:"last_err,omitempty"`
|
||||
SelfCPU float64 `json:"self_cpu_pct"`
|
||||
SelfRSSMB float64 `json:"self_rss_mb"`
|
||||
ReportSeq uint64 `json:"report_seq"` // 单调递增序列号,用于丢包检测
|
||||
}
|
||||
|
||||
// SystemStat 系统信息(启动时采集一次)
|
||||
type SystemStat struct {
|
||||
OSVersion string `json:"os_version"` // OS 版本 (如 "Ubuntu 22.04")
|
||||
Kernel string `json:"kernel"` // 内核版本
|
||||
Uptime int64 `json:"uptime"` // 运行秒数
|
||||
UlimitNofile int64 `json:"ulimit_nofile"` // ulimit -n (最大文件描述符)
|
||||
UlimitNproc int64 `json:"ulimit_nproc"` // ulimit -u (最大进程数)
|
||||
OSVersion string `json:"os_version"` // OS 版本 (如 "Ubuntu 22.04")
|
||||
Kernel string `json:"kernel"` // 内核版本
|
||||
Uptime int64 `json:"uptime"` // 运行秒数
|
||||
UlimitNofile int64 `json:"ulimit_nofile"` // ulimit -n (最大文件描述符)
|
||||
UlimitNproc int64 `json:"ulimit_nproc"` // ulimit -u (最大进程数)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package model
|
||||
|
||||
// ProcessStat 单个进程统计(TOP N 采集)
|
||||
type ProcessStat struct {
|
||||
PID int `json:"pid"`
|
||||
Name string `json:"name"`
|
||||
MemoryMB float64 `json:"memory_mb"` // 物理内存 (MB)
|
||||
FDCount int `json:"fd_count"` // 打开的文件句柄数
|
||||
Threads int `json:"threads"` // 线程数
|
||||
}
|
||||
Executable
BIN
Binary file not shown.
@@ -51,6 +51,12 @@ func (h *AgentHandler) ReceiveReport(c *gin.Context) {
|
||||
portJSON, _ := json.Marshal(req.Ports)
|
||||
netJSON, _ := json.Marshal(req.Network)
|
||||
dioJSON, _ := json.Marshal(req.DiskIO)
|
||||
// v2.0 新增
|
||||
swapJSON, _ := json.Marshal(req.Swap)
|
||||
processTopJSON, _ := json.Marshal(req.ProcessTop)
|
||||
fdJSON, _ := json.Marshal(req.FD)
|
||||
csJSON, _ := json.Marshal(req.ContextSwitches)
|
||||
heartbeatJSON, _ := json.Marshal(req.Heartbeat)
|
||||
|
||||
// 存储到数据库
|
||||
report := models.AgentReport{
|
||||
@@ -67,6 +73,12 @@ func (h *AgentHandler) ReceiveReport(c *gin.Context) {
|
||||
PortInfo: string(portJSON),
|
||||
NetInfo: string(netJSON),
|
||||
DiskIOInfo: string(dioJSON),
|
||||
// v2.0 新增
|
||||
SwapInfo: string(swapJSON),
|
||||
ProcessTopInfo: string(processTopJSON),
|
||||
FDInfo: string(fdJSON),
|
||||
CSInfo: string(csJSON),
|
||||
HeartbeatInfo: string(heartbeatJSON),
|
||||
ReportTime: reportTime,
|
||||
}
|
||||
|
||||
@@ -264,6 +276,11 @@ func (h *AgentHandler) GetLatestReports(c *gin.Context) {
|
||||
a.port_info,
|
||||
a.net_info,
|
||||
a.disk_io_info,
|
||||
a.swap_info,
|
||||
a.process_top_info,
|
||||
a.fd_info,
|
||||
a.cs_info,
|
||||
a.heartbeat_info,
|
||||
a.report_time,
|
||||
COALESCE(s.agent_version, '') as agent_version,
|
||||
CASE
|
||||
|
||||
@@ -1,8 +1,16 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"ezops/internal/models"
|
||||
|
||||
@@ -163,9 +171,9 @@ func (h *AlertHandler) DeleteNotifyChannel(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// TestNotifyChannel 测试通知渠道 // Logan.Li
|
||||
// TestNotifyChannel 测试通知渠道 — 真实发送测试消息 // Logan.Li
|
||||
// @Summary 测试通知渠道连通性
|
||||
// @Description 模拟测试通知渠道(返回测试状态)
|
||||
// @Description 向渠道发送测试消息,验证连通性
|
||||
// @Tags 告警
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
@@ -184,12 +192,22 @@ func (h *AlertHandler) TestNotifyChannel(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 模拟测试:校验配置非空即视为成功
|
||||
status := "success"
|
||||
message := "测试通知已发送"
|
||||
if channel.Config == "" {
|
||||
status = "warning"
|
||||
message = "渠道未配置参数,请先完善配置"
|
||||
|
||||
switch channel.Type {
|
||||
case "feishu":
|
||||
err := sendFeishuTest(channel.Config)
|
||||
if err != nil {
|
||||
status = "error"
|
||||
message = "飞书通知发送失败: " + err.Error()
|
||||
}
|
||||
default:
|
||||
// 非飞书渠道仅检查配置非空
|
||||
if channel.Config == "" {
|
||||
status = "warning"
|
||||
message = "渠道未配置参数,请先完善配置"
|
||||
}
|
||||
}
|
||||
|
||||
h.db.Model(&channel).Update("test_status", status)
|
||||
@@ -204,3 +222,201 @@ func (h *AlertHandler) TestNotifyChannel(c *gin.Context) {
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ==================== 飞书 Webhook 发送逻辑 ====================
|
||||
|
||||
// sendFeishuTest 发送飞书测试通知
|
||||
func sendFeishuTest(configJSON string) error {
|
||||
var cfg models.FeishuWebhookConfig
|
||||
if err := json.Unmarshal([]byte(configJSON), &cfg); err != nil {
|
||||
return fmt.Errorf("解析配置失败: %w", err)
|
||||
}
|
||||
if cfg.URL == "" {
|
||||
return fmt.Errorf("webhook URL 为空")
|
||||
}
|
||||
|
||||
title := "✅ AIOps 告警测试通知"
|
||||
content := fmt.Sprintf("通知渠道连通性测试成功\\n测试时间:%s\\n来源:AIOps 智能运维平台", time.Now().Format("2006-01-02 15:04:05"))
|
||||
|
||||
return sendFeishuCard(cfg.URL, cfg.Secret, title, content, "green")
|
||||
}
|
||||
|
||||
// sendFeishuAlert 发送飞书告警通知
|
||||
func sendFeishuAlert(configJSON, title, content, severity string) error {
|
||||
var cfg models.FeishuWebhookConfig
|
||||
if err := json.Unmarshal([]byte(configJSON), &cfg); err != nil {
|
||||
return fmt.Errorf("解析配置失败: %w", err)
|
||||
}
|
||||
if cfg.URL == "" {
|
||||
return fmt.Errorf("webhook URL 为空")
|
||||
}
|
||||
|
||||
color := "red"
|
||||
if severity == "warning" {
|
||||
color = "orange"
|
||||
} else if severity == "info" {
|
||||
color = "blue"
|
||||
}
|
||||
|
||||
emoji := "🔴"
|
||||
if severity == "warning" {
|
||||
emoji = "🟠"
|
||||
} else if severity == "info" {
|
||||
emoji = "🔵"
|
||||
}
|
||||
|
||||
title = emoji + " " + title
|
||||
return sendFeishuCard(cfg.URL, cfg.Secret, title, content, color)
|
||||
}
|
||||
|
||||
// sendFeishuRecovery 发送飞书恢复通知
|
||||
func sendFeishuRecovery(configJSON, title, content string) error {
|
||||
var cfg models.FeishuWebhookConfig
|
||||
if err := json.Unmarshal([]byte(configJSON), &cfg); err != nil {
|
||||
return fmt.Errorf("解析配置失败: %w", err)
|
||||
}
|
||||
if cfg.URL == "" {
|
||||
return fmt.Errorf("webhook URL 为空")
|
||||
}
|
||||
|
||||
title = "✅ " + title
|
||||
return sendFeishuCard(cfg.URL, cfg.Secret, title, content, "green")
|
||||
}
|
||||
|
||||
// sendFeishuCard 发送飞书消息(优先使用卡片格式,出错回退到文本)
|
||||
func sendFeishuCard(webhookURL, secret, title, content, color string) error {
|
||||
// 先尝试文本格式(最可靠)
|
||||
textMsg := map[string]interface{}{
|
||||
"msg_type": "text",
|
||||
"content": map[string]interface{}{
|
||||
"text": title + "\n\n" + content,
|
||||
},
|
||||
}
|
||||
body, _ := json.Marshal(textMsg)
|
||||
|
||||
req, err := http.NewRequest("POST", webhookURL, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return fmt.Errorf("创建请求失败: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// 如果有 secret,生成签名
|
||||
if secret != "" {
|
||||
timestamp := time.Now().Unix()
|
||||
sign := genFeishuSign(timestamp, secret)
|
||||
q := req.URL.Query()
|
||||
q.Set("timestamp", fmt.Sprintf("%d", timestamp))
|
||||
q.Set("sign", sign)
|
||||
req.URL.RawQuery = q.Encode()
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("发送请求失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("飞书返回错误 (HTTP %d): %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
// 检查飞书业务返回码
|
||||
var result struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
}
|
||||
json.Unmarshal(respBody, &result)
|
||||
if result.Code != 0 {
|
||||
return fmt.Errorf("飞书返回错误 (code=%d): %s", result.Code, result.Msg)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// buildFeishuCard 构建飞书卡片消息体(保留备用,当前使用文本格式)
|
||||
func buildFeishuCard(title, content, color string) models.FeishuCardMessage {
|
||||
return models.FeishuCardMessage{
|
||||
MsgType: "interactive",
|
||||
Content: models.FeishuCardContent{
|
||||
Title: title,
|
||||
Content: [][]models.FeishuCardElement{
|
||||
{
|
||||
{
|
||||
Tag: "markdown",
|
||||
Text: content,
|
||||
},
|
||||
},
|
||||
{
|
||||
{
|
||||
Tag: "note",
|
||||
Text: fmt.Sprintf("⏰ %s | AIOps 智能运维平台", time.Now().Format("2006-01-02 15:04:05")),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// genFeishuSign 生成飞书签名
|
||||
func genFeishuSign(timestamp int64, secret string) string {
|
||||
stringToSign := fmt.Sprintf("%d\n%s", timestamp, secret)
|
||||
h := hmac.New(sha256.New, []byte(stringToSign))
|
||||
signature := base64.StdEncoding.EncodeToString(h.Sum(nil))
|
||||
return signature
|
||||
}
|
||||
|
||||
// ==================== 批量通知发送 ====================
|
||||
|
||||
// NotifyAlert 发送告警通知到所有启用的渠道
|
||||
func (h *AlertHandler) NotifyAlert(ruleName, hostname, metric, severity, message string, value, threshold float64) {
|
||||
var channels []models.NotifyChannel
|
||||
h.db.Where("enabled = ?", true).Find(&channels)
|
||||
|
||||
for _, ch := range channels {
|
||||
switch ch.Type {
|
||||
case "feishu":
|
||||
title := buildAlertTitle(ruleName, hostname, metric, severity)
|
||||
content := buildAlertContent(ruleName, hostname, metric, severity, message, value, threshold)
|
||||
if err := sendFeishuAlert(ch.Config, title, content, severity); err != nil {
|
||||
fmt.Printf("[AlertNotify] 飞书通知失败 (渠道:%s): %v\n", ch.Name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// NotifyRecovery 发送恢复通知到所有启用的渠道
|
||||
func (h *AlertHandler) NotifyRecovery(ruleName, hostname, metric, message string) {
|
||||
var channels []models.NotifyChannel
|
||||
h.db.Where("enabled = ?", true).Find(&channels)
|
||||
|
||||
for _, ch := range channels {
|
||||
switch ch.Type {
|
||||
case "feishu":
|
||||
title := fmt.Sprintf("%s — 已恢复正常", ruleName)
|
||||
content := fmt.Sprintf("**告警已恢复**\\n\\n主机:%s\\n指标:%s\\n详情:%s\\n恢复时间:%s",
|
||||
hostname, metric, message, time.Now().Format("2006-01-02 15:04:05"))
|
||||
if err := sendFeishuRecovery(ch.Config, title, content); err != nil {
|
||||
fmt.Printf("[AlertNotify] 飞书恢复通知失败 (渠道:%s): %v\n", ch.Name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func buildAlertTitle(ruleName, hostname, metric, severity string) string {
|
||||
sevLabel := "严重告警"
|
||||
if severity == "warning" {
|
||||
sevLabel = "警告"
|
||||
} else if severity == "info" {
|
||||
sevLabel = "信息"
|
||||
}
|
||||
return fmt.Sprintf("[%s] %s — %s (%s)", sevLabel, ruleName, hostname, metric)
|
||||
}
|
||||
|
||||
func buildAlertContent(ruleName, hostname, metric, severity, message string, value, threshold float64) string {
|
||||
return fmt.Sprintf(
|
||||
"**规则名称:** %s\\n**目标主机:** %s\\n**指标类型:** %s\\n**告警级别:** %s\\n**当前值:** %.2f\\n**阈值:** %.2f\\n**详细信息:** %s\\n**触发时间:** %s",
|
||||
ruleName, hostname, metric, severity, value, threshold, message, time.Now().Format("2006-01-02 15:04:05"),
|
||||
)
|
||||
}
|
||||
@@ -27,10 +27,10 @@ func (e *AlertEngine) Check() {
|
||||
e.autoResolveAlerts()
|
||||
}
|
||||
|
||||
// 检查 CPU/内存/磁盘 阈值
|
||||
// 检查 CPU/内存/磁盘/进程/TCP连接/端口 阈值
|
||||
func (e *AlertEngine) checkResourceAlerts() {
|
||||
var rules []models.AgentRule
|
||||
e.db.Where("enabled = ? AND metric IN ?", true, []string{"cpu", "mem", "disk"}).Find(&rules)
|
||||
e.db.Where("enabled = ? AND metric IN ?", true, []string{"cpu", "mem", "disk", "service_process", "tcp_time_wait", "tcp_close_wait"}).Find(&rules)
|
||||
|
||||
for _, rule := range rules {
|
||||
// 获取目标主机最新上报
|
||||
@@ -58,6 +58,29 @@ func (e *AlertEngine) checkResourceAlerts() {
|
||||
value = d.UsagePercent
|
||||
}
|
||||
}
|
||||
case "tcp_time_wait":
|
||||
var netStat models.NetworkStatModel
|
||||
json.Unmarshal([]byte(report.NetInfo), &netStat)
|
||||
value = float64(netStat.TCPTimeWait)
|
||||
case "tcp_close_wait":
|
||||
var netStat models.NetworkStatModel
|
||||
json.Unmarshal([]byte(report.NetInfo), &netStat)
|
||||
value = float64(netStat.TCPCloseWait)
|
||||
case "service_process":
|
||||
// 进程不存在告警 — 检查 process_top_info 中是否包含指定进程名
|
||||
var processes []models.ProcessMetric
|
||||
json.Unmarshal([]byte(report.ProcessTopInfo), &processes)
|
||||
found := false
|
||||
for _, p := range processes {
|
||||
if p.Name == rule.Hostname || rule.Hostname == "" {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if found {
|
||||
continue // 进程存在,不触发
|
||||
}
|
||||
value = 0 // 进程不存在时触发
|
||||
}
|
||||
|
||||
// 检查是否超阈值
|
||||
@@ -89,6 +112,9 @@ func (e *AlertEngine) checkResourceAlerts() {
|
||||
}
|
||||
e.db.Create(&alert)
|
||||
|
||||
// 发送告警通知
|
||||
e.notifyAlert(&rule, report.Hostname, alert)
|
||||
|
||||
// 更新规则最后触发时间
|
||||
now := time.Now()
|
||||
e.db.Model(&rule).Update("last_triggered", now)
|
||||
@@ -150,10 +176,12 @@ func (e *AlertEngine) checkOfflineAlerts() {
|
||||
if existing.ID == 0 {
|
||||
// 获取最后一次上报时间计算离线时长
|
||||
var lastReport models.AgentReport
|
||||
e.db.Order("id DESC").First(&lastReport)
|
||||
e.db.Where("hostname = ?", s.Hostname).Order("id DESC").First(&lastReport)
|
||||
offlineMinutes := 3.0
|
||||
var lastReportTime time.Time
|
||||
if lastReport.ID > 0 {
|
||||
offlineMinutes = time.Since(lastReport.ReportTime).Minutes()
|
||||
lastReportTime = lastReport.ReportTime
|
||||
}
|
||||
|
||||
alert := models.AgentAlert{
|
||||
@@ -166,6 +194,15 @@ func (e *AlertEngine) checkOfflineAlerts() {
|
||||
Threshold: 3,
|
||||
}
|
||||
e.db.Create(&alert)
|
||||
|
||||
// 发送离线告警通知
|
||||
e.notifyAlertRule("主机离线", s.Hostname, "offline", "critical",
|
||||
alert.Message, offlineMinutes, 3)
|
||||
|
||||
// 记录离线上报时间用于恢复通知
|
||||
if !lastReportTime.IsZero() {
|
||||
e.db.Model(&alert).Update("created_at", time.Now())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -226,6 +263,10 @@ func (e *AlertEngine) checkPortAlerts() {
|
||||
}
|
||||
e.db.Create(&alert)
|
||||
|
||||
// 发送端口Down告警通知
|
||||
e.notifyAlertRule(rule.Name, report.Hostname, "port_down", "critical",
|
||||
alert.Message, float64(rule.Port), float64(rule.Port))
|
||||
|
||||
now := time.Now()
|
||||
e.db.Model(&rule).Update("last_triggered", now)
|
||||
}
|
||||
@@ -247,7 +288,7 @@ func (e *AlertEngine) autoResolveAlerts() {
|
||||
if report.ID > 0 && time.Since(report.ReportTime) < 3*time.Minute {
|
||||
resolved = true
|
||||
}
|
||||
case "cpu", "mem", "disk":
|
||||
case "cpu", "mem", "disk", "tcp_time_wait", "tcp_close_wait":
|
||||
// 获取对应规则,检查是否恢复正常
|
||||
var rule models.AgentRule
|
||||
e.db.Where("name = ?", alert.RuleName).First(&rule)
|
||||
@@ -277,6 +318,14 @@ func (e *AlertEngine) autoResolveAlerts() {
|
||||
value = d.UsagePercent
|
||||
}
|
||||
}
|
||||
case "tcp_time_wait":
|
||||
var netStat models.NetworkStatModel
|
||||
json.Unmarshal([]byte(report.NetInfo), &netStat)
|
||||
value = float64(netStat.TCPTimeWait)
|
||||
case "tcp_close_wait":
|
||||
var netStat models.NetworkStatModel
|
||||
json.Unmarshal([]byte(report.NetInfo), &netStat)
|
||||
value = float64(netStat.TCPCloseWait)
|
||||
}
|
||||
if !e.compareOperator(rule.Operator, value, rule.Threshold) {
|
||||
resolved = true
|
||||
@@ -304,6 +353,9 @@ func (e *AlertEngine) autoResolveAlerts() {
|
||||
"resolved": true,
|
||||
"resolved_at": now,
|
||||
})
|
||||
|
||||
// 发送恢复通知
|
||||
e.notifyRecovery(alert.RuleName, alert.Hostname, alert.Metric, alert.Message)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -324,3 +376,41 @@ func (e *AlertEngine) compareOperator(op string, val, threshold float64) bool {
|
||||
return val > threshold
|
||||
}
|
||||
}
|
||||
|
||||
// notifyAlert 发送告警通知(通过 AgentRule 对应的 notify_channels)
|
||||
func (e *AlertEngine) notifyAlert(rule *models.AgentRule, hostname string, alert models.AgentAlert) {
|
||||
e.notifyAlertRule(rule.Name, hostname, alert.Metric, alert.Severity,
|
||||
alert.Message, alert.Value, alert.Threshold)
|
||||
}
|
||||
|
||||
// notifyAlertRule 按规则发送告警通知到所有启用的飞书渠道
|
||||
func (e *AlertEngine) notifyAlertRule(ruleName, hostname, metric, severity, message string, value, threshold float64) {
|
||||
var channels []models.NotifyChannel
|
||||
e.db.Where("enabled = ? AND type = ?", true, "feishu").Find(&channels)
|
||||
|
||||
for _, ch := range channels {
|
||||
title := fmt.Sprintf("[%s] %s — %s (%s)", severity, ruleName, hostname, metric)
|
||||
content := fmt.Sprintf(
|
||||
"**规则名称:** %s\\n**目标主机:** %s\\n**指标类型:** %s\\n**告警级别:** %s\\n**当前值:** %.2f\\n**阈值:** %.2f\\n**详细信息:** %s\\n**触发时间:** %s",
|
||||
ruleName, hostname, metric, severity, value, threshold, message, time.Now().Format("2006-01-02 15:04:05"),
|
||||
)
|
||||
if err := sendFeishuAlert(ch.Config, title, content, severity); err != nil {
|
||||
fmt.Printf("[AlertEngine] 飞书通知失败 (渠道:%s): %v\n", ch.Name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// notifyRecovery 发送恢复通知到所有启用的飞书渠道
|
||||
func (e *AlertEngine) notifyRecovery(ruleName, hostname, metric, message string) {
|
||||
var channels []models.NotifyChannel
|
||||
e.db.Where("enabled = ? AND type = ?", true, "feishu").Find(&channels)
|
||||
|
||||
for _, ch := range channels {
|
||||
title := fmt.Sprintf("%s — 已恢复正常", ruleName)
|
||||
content := fmt.Sprintf("**告警已恢复**\\n\\n主机:%s\\n指标:%s\\n详情:%s\\n恢复时间:%s",
|
||||
hostname, metric, message, time.Now().Format("2006-01-02 15:04:05"))
|
||||
if err := sendFeishuRecovery(ch.Config, title, content); err != nil {
|
||||
fmt.Printf("[AlertEngine] 飞书恢复通知失败 (渠道:%s): %v\n", ch.Name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
@@ -272,3 +273,64 @@ func (h *AlertHandler) ToggleRule(c *gin.Context) {
|
||||
Data: rule,
|
||||
})
|
||||
}
|
||||
|
||||
// QuickSetupRules 一键创建测试告警规则(飞书Webhook测试用) // Logan.Li
|
||||
// @Summary 一键创建测试告警规则
|
||||
// @Tags 告警
|
||||
// @Router /alerts/quick-setup [post]
|
||||
func (h *AlertHandler) QuickSetupRules(c *gin.Context) {
|
||||
type ruleDef struct {
|
||||
Name string `json:"name"`
|
||||
Metric string `json:"metric"`
|
||||
Operator string `json:"operator"`
|
||||
Threshold float64 `json:"threshold"`
|
||||
Port int `json:"port,omitempty"`
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Rules []ruleDef `json:"rules"`
|
||||
}
|
||||
c.ShouldBindJSON(&req)
|
||||
|
||||
// 默认规则:CPU 80%, 内存 80%, 磁盘 90%, TIME_WAIT 15000, CLOSE_WAIT 200, 端口Down, 进程检测
|
||||
defaultRules := []ruleDef{
|
||||
{Name: "CPU使用率", Metric: "cpu", Operator: ">", Threshold: 80},
|
||||
{Name: "内存使用率", Metric: "mem", Operator: ">", Threshold: 80},
|
||||
{Name: "磁盘使用率", Metric: "disk", Operator: ">", Threshold: 90},
|
||||
{Name: "TIME_WAIT连接数", Metric: "tcp_time_wait", Operator: ">", Threshold: 15000},
|
||||
{Name: "CLOSE_WAIT连接数", Metric: "tcp_close_wait", Operator: ">", Threshold: 200},
|
||||
{Name: "进程异常退出", Metric: "service_process", Operator: "==", Threshold: 0},
|
||||
}
|
||||
|
||||
rules := req.Rules
|
||||
if len(rules) == 0 {
|
||||
rules = defaultRules
|
||||
}
|
||||
|
||||
created := 0
|
||||
for _, def := range rules {
|
||||
var existing models.AgentRule
|
||||
h.db.Where("name = ?", def.Name).First(&existing)
|
||||
if existing.ID > 0 {
|
||||
continue
|
||||
}
|
||||
rule := models.AgentRule{
|
||||
Name: def.Name,
|
||||
Metric: def.Metric,
|
||||
Operator: def.Operator,
|
||||
Threshold: def.Threshold,
|
||||
Port: def.Port,
|
||||
Enabled: true,
|
||||
}
|
||||
if err := h.db.Create(&rule).Error; err != nil {
|
||||
continue
|
||||
}
|
||||
created++
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, models.Response{
|
||||
Code: 200,
|
||||
Message: fmt.Sprintf("已创建 %d 条告警规则", created),
|
||||
Data: gin.H{"created": created},
|
||||
})
|
||||
}
|
||||
@@ -566,7 +566,7 @@ var (
|
||||
// 否则 → 加入队列 (status=queued)
|
||||
func (h *PipelineHandler) tryExecuteOrQueue(pipeline models.Pipeline, run models.PipelineRun) {
|
||||
max := pipeline.MaxExecutors
|
||||
if max <= 0 { max = 1 }
|
||||
if max <= 0 { max = 2 }
|
||||
|
||||
queueMu.Lock()
|
||||
running := pipelineRunningCount[pipeline.ID]
|
||||
|
||||
@@ -49,11 +49,11 @@ func (h *ToolConfigHandler) UpdateTool(c *gin.Context) {
|
||||
}
|
||||
|
||||
var req struct {
|
||||
DisplayName *string `json:"display_name"`
|
||||
Description *string `json:"description"`
|
||||
InstallMethod *models.ToolInstallMethod `json:"install_method"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
SortOrder *int `json:"sort_order"`
|
||||
DisplayName *string `json:"display_name"`
|
||||
Description *string `json:"description"`
|
||||
InstallMethod *models.ToolInstallMethod `json:"install_method"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
SortOrder *int `json:"sort_order"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()})
|
||||
@@ -87,7 +87,7 @@ func (h *ToolConfigHandler) UpdateTool(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "已更新"})
|
||||
}
|
||||
|
||||
// InstallTool triggers lazy installation of a tool
|
||||
// InstallTool triggers lazy installation with optional version override
|
||||
func (h *ToolConfigHandler) InstallTool(c *gin.Context) {
|
||||
var tool models.DeployTool
|
||||
if err := h.db.First(&tool, c.Param("id")); err.Error != nil {
|
||||
@@ -105,11 +105,33 @@ func (h *ToolConfigHandler) InstallTool(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Support version override via query param or JSON body
|
||||
version := tool.DefaultVersion
|
||||
if v := c.Query("version"); v != "" {
|
||||
version = v
|
||||
}
|
||||
if v := c.PostForm("version"); v != "" {
|
||||
version = v
|
||||
}
|
||||
// Also support JSON body
|
||||
var req struct {
|
||||
Version string `json:"version"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err == nil && req.Version != "" {
|
||||
version = req.Version
|
||||
}
|
||||
|
||||
// Store the requested version for the installer
|
||||
if version != "" && version != tool.DefaultVersion {
|
||||
h.db.Model(&tool).Update("default_version", version)
|
||||
tool.DefaultVersion = version
|
||||
}
|
||||
|
||||
go func() {
|
||||
log.Printf("[ToolConfig] Background install triggered for %s", tool.Name)
|
||||
log.Printf("[ToolConfig] Background install triggered for %s (version: %s)", tool.Name, version)
|
||||
}()
|
||||
|
||||
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "安装已触发"})
|
||||
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "安装已触发", Data: gin.H{"version": version}})
|
||||
}
|
||||
|
||||
// CheckToolStatus re-checks a tool's installation status
|
||||
@@ -124,9 +146,13 @@ func (h *ToolConfigHandler) CheckToolStatus(c *gin.Context) {
|
||||
version := ""
|
||||
if tool.CheckCommand != "" {
|
||||
cmd := exec.Command("sh", "-c", tool.CheckCommand)
|
||||
if err := cmd.Run(); err == nil {
|
||||
out, err := cmd.Output()
|
||||
if err == nil {
|
||||
available = true
|
||||
version = "已安装"
|
||||
version = string(out)
|
||||
if len(version) > 128 {
|
||||
version = version[:128]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,3 +171,47 @@ func (h *ToolConfigHandler) CheckToolStatus(c *gin.Context) {
|
||||
"tool": tool,
|
||||
}})
|
||||
}
|
||||
|
||||
// GetToolVersions returns available versions for a tool (jdk/node/maven)
|
||||
func (h *ToolConfigHandler) GetToolVersions(c *gin.Context) {
|
||||
var tool models.DeployTool
|
||||
if err := h.db.First(&tool, c.Param("id")); err.Error != nil {
|
||||
c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "工具不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
versions := getPresetVersions(tool.Name)
|
||||
|
||||
c.JSON(http.StatusOK, models.Response{Code: 200, Data: gin.H{
|
||||
"name": tool.Name,
|
||||
"default": tool.DefaultVersion,
|
||||
"versions": versions,
|
||||
}})
|
||||
}
|
||||
|
||||
// getPresetVersions returns known versions for common tools
|
||||
func getPresetVersions(toolName string) []map[string]string {
|
||||
switch toolName {
|
||||
case "jdk":
|
||||
return []map[string]string{
|
||||
{"version": "11.0.24+8", "label": "JDK 11 (LTS)"},
|
||||
{"version": "17.0.13+7", "label": "JDK 17 (LTS) ★ 推荐"},
|
||||
{"version": "21.0.5+11", "label": "JDK 21 (LTS)"},
|
||||
{"version": "23.0.1+11", "label": "JDK 23 (最新)"},
|
||||
}
|
||||
case "nodejs":
|
||||
return []map[string]string{
|
||||
{"version": "v18.20.5", "label": "Node 18 (LTS)"},
|
||||
{"version": "v20.18.1", "label": "Node 20 (LTS)"},
|
||||
{"version": "v22.14.0", "label": "Node 22 (LTS) ★ 推荐"},
|
||||
}
|
||||
case "maven":
|
||||
return []map[string]string{
|
||||
{"version": "3.9.9", "label": "Maven 3.9.9 ★ 推荐"},
|
||||
{"version": "3.8.8", "label": "Maven 3.8.8"},
|
||||
{"version": "3.6.3", "label": "Maven 3.6.3"},
|
||||
}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -454,6 +454,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c
|
||||
alerts.PUT("/notify-channels/:id", alertHandler.UpdateNotifyChannel)
|
||||
alerts.DELETE("/notify-channels/:id", alertHandler.DeleteNotifyChannel)
|
||||
alerts.POST("/notify-channels/:id/test", alertHandler.TestNotifyChannel)
|
||||
alerts.POST("/quick-setup", alertHandler.QuickSetupRules)
|
||||
}
|
||||
|
||||
// 流水线路由
|
||||
@@ -545,6 +546,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c
|
||||
tools.PUT("/:id", toolConfigHandler.UpdateTool)
|
||||
tools.POST("/:id/install", toolConfigHandler.InstallTool)
|
||||
tools.POST("/:id/check", toolConfigHandler.CheckToolStatus)
|
||||
tools.GET("/:id/versions", toolConfigHandler.GetToolVersions)
|
||||
}
|
||||
|
||||
// 自动化运维路由
|
||||
|
||||
@@ -2,35 +2,41 @@ package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
)
|
||||
|
||||
// AgentReport Agent 上报的原始指标数据 // Logan.Li
|
||||
type AgentReport struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
Hostname string `gorm:"size:255;index;not null" json:"hostname"`
|
||||
CPUUsage float64 `gorm:"type:decimal(6,2)" json:"cpu_usage"` // CPU 使用率 %
|
||||
CPUCores int `json:"cpu_cores"` // CPU 核心数
|
||||
Load1 float64 `gorm:"type:decimal(8,2)" json:"load1"` // 1分钟负载
|
||||
Load5 float64 `gorm:"type:decimal(8,2)" json:"load5"` // 5分钟负载
|
||||
Load15 float64 `gorm:"type:decimal(8,2)" json:"load15"` // 15分钟负载
|
||||
MemTotal float64 `gorm:"type:decimal(10,2)" json:"mem_total"` // 总内存 GB
|
||||
MemUsed float64 `gorm:"type:decimal(10,2)" json:"mem_used"` // 已用内存 GB
|
||||
MemUsage float64 `gorm:"type:decimal(6,2)" json:"mem_usage"` // 内存使用率 %
|
||||
DiskInfo string `gorm:"type:text" json:"disk_info"` // 磁盘信息 JSON
|
||||
PortInfo string `gorm:"type:text" json:"port_info"` // 端口信息 JSON
|
||||
NetInfo string `gorm:"type:text" json:"net_info"` // 网络指标 JSON
|
||||
DiskIOInfo string `gorm:"type:text" json:"disk_io_info"` // 磁盘 IO JSON
|
||||
ReportTime time.Time `json:"report_time"` // 上报时间
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
Hostname string `gorm:"size:255;index;not null" json:"hostname"`
|
||||
CPUUsage float64 `gorm:"type:decimal(6,2)" json:"cpu_usage"`
|
||||
CPUCores int `json:"cpu_cores"`
|
||||
Load1 float64 `gorm:"type:decimal(8,2)" json:"load1"`
|
||||
Load5 float64 `gorm:"type:decimal(8,2)" json:"load5"`
|
||||
Load15 float64 `gorm:"type:decimal(8,2)" json:"load15"`
|
||||
MemTotal float64 `gorm:"type:decimal(10,2)" json:"mem_total"`
|
||||
MemUsed float64 `gorm:"type:decimal(10,2)" json:"mem_used"`
|
||||
MemUsage float64 `gorm:"type:decimal(6,2)" json:"mem_usage"`
|
||||
DiskInfo string `gorm:"type:text" json:"disk_info"`
|
||||
PortInfo string `gorm:"type:text" json:"port_info"`
|
||||
NetInfo string `gorm:"type:text" json:"net_info"`
|
||||
DiskIOInfo string `gorm:"type:text" json:"disk_io_info"`
|
||||
// ──── v2.0 新增字段 ────
|
||||
SwapInfo string `gorm:"type:text" json:"swap_info"` // Swap JSON
|
||||
ProcessTopInfo string `gorm:"type:text" json:"process_top_info"` // 进程 TOP JSON
|
||||
FDInfo string `gorm:"type:text" json:"fd_info"` // FD 句柄 JSON
|
||||
CSInfo string `gorm:"type:text" json:"cs_info"` // 上下文切换 JSON
|
||||
HeartbeatInfo string `gorm:"type:text" json:"heartbeat_info"` // Agent 心跳 JSON
|
||||
// ──────────────────────────
|
||||
ReportTime time.Time `json:"report_time"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (AgentReport) TableName() string {
|
||||
return "monitor_agent_reports"
|
||||
}
|
||||
|
||||
// AgentLatestResponse Agent 最新状态(含服务器元信息)// Logan.Li
|
||||
// AgentLatestResponse Agent 最新状态(含服务器元信息)
|
||||
type AgentLatestResponse struct {
|
||||
ServerID uint `json:"server_id"`
|
||||
Hostname string `json:"hostname"`
|
||||
@@ -41,41 +47,91 @@ type AgentLatestResponse struct {
|
||||
MemTotal float64 `json:"mem_total"`
|
||||
MemUsed float64 `json:"mem_used"`
|
||||
DiskUsage float64 `json:"disk_usage"`
|
||||
DiskTotal int64 `json:"disk_total"` // 磁盘总容量 GB
|
||||
DiskTotal int64 `json:"disk_total"`
|
||||
DiskInfo string `json:"disk_info"`
|
||||
PortInfo string `json:"port_info"`
|
||||
NetInfo string `json:"net_info"`
|
||||
DiskIOInfo string `json:"disk_io_info"`
|
||||
ReportTime string `json:"report_time"`
|
||||
AgentVersion string `json:"agent_version"`
|
||||
AgentStatus string `json:"agent_status"`
|
||||
OS string `json:"os"`
|
||||
Kernel string `json:"kernel"` // 内核版本
|
||||
Uptime int64 `json:"uptime"` // 运行秒数
|
||||
Region string `json:"region"`
|
||||
HasAuth bool `json:"has_auth"` // 是否有 SSH 凭据
|
||||
// ──── v2.0 新增 ────
|
||||
SwapInfo string `json:"swap_info"`
|
||||
ProcessTopInfo string `json:"process_top_info"`
|
||||
FDInfo string `json:"fd_info"`
|
||||
CSInfo string `json:"cs_info"`
|
||||
HeartbeatInfo string `json:"heartbeat_info"`
|
||||
// ─────────────────
|
||||
ReportTime string `json:"report_time"`
|
||||
AgentVersion string `json:"agent_version"`
|
||||
AgentStatus string `json:"agent_status"`
|
||||
OS string `json:"os"`
|
||||
Kernel string `json:"kernel"`
|
||||
Uptime int64 `json:"uptime"`
|
||||
Region string `json:"region"`
|
||||
HasAuth bool `json:"has_auth"`
|
||||
}
|
||||
|
||||
// AgentReportRequest Agent 上报请求体 // Logan.Li
|
||||
// AgentReportRequest Agent 上报请求体
|
||||
type AgentReportRequest struct {
|
||||
Hostname string `json:"hostname" binding:"required"`
|
||||
IP string `json:"ip"` // Agent 探测的本机 IP
|
||||
Timestamp string `json:"timestamp"`
|
||||
AgentVersion string `json:"agent_version"` // Agent 版本号
|
||||
CPU CPUMetric `json:"cpu"`
|
||||
Memory MemMetric `json:"memory"`
|
||||
Disks []DiskMetric `json:"disks"`
|
||||
Ports []PortMetric `json:"ports"`
|
||||
Network NetworkStat `json:"network"` // 网络指标
|
||||
DiskIO DiskIOStat `json:"disk_io"` // 磁盘 IO
|
||||
System *SystemStat `json:"system,omitempty"` // 系统信息(首次/变更时上报)
|
||||
Hostname string `json:"hostname" binding:"required"`
|
||||
IP string `json:"ip"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
AgentVersion string `json:"agent_version"`
|
||||
CPU CPUMetric `json:"cpu"`
|
||||
Memory MemMetric `json:"memory"`
|
||||
Swap *SwapMetric `json:"swap,omitempty"`
|
||||
Disks []DiskMetric `json:"disks"`
|
||||
Ports []PortMetric `json:"ports"`
|
||||
Network NetworkStatModel `json:"network"`
|
||||
DiskIO DiskIOStatModel `json:"disk_io"`
|
||||
System *SystemStatModel `json:"system,omitempty"`
|
||||
// ──── v2.0 新增 ────
|
||||
ProcessTop []ProcessMetric `json:"process_top,omitempty"`
|
||||
FD *FDMetric `json:"fd,omitempty"`
|
||||
ContextSwitches *CSMetric `json:"context_switches,omitempty"`
|
||||
Heartbeat HeartbeatMetric `json:"heartbeat"`
|
||||
}
|
||||
|
||||
// SystemStat 系统静态信息(OS/内核/运行时长)// Logan.Li
|
||||
type SystemStat struct {
|
||||
OSVersion string `json:"os_version"` // OS 版本 (如 "Ubuntu 22.04")
|
||||
Kernel string `json:"kernel"` // 内核版本
|
||||
Uptime int64 `json:"uptime"` // 运行秒数
|
||||
// ──── v2.0 新增上报类型 ────
|
||||
|
||||
type SwapMetric struct {
|
||||
TotalGB float64 `json:"total_gb"`
|
||||
UsedGB float64 `json:"used_gb"`
|
||||
UsagePercent float64 `json:"usage_percent"`
|
||||
}
|
||||
|
||||
type ProcessMetric struct {
|
||||
PID int `json:"pid"`
|
||||
Name string `json:"name"`
|
||||
MemoryMB float64 `json:"memory_mb"`
|
||||
FDCount int `json:"fd_count"`
|
||||
Threads int `json:"threads"`
|
||||
}
|
||||
|
||||
type FDMetric struct {
|
||||
Allocated int `json:"allocated"`
|
||||
Max int64 `json:"max"`
|
||||
UsagePct float64 `json:"usage_pct"`
|
||||
}
|
||||
|
||||
type CSMetric struct {
|
||||
CTXPerSec float64 `json:"ctx_per_sec"`
|
||||
IRQPerSec float64 `json:"irq_per_sec"`
|
||||
}
|
||||
|
||||
type HeartbeatMetric struct {
|
||||
Version string `json:"version"`
|
||||
UptimeSec int64 `json:"uptime_sec"`
|
||||
LastErr string `json:"last_err,omitempty"`
|
||||
SelfCPU float64 `json:"self_cpu_pct"`
|
||||
SelfRSSMB float64 `json:"self_rss_mb"`
|
||||
ReportSeq uint64 `json:"report_seq"`
|
||||
}
|
||||
|
||||
// ──── 已有类型 ────
|
||||
|
||||
type SystemStatModel struct {
|
||||
OSVersion string `json:"os_version"`
|
||||
Kernel string `json:"kernel"`
|
||||
Uptime int64 `json:"uptime"`
|
||||
}
|
||||
|
||||
type CPUMetric struct {
|
||||
@@ -108,18 +164,17 @@ type PortMetric struct {
|
||||
PID int `json:"pid"`
|
||||
}
|
||||
|
||||
// NetworkStat 网络指标(Agent 上报)
|
||||
type NetworkStat struct {
|
||||
type NetworkStatModel struct {
|
||||
TCPEstablished int `json:"tcp_established"`
|
||||
TCPTimeWait int `json:"tcp_time_wait"`
|
||||
TCPCloseWait int `json:"tcp_close_wait"`
|
||||
TCPTotal int `json:"tcp_total"`
|
||||
NicName string `json:"nic_name"`
|
||||
NetRxBPS float64 `json:"net_rx_bps"`
|
||||
NetTxBPS float64 `json:"net_tx_bps"`
|
||||
}
|
||||
|
||||
// DiskIOStat 磁盘 IO 指标(Agent 上报)
|
||||
type DiskIOStat struct {
|
||||
type DiskIOStatModel struct {
|
||||
ReadBPS float64 `json:"read_bps"`
|
||||
WriteBPS float64 `json:"write_bps"`
|
||||
ReadIOPS float64 `json:"read_iops"`
|
||||
|
||||
@@ -32,7 +32,7 @@ type AgentRule struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
Name string `gorm:"size:255;not null" json:"name"`
|
||||
Hostname string `gorm:"size:255" json:"hostname"` // 空表示全部主机
|
||||
Metric string `gorm:"size:32;not null" json:"metric"` // cpu/mem/disk/offline/port_down
|
||||
Metric string `gorm:"size:32;not null" json:"metric"` // cpu/mem/disk/offline/port_down/tcp_time_wait/tcp_close_wait/service_process
|
||||
Operator string `gorm:"size:10;default:>" json:"operator"` // > >= < <= ==
|
||||
Threshold float64 `gorm:"type:decimal(10,2)" json:"threshold"`
|
||||
Port int `json:"port"` // port_down 专用
|
||||
|
||||
@@ -398,14 +398,36 @@ type AcknowledgeAlertRequest struct {
|
||||
// CreateNotifyChannelRequest 创建通知渠道请求
|
||||
type CreateNotifyChannelRequest struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Type string `json:"type" binding:"required,oneof=email sms webhook dingtalk wechat"`
|
||||
Type string `json:"type" binding:"required,oneof=email sms webhook dingtalk wechat feishu"`
|
||||
Config string `json:"config"`
|
||||
}
|
||||
|
||||
// UpdateNotifyChannelRequest 更新通知渠道请求
|
||||
type UpdateNotifyChannelRequest struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type" binding:"omitempty,oneof=email sms webhook dingtalk wechat"`
|
||||
Type string `json:"type" binding:"omitempty,oneof=email sms webhook dingtalk wechat feishu"`
|
||||
Config string `json:"config"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// FeishuWebhookConfig 飞书 Webhook 配置
|
||||
type FeishuWebhookConfig struct {
|
||||
URL string `json:"url"` // 飞书机器人 webhook 地址
|
||||
Secret string `json:"secret"` // 可选:签名密钥
|
||||
}
|
||||
|
||||
// FeishuCardMessage 飞书卡片消息
|
||||
type FeishuCardMessage struct {
|
||||
MsgType string `json:"msg_type"`
|
||||
Content FeishuCardContent `json:"content"`
|
||||
}
|
||||
|
||||
type FeishuCardContent struct {
|
||||
Title string `json:"title"`
|
||||
Content [][]FeishuCardElement `json:"content"`
|
||||
}
|
||||
|
||||
type FeishuCardElement struct {
|
||||
Tag string `json:"tag"`
|
||||
Text string `json:"text,omitempty"`
|
||||
}
|
||||
@@ -25,7 +25,7 @@ type Pipeline struct {
|
||||
DeployTarget string `gorm:"size:16;default:ssh;comment:部署目标 ssh/k8s" json:"deploy_target"`
|
||||
|
||||
// 并发控制
|
||||
MaxExecutors int `gorm:"default:1;comment:最大并发执行数(1=串行)" json:"max_executors"`
|
||||
MaxExecutors int `gorm:"default:2;comment:最大并发执行数(1=串行,默认2)" json:"max_executors"`
|
||||
|
||||
// SSH 部署目标服务器 (JSON: [1,2,3])
|
||||
ServerIDs string `gorm:"type:text;comment:SSH服务器ID列表(JSON)" json:"server_ids,omitempty"`
|
||||
|
||||
@@ -57,30 +57,51 @@ func (DeployTool) TableName() string {
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 预置工具定义(Seeder)
|
||||
// 预置工具定义(Seeder)— 精简版 v2
|
||||
// 移除: kubectl(Dockerfile 预装)、helm(非核心)
|
||||
// 新增: nvm(管理 Node 版本)、jdk(Java 构建)
|
||||
// ============================================
|
||||
|
||||
// PredefinedTools 返回系统预置的工具配置列表
|
||||
func PredefinedTools() []DeployTool {
|
||||
return []DeployTool{
|
||||
// ──── JDK — Java 构建 // Logan.Li ────
|
||||
{
|
||||
Name: "kubectl",
|
||||
DisplayName: "Kubectl",
|
||||
Description: "Kubernetes 命令行工具,用于 K8s 集群交互(已预装在镜像中)",
|
||||
Category: "k8s",
|
||||
InstallMethod: ToolPreinstall,
|
||||
BinaryName: "kubectl",
|
||||
InstallPath: "/usr/local/bin/kubectl",
|
||||
CheckCommand: "kubectl version --client --short 2>/dev/null || kubectl version --client 2>/dev/null",
|
||||
VersionURL: "https://dl.k8s.io/release/stable.txt",
|
||||
DownloadURL: "https://dl.k8s.io/release/{version}/bin/linux/amd64/kubectl",
|
||||
DefaultVersion: "v1.32.0",
|
||||
SortOrder: 1,
|
||||
Name: "jdk",
|
||||
DisplayName: "JDK (Java)",
|
||||
Description: "Java 开发工具包,流水线 Java/Maven 构建阶段使用",
|
||||
Category: "build",
|
||||
InstallMethod: ToolLazy,
|
||||
BinaryName: "java",
|
||||
InstallPath: "/usr/local/bin/java",
|
||||
CheckCommand: "java -version 2>&1 | head -1",
|
||||
VersionURL: "https://api.adoptium.net/v3/info/release_versions?heap_size=normal&image_type=jdk&page=0&page_size=1&project=jdk&release_type=ga&semver=false&sort_method=DEFAULT&sort_order=DESC&version=%5B17%2C99%5D",
|
||||
DownloadURL: "https://github.com/adoptium/temurin17-binaries/releases/download/jdk-{version}/OpenJDK17U-jdk_x64_linux_hotspot_{version}.tar.gz",
|
||||
DefaultVersion: "17.0.13+7",
|
||||
InstallScript: `#!/bin/sh
|
||||
# JDK lazy install — Temurin OpenJDK
|
||||
JDK_VERSION="${TOOL_VERSION:-17.0.13+7}"
|
||||
JDK_MAJOR=$(echo "$JDK_VERSION" | cut -d. -f1)
|
||||
JDK_URL="https://github.com/adoptium/temurin${JDK_MAJOR}-binaries/releases/download/jdk-${JDK_VERSION}/OpenJDK${JDK_MAJOR}U-jdk_x64_linux_hotspot_${JDK_VERSION}.tar.gz"
|
||||
echo "[JDK] Downloading ${JDK_VERSION}..."
|
||||
cd /tmp
|
||||
curl -sL "$JDK_URL" -o jdk.tar.gz
|
||||
tar xzf jdk.tar.gz
|
||||
mkdir -p /usr/local/share
|
||||
mv jdk-${JDK_VERSION} /usr/local/share/jdk
|
||||
ln -sf /usr/local/share/jdk/bin/java /usr/local/bin/java
|
||||
ln -sf /usr/local/share/jdk/bin/javac /usr/local/bin/javac
|
||||
ln -sf /usr/local/share/jdk/bin/jar /usr/local/bin/jar
|
||||
rm -f jdk.tar.gz
|
||||
echo "[JDK] Installed: $(java -version 2>&1 | head -1)"
|
||||
`,
|
||||
SortOrder: 1,
|
||||
},
|
||||
// ──── Maven — Java 构建 // Logan.Li ────
|
||||
{
|
||||
Name: "maven",
|
||||
DisplayName: "Maven",
|
||||
Description: "Java 项目构建工具,流水线 Java 构建阶段使用",
|
||||
Description: "Java 项目构建工具,流水线 Java 构建阶段使用(依赖 JDK)",
|
||||
Category: "build",
|
||||
InstallMethod: ToolLazy,
|
||||
BinaryName: "mvn",
|
||||
@@ -102,87 +123,97 @@ mv apache-maven-${MAVEN_VERSION} /usr/local/share/maven
|
||||
ln -sf /usr/local/share/maven/bin/mvn /usr/local/bin/mvn
|
||||
rm -f maven.tar.gz
|
||||
echo "[Maven] Installed: $(mvn --version 2>&1 | head -1)"
|
||||
`,
|
||||
`,
|
||||
SortOrder: 2,
|
||||
},
|
||||
// ──── NVM — Node Version Manager // Logan.Li ────
|
||||
{
|
||||
Name: "nvm",
|
||||
DisplayName: "NVM (Node 版本管理)",
|
||||
Description: "Node 版本管理器,流水线 Node.js 构建阶段使用(node 依赖此工具)",
|
||||
Category: "build",
|
||||
InstallMethod: ToolLazy,
|
||||
BinaryName: "nvm",
|
||||
InstallPath: "/usr/local/share/nvm/nvm.sh",
|
||||
CheckCommand: "source /usr/local/share/nvm/nvm.sh 2>/dev/null && nvm --version 2>/dev/null",
|
||||
VersionURL: "https://api.github.com/repos/nvm-sh/nvm/releases/latest",
|
||||
DefaultVersion: "0.40.1",
|
||||
InstallScript: `#!/bin/sh
|
||||
# NVM lazy install
|
||||
NVM_VERSION="${TOOL_VERSION:-0.40.1}"
|
||||
NVM_DIR="/usr/local/share/nvm"
|
||||
echo "[NVM] Downloading ${NVM_VERSION}..."
|
||||
mkdir -p "$NVM_DIR"
|
||||
curl -sL "https://raw.githubusercontent.com/nvm-sh/nvm/v${NVM_VERSION}/install.sh" | NVM_DIR="$NVM_DIR" bash
|
||||
# Make available system-wide via profile.d
|
||||
cat > /etc/profile.d/nvm.sh << 'NVM_PROFILE'
|
||||
export NVM_DIR="/usr/local/share/nvm"
|
||||
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
|
||||
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"
|
||||
NVM_PROFILE
|
||||
chmod +x /etc/profile.d/nvm.sh
|
||||
echo "[NVM] Installed: v${NVM_VERSION}"
|
||||
`,
|
||||
SortOrder: 3,
|
||||
},
|
||||
// ──── Node.js — 通过 NVM 安装 // Logan.Li ────
|
||||
{
|
||||
Name: "nodejs",
|
||||
DisplayName: "Node.js + npm",
|
||||
Description: "前端构建工具,流水线 npm install/build 阶段使用",
|
||||
Description: "前端构建工具,流水线 npm install/build 阶段使用(通过 NVM 安装)",
|
||||
Category: "build",
|
||||
InstallMethod: ToolLazy,
|
||||
BinaryName: "node",
|
||||
InstallPath: "/usr/local/bin/node",
|
||||
CheckCommand: "node --version 2>/dev/null",
|
||||
DownloadURL: "https://nodejs.org/dist/{version}/node-{version}-linux-x64.tar.xz",
|
||||
VersionURL: "https://nodejs.org/dist/latest-v22.x/",
|
||||
DefaultVersion: "v22.14.0",
|
||||
InstallScript: `#!/bin/sh
|
||||
# Node.js lazy install — download & extract
|
||||
# Node.js via NVM install
|
||||
NODE_VERSION="${TOOL_VERSION:-v22.14.0}"
|
||||
NODE_URL="https://nodejs.org/dist/${NODE_VERSION}/node-${NODE_VERSION}-linux-x64.tar.xz"
|
||||
echo "[Node.js] Downloading ${NODE_VERSION}..."
|
||||
cd /tmp
|
||||
curl -sL "$NODE_URL" -o node.tar.xz
|
||||
tar xJf node.tar.xz
|
||||
mkdir -p /usr/local/share
|
||||
mv node-${NODE_VERSION}-linux-x64 /usr/local/share/node
|
||||
ln -sf /usr/local/share/node/bin/node /usr/local/bin/node
|
||||
ln -sf /usr/local/share/node/bin/npm /usr/local/bin/npm
|
||||
ln -sf /usr/local/share/node/bin/npx /usr/local/bin/npx
|
||||
rm -f node.tar.xz
|
||||
echo "[Node.js] Installing via NVM ${NODE_VERSION}..."
|
||||
export NVM_DIR="/usr/local/share/nvm"
|
||||
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
|
||||
if ! command -v nvm >/dev/null 2>&1; then
|
||||
# NVM not found — install it first
|
||||
echo "[Node.js] NVM not found, installing NVM first..."
|
||||
curl -sL "https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh" | NVM_DIR="$NVM_DIR" bash
|
||||
\. "$NVM_DIR/nvm.sh"
|
||||
fi
|
||||
nvm install "${NODE_VERSION#v}"
|
||||
nvm alias default "${NODE_VERSION#v}"
|
||||
nvm use "${NODE_VERSION#v}"
|
||||
# Symlink for system-wide access
|
||||
ln -sf "$NVM_DIR/versions/node/$(nvm version)/bin/node" /usr/local/bin/node
|
||||
ln -sf "$NVM_DIR/versions/node/$(nvm version)/bin/npm" /usr/local/bin/npm
|
||||
ln -sf "$NVM_DIR/versions/node/$(nvm version)/bin/npx" /usr/local/bin/npx
|
||||
npm config set registry https://registry.npmmirror.com
|
||||
echo "[Node.js] Installed: $(node --version) / npm $(npm --version)"
|
||||
`,
|
||||
SortOrder: 3,
|
||||
},
|
||||
{
|
||||
Name: "helm",
|
||||
DisplayName: "Helm",
|
||||
Description: "Kubernetes 包管理工具,Chart 部署使用",
|
||||
Category: "k8s",
|
||||
InstallMethod: ToolLazy,
|
||||
BinaryName: "helm",
|
||||
InstallPath: "/usr/local/bin/helm",
|
||||
CheckCommand: "helm version --short 2>/dev/null",
|
||||
VersionURL: "https://get.helm.sh/",
|
||||
DownloadURL: "https://get.helm.sh/helm-{version}-linux-amd64.tar.gz",
|
||||
DefaultVersion: "v3.16.0",
|
||||
InstallScript: `#!/bin/sh
|
||||
# Helm lazy install — download & extract
|
||||
HELM_VERSION="${TOOL_VERSION:-v3.16.0}"
|
||||
HELM_URL="https://get.helm.sh/helm-${HELM_VERSION}-linux-amd64.tar.gz"
|
||||
echo "[Helm] Downloading ${HELM_VERSION}..."
|
||||
cd /tmp
|
||||
curl -sL "$HELM_URL" -o helm.tar.gz
|
||||
tar xzf helm.tar.gz
|
||||
mv linux-amd64/helm /usr/local/bin/helm
|
||||
rm -rf helm.tar.gz linux-amd64
|
||||
echo "[Helm] Installed: $(helm version --short 2>&1)"
|
||||
`,
|
||||
`,
|
||||
SortOrder: 4,
|
||||
},
|
||||
// ──── Git — 版本控制(预装)// Logan.Li ────
|
||||
{
|
||||
Name: "git",
|
||||
DisplayName: "Git",
|
||||
Description: "版本控制工具,流水线代码拉取使用",
|
||||
Category: "build",
|
||||
InstallMethod: ToolPreinstall,
|
||||
BinaryName: "git",
|
||||
InstallPath: "/usr/bin/git",
|
||||
CheckCommand: "git --version 2>/dev/null",
|
||||
SortOrder: 5,
|
||||
Name: "git",
|
||||
DisplayName: "Git",
|
||||
Description: "版本控制工具,流水线代码拉取使用",
|
||||
Category: "build",
|
||||
InstallMethod: ToolPreinstall,
|
||||
BinaryName: "git",
|
||||
InstallPath: "/usr/bin/git",
|
||||
CheckCommand: "git --version 2>/dev/null",
|
||||
SortOrder: 5,
|
||||
},
|
||||
// ──── Docker CLI — 容器构建(预装)// Logan.Li ────
|
||||
{
|
||||
Name: "docker-cli",
|
||||
DisplayName: "Docker CLI",
|
||||
Description: "Docker 命令行工具,流水线镜像构建/推送使用",
|
||||
Category: "deploy",
|
||||
InstallMethod: ToolPreinstall,
|
||||
BinaryName: "docker",
|
||||
InstallPath: "/usr/bin/docker",
|
||||
CheckCommand: "docker --version 2>/dev/null",
|
||||
SortOrder: 6,
|
||||
Name: "docker-cli",
|
||||
DisplayName: "Docker CLI",
|
||||
Description: "Docker 命令行工具,流水线镜像构建/推送使用",
|
||||
Category: "deploy",
|
||||
InstallMethod: ToolPreinstall,
|
||||
BinaryName: "docker",
|
||||
InstallPath: "/usr/bin/docker",
|
||||
CheckCommand: "docker --version 2>/dev/null",
|
||||
SortOrder: 6,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -85,7 +85,7 @@ export function PipelineManager() {
|
||||
const [newCachePaths, setNewCachePaths] = useState('');
|
||||
|
||||
// Executor concurrency
|
||||
const [newMaxExecutors, setNewMaxExecutors] = useState(1);
|
||||
const [newMaxExecutors, setNewMaxExecutors] = useState(2);
|
||||
|
||||
// Reference data
|
||||
const [repos, setRepos] = useState<any[]>([]);
|
||||
@@ -288,33 +288,46 @@ export function PipelineManager() {
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* ══════════ 全流程可视化横幅 // Logan.Li ══════════ */}
|
||||
<div className="flex items-center gap-1.5 px-4 py-2.5 rounded-lg bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)]">
|
||||
<div className="flex items-center gap-1">
|
||||
<GitBranch className="h-3.5 w-3.5 text-indigo-400" />
|
||||
<span className="text-[11px] font-semibold text-indigo-400">Git 代码</span>
|
||||
{/* ══════════ 全流程可视化横幅 — 双路径 ══════════ */}
|
||||
<div className="flex items-stretch gap-3 px-4 py-3 rounded-lg bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)]">
|
||||
{/* 路径 1: SSH 传统主机部署 */}
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<GitBranch className="h-3 w-3 text-indigo-400" />
|
||||
<span className="text-[10px] font-semibold text-indigo-400">构建</span>
|
||||
<ArrowRight className="h-2.5 w-2.5 text-[var(--dg-text-secondary)] opacity-30" />
|
||||
<Rocket className="h-3 w-3 text-red-400" />
|
||||
<span className="text-[10px] font-semibold text-red-400">部署</span>
|
||||
<ArrowRight className="h-2.5 w-2.5 text-[var(--dg-text-secondary)] opacity-30" />
|
||||
<div className="flex items-center gap-1 px-2 py-0.5 rounded bg-blue-400/10 border border-blue-400/20">
|
||||
<Server className="h-3 w-3 text-blue-400" />
|
||||
<span className="text-[10px] font-medium text-blue-400">SSH 主机</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-[9px] text-[var(--dg-text-secondary)] opacity-40 pl-1">传统主机 SCP 部署 · 无需镜像仓库</p>
|
||||
</div>
|
||||
<ArrowRight className="h-3 w-3 text-[var(--dg-text-secondary)] opacity-30" />
|
||||
<div className="flex items-center gap-1">
|
||||
<Box className="h-3.5 w-3.5 text-amber-400" />
|
||||
<span className="text-[11px] font-semibold text-amber-400">构建</span>
|
||||
{/* 分隔 */}
|
||||
<div className="w-px bg-[var(--dg-border)]" />
|
||||
{/* 路径 2: Kubernetes 容器部署 */}
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<GitBranch className="h-3 w-3 text-indigo-400" />
|
||||
<span className="text-[10px] font-semibold text-indigo-400">构建</span>
|
||||
<ArrowRight className="h-2.5 w-2.5 text-[var(--dg-text-secondary)] opacity-30" />
|
||||
<Container className="h-3 w-3 text-cyan-400" />
|
||||
<span className="text-[10px] font-semibold text-cyan-400">镜像仓库</span>
|
||||
<ArrowRight className="h-2.5 w-2.5 text-[var(--dg-text-secondary)] opacity-30" />
|
||||
<Rocket className="h-3 w-3 text-red-400" />
|
||||
<span className="text-[10px] font-semibold text-red-400">部署</span>
|
||||
<ArrowRight className="h-2.5 w-2.5 text-[var(--dg-text-secondary)] opacity-30" />
|
||||
<div className="flex items-center gap-1 px-2 py-0.5 rounded bg-emerald-400/10 border border-emerald-400/20">
|
||||
<Network className="h-3 w-3 text-emerald-400" />
|
||||
<span className="text-[10px] font-medium text-emerald-400">Kubernetes</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-[9px] text-[var(--dg-text-secondary)] opacity-40 pl-1">容器化部署 · 需镜像仓库推送</p>
|
||||
</div>
|
||||
<ArrowRight className="h-3 w-3 text-[var(--dg-text-secondary)] opacity-30" />
|
||||
<div className="flex items-center gap-1">
|
||||
<Container className="h-3.5 w-3.5 text-cyan-400" />
|
||||
<span className="text-[11px] font-semibold text-cyan-400">镜像仓库</span>
|
||||
</div>
|
||||
<ArrowRight className="h-3 w-3 text-[var(--dg-text-secondary)] opacity-30" />
|
||||
<div className="flex items-center gap-1">
|
||||
<Rocket className="h-3.5 w-3.5 text-red-400" />
|
||||
<span className="text-[11px] font-semibold text-red-400">部署</span>
|
||||
</div>
|
||||
<ArrowRight className="h-3 w-3 text-[var(--dg-text-secondary)] opacity-30" />
|
||||
<div className="flex items-center gap-1">
|
||||
<Network className="h-3.5 w-3.5 text-emerald-400" />
|
||||
<span className="text-[11px] font-semibold text-emerald-400">K8s</span>
|
||||
</div>
|
||||
<span className="ml-auto text-[10px] text-[var(--dg-text-secondary)] opacity-40 tracking-wide">全流程可视化</span>
|
||||
<span className="self-center ml-2 text-[10px] text-[var(--dg-text-secondary)] opacity-30 tracking-wide whitespace-nowrap">全流程可视化</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
@@ -401,7 +414,7 @@ export function PipelineManager() {
|
||||
)}
|
||||
<div className="flex items-center gap-3 mt-1.5 text-xs text-[var(--dg-text-secondary)] opacity-60">
|
||||
<span className="flex items-center gap-1"><GitBranch className="h-3 w-3" />{pipeline.deploy_mode === 'tag' ? 'Tag发版' : pipeline.branch || 'main'}</span>
|
||||
<span className="flex items-center gap-1">{(pipeline.deploy_target || 'ssh') === 'k8s' ? <><Network className="h-3 w-3" />K8s</> : <><Server className="h-3 w-3" />SSH</>}</span>
|
||||
<span className="flex items-center gap-1">{(pipeline.deploy_target || 'ssh') === 'k8s' ? <><Network className="h-3 w-3" />Kubernetes</> : <><Server className="h-3 w-3" />SSH 主机</>}</span>
|
||||
{repo && <span className="flex items-center gap-1"><Globe className="h-3 w-3" />{repo.name}</span>}
|
||||
{registry && <span className="flex items-center gap-1"><Container className="h-3 w-3" />{registry.name}</span>}
|
||||
{pipeline.last_run_at && <span><Clock className="h-3 w-3 inline mr-0.5" />{new Date(pipeline.last_run_at).toLocaleString('zh-CN')}</span>}
|
||||
@@ -560,7 +573,7 @@ export function PipelineManager() {
|
||||
<div className="flex gap-1 bg-[var(--dg-bg-secondary)] rounded-lg p-1 border border-[var(--dg-border)]">
|
||||
{[
|
||||
{ key: 'ssh', label: 'SSH 主机', icon: Server },
|
||||
{ key: 'k8s', label: 'K8s 集群', icon: Network },
|
||||
{ key: 'k8s', label: 'Kubernetes 集群', icon: Network },
|
||||
].map(t => {
|
||||
const active = newDeployTarget === t.key;
|
||||
return (
|
||||
@@ -819,7 +832,7 @@ export function PipelineManager() {
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<p className="text-[10px] text-[var(--dg-text-secondary)] opacity-50 mt-1">设为 1 则按顺序串行执行,超过 1 可并发构建</p>
|
||||
<p className="text-[10px] text-[var(--dg-text-secondary)] opacity-50 mt-1">设为 1 则按顺序串行执行,默认 2 可并发构建</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 mt-4 pt-4 border-t border-[var(--dg-border)]">
|
||||
@@ -889,7 +902,7 @@ function PipelineQueuePanel({ pipeline, clusterId: _cid }: { pipeline: any; clus
|
||||
const running = queue?.running || 0;
|
||||
const queued = queue?.queued || 0;
|
||||
const queueIds: number[] = queue?.queue_ids || [];
|
||||
const max = pipeline.max_executors || 1;
|
||||
const max = pipeline.max_executors || 2;
|
||||
const pendingRuns = queue?.pending_runs || [];
|
||||
|
||||
if (loading && !queue) return null;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Wrench, RefreshCw, Loader2, Download, CheckCircle, XCircle, Clock, Settings2 } from 'lucide-react';
|
||||
import { Wrench, RefreshCw, Loader2, Download, CheckCircle, XCircle, Clock, Settings2, ChevronDown } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
|
||||
import { toast } from 'sonner';
|
||||
import { deployApi } from '@/services/api';
|
||||
|
||||
@@ -12,14 +12,17 @@ interface ToolConfig {
|
||||
category: string; install_method: 'preinstall' | 'lazy' | 'disabled';
|
||||
binary_name: string; install_path: string; status: string;
|
||||
installed_version: string; error_msg: string; enabled: boolean;
|
||||
sort_order: number;
|
||||
sort_order: number; default_version: string;
|
||||
}
|
||||
|
||||
interface VersionOption {
|
||||
version: string; label: string;
|
||||
}
|
||||
|
||||
const categoryLabel: Record<string, string> = {
|
||||
k8s: 'K8s', build: '构建', deploy: '部署', automation: '自动化', other: '其他',
|
||||
build: '构建', deploy: '部署', automation: '自动化', other: '其他',
|
||||
};
|
||||
const categoryColor: Record<string, string> = {
|
||||
k8s: 'bg-blue-500/20 text-blue-400 border-blue-500/30',
|
||||
build: 'bg-amber-500/20 text-amber-400 border-amber-500/30',
|
||||
deploy: 'bg-cyan-500/20 text-cyan-400 border-cyan-500/30',
|
||||
automation: 'bg-purple-500/20 text-purple-400 border-purple-500/30',
|
||||
@@ -34,11 +37,21 @@ const methodColor: Record<string, string> = {
|
||||
disabled: 'bg-slate-500/20 text-slate-400 border-slate-500/30',
|
||||
};
|
||||
|
||||
// Tools that support version selection
|
||||
const VERSIONED_TOOLS = ['jdk', 'nodejs', 'maven'];
|
||||
|
||||
export default function ToolConfigTab() {
|
||||
const [tools, setTools] = useState<ToolConfig[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [installing, setInstalling] = useState<number | null>(null);
|
||||
|
||||
// Version dialog state
|
||||
const [versionDialog, setVersionDialog] = useState<{ tool: ToolConfig; versions: VersionOption[] } | null>(null);
|
||||
const [selectedVersion, setSelectedVersion] = useState('');
|
||||
|
||||
// Download test state
|
||||
const [testing, setTesting] = useState<number | null>(null);
|
||||
|
||||
const fetchTools = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
@@ -50,17 +63,32 @@ export default function ToolConfigTab() {
|
||||
|
||||
useEffect(() => { fetchTools(); }, []);
|
||||
|
||||
const handleInstall = async (tool: ToolConfig) => {
|
||||
const openVersionDialog = async (tool: ToolConfig) => {
|
||||
try {
|
||||
const res: any = await deployApi.getToolVersions(tool.id);
|
||||
const versions = (res as any)?.versions || [];
|
||||
if (versions.length === 0) {
|
||||
// No versions — install directly
|
||||
handleInstall(tool);
|
||||
return;
|
||||
}
|
||||
setVersionDialog({ tool, versions });
|
||||
setSelectedVersion(tool.default_version || versions[0]?.version || '');
|
||||
} catch {
|
||||
// Fallback: install with default version
|
||||
handleInstall(tool);
|
||||
}
|
||||
};
|
||||
|
||||
const handleInstall = async (tool: ToolConfig, version?: string) => {
|
||||
setInstalling(tool.id);
|
||||
try {
|
||||
await deployApi.installTool(tool.id);
|
||||
toast.success(`${tool.display_name} 安装已触发`);
|
||||
// Poll for status
|
||||
const v = version || tool.default_version;
|
||||
await deployApi.installTool(tool.id, v);
|
||||
toast.success(`${tool.display_name}${v ? ` (${v})` : ''} 安装已触发`);
|
||||
setVersionDialog(null);
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
await deployApi.checkTool(tool.id);
|
||||
fetchTools();
|
||||
} catch { /* ignore */ }
|
||||
try { await deployApi.checkTool(tool.id); fetchTools(); } catch { /* ignore */ }
|
||||
setInstalling(null);
|
||||
}, 3000);
|
||||
} catch {
|
||||
@@ -85,6 +113,26 @@ export default function ToolConfigTab() {
|
||||
} catch { toast.error('更新失败'); }
|
||||
};
|
||||
|
||||
// Download speed test
|
||||
const handleTestDownload = async (tool: ToolConfig) => {
|
||||
setTesting(tool.id);
|
||||
const start = Date.now();
|
||||
try {
|
||||
// Simulate a quick reachability test by fetching the version URL
|
||||
const res: any = await deployApi.getToolVersions(tool.id);
|
||||
const elapsed = ((Date.now() - start) / 1000).toFixed(1);
|
||||
const available = (res as any)?.versions?.length > 0;
|
||||
if (available) {
|
||||
toast.success(`${tool.display_name} 镜像可访问 (${elapsed}s)`);
|
||||
} else {
|
||||
toast(`${tool.display_name} 无法获取版本列表`, { description: '请检查网络连接' });
|
||||
}
|
||||
} catch {
|
||||
toast.error(`${tool.display_name} 网络不可达`);
|
||||
}
|
||||
setTesting(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
@@ -117,84 +165,164 @@ export default function ToolConfigTab() {
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{tools.map(tool => (
|
||||
<tr key={tool.id} className="border-b border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/50">
|
||||
<td className="px-3 py-2">
|
||||
<div className="font-medium text-[var(--dg-text-primary)]">{tool.display_name}</div>
|
||||
<div className="text-xs text-[var(--dg-text-secondary)] font-mono">{tool.name}</div>
|
||||
{tool.installed_version && tool.status === 'installed' && (
|
||||
<div className="text-xs text-emerald-400 font-mono mt-0.5">v{tool.installed_version}</div>
|
||||
)}
|
||||
{tool.error_msg && (
|
||||
<div className="text-xs text-red-400 mt-0.5 max-w-[200px] truncate" title={tool.error_msg}>{tool.error_msg}</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-3 py-2 hidden sm:table-cell">
|
||||
<Badge className={`text-xs ${categoryColor[tool.category] || categoryColor.other}`}>
|
||||
{categoryLabel[tool.category] || tool.category}
|
||||
</Badge>
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
<Select
|
||||
value={tool.install_method}
|
||||
onValueChange={(v) => handleMethodChange(tool, v as 'preinstall' | 'lazy' | 'disabled')}
|
||||
>
|
||||
<SelectTrigger className="h-7 w-[90px] text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="preinstall">预装</SelectItem>
|
||||
<SelectItem value="lazy">懒加载</SelectItem>
|
||||
<SelectItem value="disabled">禁用</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
{tool.status === 'installed' ? (
|
||||
<Badge className="bg-emerald-500/20 text-emerald-400 border-emerald-500/30 text-xs gap-1">
|
||||
<CheckCircle className="w-3 h-3" />已安装
|
||||
</Badge>
|
||||
) : tool.status === 'installing' ? (
|
||||
<Badge className="bg-amber-500/20 text-amber-400 border-amber-500/30 text-xs gap-1">
|
||||
<Loader2 className="w-3 h-3 animate-spin" />安装中
|
||||
</Badge>
|
||||
) : tool.status === 'failed' ? (
|
||||
<Badge className="bg-red-500/20 text-red-400 border-red-500/30 text-xs gap-1">
|
||||
<XCircle className="w-3 h-3" />失败
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge className="bg-slate-500/20 text-slate-400 border-slate-500/30 text-xs gap-1">
|
||||
<Clock className="w-3 h-3" />未安装
|
||||
</Badge>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right">
|
||||
<div className="flex justify-end gap-1">
|
||||
{tool.install_method === 'lazy' && tool.status !== 'installed' && (
|
||||
<Button
|
||||
variant="outline" size="sm" className="h-7 text-xs"
|
||||
onClick={() => handleInstall(tool)}
|
||||
disabled={installing === tool.id}
|
||||
>
|
||||
{installing === tool.id ? (
|
||||
<Loader2 className="w-3 h-3 animate-spin mr-1" />
|
||||
) : (
|
||||
<Download className="w-3 h-3 mr-1" />
|
||||
)}
|
||||
安装
|
||||
</Button>
|
||||
{tools.map(tool => {
|
||||
const hasVersions = VERSIONED_TOOLS.includes(tool.name);
|
||||
return (
|
||||
<tr key={tool.id} className="border-b border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/50">
|
||||
<td className="px-3 py-2">
|
||||
<div className="font-medium text-[var(--dg-text-primary)]">{tool.display_name}</div>
|
||||
<div className="text-xs text-[var(--dg-text-secondary)] font-mono">{tool.name}</div>
|
||||
{tool.description && (
|
||||
<div className="text-[10px] text-[var(--dg-text-muted)] mt-0.5 max-w-[220px] leading-tight">{tool.description}</div>
|
||||
)}
|
||||
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => handleCheckStatus(tool)} title="检测">
|
||||
<Settings2 className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{tool.installed_version && tool.status === 'installed' && (
|
||||
<div className="text-xs text-emerald-400 font-mono mt-0.5">v{tool.installed_version}</div>
|
||||
)}
|
||||
{tool.error_msg && (
|
||||
<div className="text-xs text-red-400 mt-0.5 max-w-[200px] truncate" title={tool.error_msg}>{tool.error_msg}</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-3 py-2 hidden sm:table-cell">
|
||||
<Badge className={`text-xs ${categoryColor[tool.category] || categoryColor.other}`}>
|
||||
{categoryLabel[tool.category] || tool.category}
|
||||
</Badge>
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
<Select
|
||||
value={tool.install_method}
|
||||
onValueChange={(v) => handleMethodChange(tool, v as 'preinstall' | 'lazy' | 'disabled')}
|
||||
>
|
||||
<SelectTrigger className="h-7 w-[90px] text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="preinstall">预装</SelectItem>
|
||||
<SelectItem value="lazy">懒加载</SelectItem>
|
||||
<SelectItem value="disabled">禁用</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
{tool.status === 'installed' ? (
|
||||
<Badge className="bg-emerald-500/20 text-emerald-400 border-emerald-500/30 text-xs gap-1">
|
||||
<CheckCircle className="w-3 h-3" />已安装
|
||||
</Badge>
|
||||
) : tool.status === 'installing' ? (
|
||||
<Badge className="bg-amber-500/20 text-amber-400 border-amber-500/30 text-xs gap-1">
|
||||
<Loader2 className="w-3 h-3 animate-spin" />安装中
|
||||
</Badge>
|
||||
) : tool.status === 'failed' ? (
|
||||
<Badge className="bg-red-500/20 text-red-400 border-red-500/30 text-xs gap-1">
|
||||
<XCircle className="w-3 h-3" />失败
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge className="bg-slate-500/20 text-slate-400 border-slate-500/30 text-xs gap-1">
|
||||
<Clock className="w-3 h-3" />未安装
|
||||
</Badge>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right">
|
||||
<div className="flex justify-end gap-1">
|
||||
{tool.install_method === 'lazy' && tool.status !== 'installed' && (
|
||||
hasVersions ? (
|
||||
<Button
|
||||
variant="outline" size="sm" className="h-7 text-xs"
|
||||
onClick={() => openVersionDialog(tool)}
|
||||
disabled={installing === tool.id}
|
||||
>
|
||||
{installing === tool.id ? (
|
||||
<Loader2 className="w-3 h-3 animate-spin mr-1" />
|
||||
) : (
|
||||
<Download className="w-3 h-3 mr-1" />
|
||||
)}
|
||||
安装
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant="outline" size="sm" className="h-7 text-xs"
|
||||
onClick={() => handleInstall(tool)}
|
||||
disabled={installing === tool.id}
|
||||
>
|
||||
{installing === tool.id ? (
|
||||
<Loader2 className="w-3 h-3 animate-spin mr-1" />
|
||||
) : (
|
||||
<Download className="w-3 h-3 mr-1" />
|
||||
)}
|
||||
安装
|
||||
</Button>
|
||||
)
|
||||
)}
|
||||
{tool.install_method === 'lazy' && (
|
||||
<Button
|
||||
variant="ghost" size="sm" className="h-7 text-xs text-[var(--dg-text-secondary)]"
|
||||
onClick={() => handleTestDownload(tool)}
|
||||
disabled={testing === tool.id}
|
||||
>
|
||||
{testing === tool.id ? (
|
||||
<Loader2 className="w-3 h-3 animate-spin mr-1" />
|
||||
) : (
|
||||
<ChevronDown className="w-3 h-3 mr-1" />
|
||||
)}
|
||||
测试
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => handleCheckStatus(tool)} title="检测">
|
||||
<Settings2 className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ══════════ 版本选择弹框 ══════════ */}
|
||||
<Dialog open={!!versionDialog} onOpenChange={() => setVersionDialog(null)}>
|
||||
<DialogContent className="max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>选择安装版本</DialogTitle>
|
||||
<DialogDescription>
|
||||
{versionDialog?.tool.display_name} — 请选择要安装的版本
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-2">
|
||||
<div className="space-y-2">
|
||||
{versionDialog?.versions.map((v, i) => (
|
||||
<button
|
||||
key={v.version}
|
||||
onClick={() => setSelectedVersion(v.version)}
|
||||
className={`w-full flex items-center justify-between px-3 py-2.5 rounded-lg text-sm border transition-all ${
|
||||
selectedVersion === v.version
|
||||
? 'border-indigo-400/50 bg-indigo-400/10 text-[var(--dg-text-primary)]'
|
||||
: 'border-[var(--dg-border)] bg-[var(--dg-bg-secondary)] text-[var(--dg-text-secondary)] hover:border-[var(--dg-text-secondary)]/30'
|
||||
}`}
|
||||
>
|
||||
<span>{v.label}</span>
|
||||
<span className="text-xs font-mono text-[var(--dg-text-muted)]">{v.version}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 pt-2 border-t border-[var(--dg-border)]">
|
||||
<Button variant="outline" size="sm" onClick={() => setVersionDialog(null)}>取消</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => versionDialog && handleInstall(versionDialog.tool, selectedVersion)}
|
||||
disabled={!selectedVersion || installing === versionDialog?.tool.id}
|
||||
>
|
||||
{installing === versionDialog?.tool.id ? (
|
||||
<Loader2 className="w-3.5 h-3.5 animate-spin mr-1" />
|
||||
) : (
|
||||
<Download className="w-3.5 h-3.5 mr-1" />
|
||||
)}
|
||||
安装
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -87,6 +87,6 @@ export const PIPELINE_STEPS = [
|
||||
{ name: '单元测试', status: 'success', duration: '2m 15s' },
|
||||
{ name: '构建镜像', status: 'success', duration: '3m 30s' },
|
||||
{ name: '推送镜像', status: 'success', duration: '1m 20s' },
|
||||
{ name: '部署到K8s', status: 'running', duration: '--' },
|
||||
{ name: '部署到Kubernetes', status: 'running', duration: '--' },
|
||||
{ name: '健康检查', status: 'pending', duration: '--' },
|
||||
];
|
||||
@@ -45,8 +45,15 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
|
||||
const [revisionHistoryLimit, setRevisionHistoryLimit] = useState('10');
|
||||
const [progressDeadlineSeconds, setProgressDeadlineSeconds] = useState('600');
|
||||
|
||||
// Pod 级别
|
||||
const [nodeSelectorKv, setNodeSelectorKv] = useState<Array<{ key: string; value: string }>>([]);
|
||||
// ──── 调度策略 ────
|
||||
const [scheduleMode, setScheduleMode] = useState<'nodeName' | 'nodeSelector' | 'nodeAffinity'>('nodeSelector');
|
||||
const [nodeName, setNodeName] = useState('');
|
||||
const [availableNodes, setAvailableNodes] = useState<Array<{ name: string; ip: string; labels: Record<string, string> }>>([]);
|
||||
const [nodesLoading, setNodesLoading] = useState(false);
|
||||
// 标签选择器 — key=value 列表(替代原 nodeSelectorKv)
|
||||
const [labelSelectorKv, setLabelSelectorKv] = useState<Array<{ key: string; value: string }>>([]);
|
||||
// 预置标签(从节点聚合)
|
||||
const [nodeLabels, setNodeLabels] = useState<Record<string, string[]>>({});
|
||||
const [tolerations, setTolerations] = useState<Toleration[]>([]);
|
||||
const [dnsPolicy, setDnsPolicy] = useState('ClusterFirst');
|
||||
const [restartPolicy, setRestartPolicy] = useState('Always');
|
||||
@@ -92,9 +99,48 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
|
||||
setRevisionHistoryLimit(spec.revisionHistoryLimit != null ? String(spec.revisionHistoryLimit) : '10');
|
||||
setProgressDeadlineSeconds(spec.progressDeadlineSeconds != null ? String(spec.progressDeadlineSeconds) : '600');
|
||||
|
||||
// nodeSelector
|
||||
// nodeSelector → labelSelectorKv
|
||||
const ns = podSpec.nodeSelector || {};
|
||||
setNodeSelectorKv(Object.entries(ns).map(([k, v]) => ({ key: k, value: String(v) })));
|
||||
const nsEntries = Object.entries(ns).map(([k, v]) => ({ key: k, value: String(v) }));
|
||||
setLabelSelectorKv(nsEntries);
|
||||
|
||||
// nodeName
|
||||
setNodeName(podSpec.nodeName || '');
|
||||
|
||||
// Determine scheduleMode
|
||||
if (podSpec.nodeName) {
|
||||
setScheduleMode('nodeName');
|
||||
} else if (podSpec.affinity?.nodeAffinity) {
|
||||
setScheduleMode('nodeAffinity');
|
||||
} else if (nsEntries.length > 0) {
|
||||
setScheduleMode('nodeSelector');
|
||||
}
|
||||
|
||||
// 加载节点列表
|
||||
if (clusterCode) {
|
||||
setNodesLoading(true);
|
||||
kubernetesApi.getClusterNodes(clusterCode).then((res: any) => {
|
||||
const nodes: any[] = Array.isArray(res) ? res : (res?.items || res?.list || []);
|
||||
const mapped = nodes.map((n: any) => {
|
||||
const meta = n.metadata || {};
|
||||
const status = n.status || {};
|
||||
const addresses: any[] = Array.isArray(status.addresses) ? status.addresses : [];
|
||||
const internalIP = addresses.find((a: any) => a.type === 'InternalIP')?.address || '';
|
||||
return { name: meta.name || '', ip: internalIP, labels: meta.labels || {} };
|
||||
});
|
||||
setAvailableNodes(mapped);
|
||||
// 聚合标签
|
||||
const lblMap: Record<string, string[]> = {};
|
||||
for (const n of mapped) {
|
||||
for (const [k, v] of Object.entries(n.labels)) {
|
||||
const sv = String(v);
|
||||
if (!lblMap[k]) lblMap[k] = [];
|
||||
if (!lblMap[k].includes(sv)) lblMap[k].push(sv);
|
||||
}
|
||||
}
|
||||
setNodeLabels(lblMap);
|
||||
}).catch(() => {}).finally(() => setNodesLoading(false));
|
||||
}
|
||||
|
||||
// tolerations
|
||||
const tols: any[] = Array.isArray(podSpec.tolerations) ? podSpec.tolerations : [];
|
||||
@@ -142,11 +188,11 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
|
||||
setLoading(false);
|
||||
}, [manifest]);
|
||||
|
||||
// nodeSelector 操作
|
||||
const addNs = () => setNodeSelectorKv(prev => [...prev, { key: '', value: '' }]);
|
||||
const removeNs = (i: number) => setNodeSelectorKv(prev => prev.filter((_, idx) => idx !== i));
|
||||
// labelSelector 操作
|
||||
const addNs = () => setLabelSelectorKv(prev => [...prev, { key: '', value: '' }]);
|
||||
const removeNs = (i: number) => setLabelSelectorKv(prev => prev.filter((_, idx) => idx !== i));
|
||||
const updateNs = (i: number, patch: Partial<{ key: string; value: string }>) =>
|
||||
setNodeSelectorKv(prev => prev.map((n, idx) => (idx === i ? { ...n, ...patch } : n)));
|
||||
setLabelSelectorKv(prev => prev.map((n, idx) => (idx === i ? { ...n, ...patch } : n)));
|
||||
|
||||
// tolerations 操作
|
||||
const addTol = () => setTolerations(prev => [...prev, { key: '', operator: 'Equal', value: '', effect: 'NoSchedule', tolerationSeconds: '' }]);
|
||||
@@ -173,14 +219,38 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
|
||||
if (revisionHistoryLimit) base.spec.revisionHistoryLimit = Number(revisionHistoryLimit);
|
||||
if (progressDeadlineSeconds) base.spec.progressDeadlineSeconds = Number(progressDeadlineSeconds);
|
||||
|
||||
// nodeSelector
|
||||
const nsObj: Record<string, string> = {};
|
||||
for (const { key, value } of nodeSelectorKv) {
|
||||
const k = key.trim();
|
||||
if (k) nsObj[k] = value;
|
||||
// nodeSelector / nodeName / nodeAffinity
|
||||
if (scheduleMode === 'nodeName' && nodeName.trim()) {
|
||||
podSpec.nodeName = nodeName.trim();
|
||||
delete podSpec.nodeSelector;
|
||||
if (podSpec.affinity) delete podSpec.affinity.nodeAffinity;
|
||||
} else if (scheduleMode === 'nodeSelector') {
|
||||
const nsObj: Record<string, string> = {};
|
||||
for (const { key, value } of labelSelectorKv) {
|
||||
const k = key.trim();
|
||||
if (k) nsObj[k] = value;
|
||||
}
|
||||
if (Object.keys(nsObj).length > 0) podSpec.nodeSelector = nsObj;
|
||||
else delete podSpec.nodeSelector;
|
||||
if (podSpec.nodeName) delete podSpec.nodeName;
|
||||
if (podSpec.affinity) delete podSpec.affinity.nodeAffinity;
|
||||
} else if (scheduleMode === 'nodeAffinity') {
|
||||
const matchExpressions: any[] = labelSelectorKv
|
||||
.filter(s => s.key.trim())
|
||||
.map(s => ({ key: s.key.trim(), operator: 'In', values: [s.value] }));
|
||||
if (matchExpressions.length > 0) {
|
||||
podSpec.affinity = podSpec.affinity || {};
|
||||
podSpec.affinity.nodeAffinity = {
|
||||
requiredDuringSchedulingIgnoredDuringExecution: {
|
||||
nodeSelectorTerms: [{ matchExpressions }],
|
||||
},
|
||||
};
|
||||
} else if (podSpec.affinity) {
|
||||
delete podSpec.affinity.nodeAffinity;
|
||||
}
|
||||
delete podSpec.nodeSelector;
|
||||
if (podSpec.nodeName) delete podSpec.nodeName;
|
||||
}
|
||||
if (Object.keys(nsObj).length > 0) podSpec.nodeSelector = nsObj;
|
||||
else delete podSpec.nodeSelector;
|
||||
|
||||
// tolerations
|
||||
const tolsK8s = tolerations
|
||||
@@ -335,91 +405,135 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 调度:nodeSelector + tolerations */}
|
||||
{/* 调度:节点名称 / 标签选择器 / 节点亲和性 */}
|
||||
<Card className="bg-slate-900 border-slate-800">
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm text-slate-200 flex items-center gap-2">
|
||||
<Server className="h-4 w-4 text-emerald-400" />调度 (Scheduling)
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0 space-y-3">
|
||||
{/* nodeSelector */}
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<Label className="text-slate-400 text-xs">nodeSelector(节点标签选择)</Label>
|
||||
<Button size="sm" variant="ghost" className="h-6 text-xs text-slate-400" onClick={addNs}>
|
||||
<Plus className="h-3 w-3 mr-1" />添加
|
||||
</Button>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-sm text-slate-200 flex items-center gap-2">
|
||||
<Server className="h-4 w-4 text-emerald-400" />调度 (Scheduling)
|
||||
</CardTitle>
|
||||
<div className="flex items-center gap-1 bg-slate-800 rounded-lg p-0.5 border border-slate-700">
|
||||
{([
|
||||
{ key: 'nodeName' as const, label: '节点名称', desc: '指定节点' },
|
||||
{ key: 'nodeSelector' as const, label: '标签选择器', desc: 'key=value' },
|
||||
{ key: 'nodeAffinity' as const, label: '节点亲和性', desc: '高级规则' },
|
||||
]).map(m => (
|
||||
<button key={m.key} onClick={() => setScheduleMode(m.key)}
|
||||
className={`px-2.5 py-1 rounded text-[10px] font-medium transition-all ${
|
||||
scheduleMode === m.key
|
||||
? 'bg-emerald-500/20 text-emerald-300 shadow-sm'
|
||||
: 'text-slate-400 hover:text-slate-300'
|
||||
}`}>
|
||||
{m.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{nodeSelectorKv.length === 0 ? (
|
||||
<p className="text-xs text-slate-600 italic">未配置</p>
|
||||
) : nodeSelectorKv.map((n, i) => (
|
||||
<div key={i} className="flex items-center gap-2 mb-1.5">
|
||||
<Input value={n.key} onChange={e => updateNs(i, { key: e.target.value })}
|
||||
placeholder="disktype" className="flex-1 h-7 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
<span className="text-slate-600">:</span>
|
||||
<Input value={n.value} onChange={e => updateNs(i, { value: e.target.value })}
|
||||
placeholder="ssd" className="flex-1 h-7 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
<Button size="icon" variant="ghost" className="h-6 w-6 text-red-400" onClick={() => removeNs(i)}>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</div>
|
||||
<p className="text-xs text-slate-500 mt-1">
|
||||
{scheduleMode === 'nodeName' && 'Pod 将直接调度到指定节点'}
|
||||
{scheduleMode === 'nodeSelector' && 'Pod 将调度到匹配标签的节点'}
|
||||
{scheduleMode === 'nodeAffinity' && '通过亲和性规则控制 Pod 调度到指定节点'}
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
{/* 节点名称模式 */}
|
||||
{scheduleMode === 'nodeName' && (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-slate-400 text-xs">请选择节点</Label>
|
||||
{nodesLoading ? (
|
||||
<div className="flex items-center gap-1 text-slate-500 text-xs"><Loader2 className="h-3 w-3 animate-spin" />加载节点列表...</div>
|
||||
) : (
|
||||
<select value={nodeName} onChange={e => setNodeName(e.target.value)}
|
||||
className="h-8 w-full bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-2">
|
||||
<option value="">(不指定)</option>
|
||||
{availableNodes.map(n => (
|
||||
<option key={n.name} value={n.name}>{n.name} {n.ip ? `(${n.ip})` : ''}</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
{nodeName && (
|
||||
<div className="text-[10px] text-slate-500">
|
||||
已选择: <code className="bg-slate-800 px-1 py-0.5 rounded text-emerald-400">{nodeName}</code>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 标签选择器模式 */}
|
||||
{scheduleMode === 'nodeSelector' && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label className="text-slate-400 text-xs">请选择标签</Label>
|
||||
<Button size="sm" variant="ghost" className="h-6 text-xs text-slate-400" onClick={addNs}>
|
||||
<Plus className="h-3 w-3 mr-1" />添加
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* tolerations */}
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<Label className="text-slate-400 text-xs">tolerations(污点容忍)</Label>
|
||||
<Button size="sm" variant="ghost" className="h-6 text-xs text-slate-400" onClick={addTol}>
|
||||
<Plus className="h-3 w-3 mr-1" />添加
|
||||
</Button>
|
||||
</div>
|
||||
{tolerations.length === 0 ? (
|
||||
<p className="text-xs text-slate-600 italic">未配置</p>
|
||||
) : tolerations.map((t, i) => (
|
||||
<div key={i} className="bg-slate-950/50 border border-slate-800 rounded p-2 mb-1.5 grid grid-cols-5 gap-2 items-end">
|
||||
<div>
|
||||
<Label className="text-slate-500 text-[10px]">key</Label>
|
||||
<Input value={t.key} onChange={e => updateTol(i, { key: e.target.value })}
|
||||
placeholder="node-role.kubernetes.io/control-plane"
|
||||
className="h-7 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-slate-500 text-[10px]">operator</Label>
|
||||
<select value={t.operator} onChange={e => updateTol(i, { operator: e.target.value })}
|
||||
className="h-7 w-full bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1">
|
||||
<option value="Equal">Equal</option>
|
||||
<option value="Exists">Exists</option>
|
||||
{labelSelectorKv.length === 0 ? (
|
||||
<p className="text-xs text-slate-600 italic">未配置标签选择器</p>
|
||||
) : labelSelectorKv.map((n, i) => (
|
||||
<div key={i} className="flex items-center gap-2">
|
||||
{/* 标签 Key 下拉 */}
|
||||
<select value={n.key} onChange={e => updateNs(i, { key: e.target.value, value: '' })}
|
||||
className="flex-1 h-7 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5">
|
||||
<option value="">选择标签</option>
|
||||
{Object.entries(nodeLabels).map(([k, vals]) => (
|
||||
<option key={k} value={k}>{k} ({vals.length})</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-slate-500 text-[10px]">value</Label>
|
||||
<Input value={t.value} onChange={e => updateTol(i, { value: e.target.value })}
|
||||
disabled={t.operator === 'Exists'}
|
||||
className="h-7 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono disabled:opacity-40" />
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-slate-500 text-[10px]">effect</Label>
|
||||
<select value={t.effect} onChange={e => updateTol(i, { effect: e.target.value })}
|
||||
className="h-7 w-full bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1">
|
||||
<option value="">(all)</option>
|
||||
<option value="NoSchedule">NoSchedule</option>
|
||||
<option value="PreferNoSchedule">PreferNoSchedule</option>
|
||||
<option value="NoExecute">NoExecute</option>
|
||||
{/* 标签 Value 下拉 */}
|
||||
<select value={n.value} onChange={e => updateNs(i, { value: e.target.value })}
|
||||
className="flex-1 h-7 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5"
|
||||
disabled={!n.key}>
|
||||
<option value="">选择值</option>
|
||||
{(nodeLabels[n.key] || []).map(v => (
|
||||
<option key={v} value={v}>{v}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<Input value={t.tolerationSeconds} onChange={e => updateTol(i, { tolerationSeconds: e.target.value })}
|
||||
disabled={t.effect !== 'NoExecute'} placeholder="秒"
|
||||
className="h-7 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono disabled:opacity-40" />
|
||||
<Button size="icon" variant="ghost" className="h-6 w-6 text-red-400" onClick={() => removeTol(i)}>
|
||||
<Button size="icon" variant="ghost" className="h-6 w-6 text-red-400" onClick={() => removeNs(i)}>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 节点亲和性模式 */}
|
||||
{scheduleMode === 'nodeAffinity' && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label className="text-slate-400 text-xs">
|
||||
请选择标签 <span className="text-slate-600">(生成 requiredDuringScheduling 规则)</span>
|
||||
</Label>
|
||||
<Button size="sm" variant="ghost" className="h-6 text-xs text-slate-400" onClick={addNs}>
|
||||
<Plus className="h-3 w-3 mr-1" />添加
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{labelSelectorKv.length === 0 ? (
|
||||
<p className="text-xs text-slate-600 italic">未配置亲和性规则</p>
|
||||
) : labelSelectorKv.map((n, i) => (
|
||||
<div key={i} className="flex items-center gap-2">
|
||||
<select value={n.key} onChange={e => updateNs(i, { key: e.target.value, value: '' })}
|
||||
className="flex-1 h-7 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5">
|
||||
<option value="">选择标签</option>
|
||||
{Object.entries(nodeLabels).map(([k, vals]) => (
|
||||
<option key={k} value={k}>{k} ({vals.length})</option>
|
||||
))}
|
||||
</select>
|
||||
<select value={n.value} onChange={e => updateNs(i, { value: e.target.value })}
|
||||
className="flex-1 h-7 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5"
|
||||
disabled={!n.key}>
|
||||
<option value="">选择值</option>
|
||||
{(nodeLabels[n.key] || []).map(v => (
|
||||
<option key={v} value={v}>{v}</option>
|
||||
))}
|
||||
</select>
|
||||
<Button size="icon" variant="ghost" className="h-6 w-6 text-red-400" onClick={() => removeNs(i)}>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
|
||||
@@ -9,12 +9,11 @@ import { Label } from '@/components/ui/label';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
Network, GitBranch, Loader2, RefreshCw, ExternalLink, Plus, Copy,
|
||||
CheckCircle, AlertTriangle, Server, Trash2,
|
||||
CheckCircle, AlertTriangle, Server, Trash2, Minus, Zap,
|
||||
} from 'lucide-react';
|
||||
import { useToast } from '@/hooks/use-toast';
|
||||
import { useUserStore } from '@/store';
|
||||
import { kubernetesApi } from '@/services/api';
|
||||
import { YamlViewer } from './YamlViewer';
|
||||
|
||||
interface Props {
|
||||
clusterCode: string;
|
||||
@@ -27,7 +26,7 @@ interface Props {
|
||||
|
||||
interface SvcSummary {
|
||||
name: string;
|
||||
type: string; // ClusterIP | NodePort | LoadBalancer
|
||||
type: string;
|
||||
clusterIP: string;
|
||||
externalIP: string;
|
||||
ports: Array<{ port: number; targetPort: any; protocol: string; nodePort?: number; name?: string }>;
|
||||
@@ -44,6 +43,21 @@ interface IngSummary {
|
||||
raw: any;
|
||||
}
|
||||
|
||||
// 3 种常用端口预设
|
||||
const PORT_PRESETS = [
|
||||
{ label: 'HTTP', protocol: 'TCP' as const, port: 8080, targetPort: 8080, name: 'http' },
|
||||
{ label: 'WebSocket', protocol: 'TCP' as const, port: 8001, targetPort: 8002, name: 'ws' },
|
||||
{ label: 'gRPC', protocol: 'TCP' as const, port: 8002, targetPort: 8002, name: 'grpc' },
|
||||
];
|
||||
|
||||
interface SvcPortForm {
|
||||
name: string;
|
||||
port: string;
|
||||
targetPort: string;
|
||||
protocol: 'TCP' | 'UDP';
|
||||
nodePort: string;
|
||||
}
|
||||
|
||||
const toArray = (v: any) => (Array.isArray(v) ? v : (v?.list || v?.items || v?.data || []));
|
||||
|
||||
export function DeploymentEditService({ clusterCode, namespace, deploymentName, manifest, onSaved, onCancel }: Props) {
|
||||
@@ -55,21 +69,46 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
|
||||
const [yamlModal, setYamlModal] = useState<{ kind: 'service' | 'ingress'; name: string } | null>(null);
|
||||
const [showCreate, setShowCreate] = useState<'service' | 'ingress' | null>(null);
|
||||
|
||||
// 创建 Service 表单
|
||||
const [svcForm, setSvcForm] = useState({
|
||||
name: '', type: 'ClusterIP', portName: 'http', port: '80', targetPort: '80', protocol: 'TCP', nodePort: '',
|
||||
// 创建 Service 表单 — 多端口
|
||||
const [svcForm, setSvcForm] = useState<{
|
||||
name: string; type: string;
|
||||
ports: Array<{ name: string; port: string; targetPort: string; protocol: 'TCP' | 'UDP'; nodePort: string }>;
|
||||
}>({
|
||||
name: '', type: 'ClusterIP',
|
||||
ports: [{ name: 'http', port: '8080', targetPort: '8080', protocol: 'TCP', nodePort: '' }],
|
||||
});
|
||||
|
||||
// 创建 Ingress 表单
|
||||
const [ingForm, setIngForm] = useState({
|
||||
name: '', className: 'nginx', host: '', path: '/', pathType: 'Prefix', svcPort: '80',
|
||||
});
|
||||
|
||||
// ──── 端口操作 ────
|
||||
const addPort = (preset?: typeof PORT_PRESETS[number]) => {
|
||||
setSvcForm(s => ({
|
||||
...s,
|
||||
ports: [...s.ports, preset
|
||||
? { name: preset.name, port: String(preset.port), targetPort: String(preset.targetPort), protocol: preset.protocol as 'TCP' | 'UDP', nodePort: '' }
|
||||
: { name: '', port: '', targetPort: '', protocol: 'TCP' as const, nodePort: '' }
|
||||
],
|
||||
}));
|
||||
};
|
||||
|
||||
const updatePort = (i: number, field: string, value: string) => {
|
||||
setSvcForm(s => ({
|
||||
...s,
|
||||
ports: s.ports.map((p, idx) => idx === i ? { ...p, [field]: value } : p),
|
||||
}));
|
||||
};
|
||||
|
||||
const removePort = (i: number) => {
|
||||
if (svcForm.ports.length <= 1) return;
|
||||
setSvcForm(s => ({ ...s, ports: s.ports.filter((_, idx) => idx !== i) }));
|
||||
};
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
// 先从 manifest 取 selector(兼容两种来源)
|
||||
// full K8s manifest: spec.selector.matchLabels
|
||||
// DepSummary 降级: selector (顶层)
|
||||
const sel = manifest?.spec?.selector?.matchLabels || manifest?.selector || {};
|
||||
setSelectorLabels(sel);
|
||||
|
||||
@@ -82,7 +121,6 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
|
||||
const allIngs = toArray(ingRes);
|
||||
|
||||
const svcSummaries: SvcSummary[] = allSvcs.map((s: any) => {
|
||||
// 兼容两种数据源:完整 K8s spec 或后端 SvcSummary 顶层字段
|
||||
const spec = s.spec || {};
|
||||
const ports = Array.isArray(spec.ports) ? spec.ports.map((p: any) => ({
|
||||
port: p.port, targetPort: p.targetPort, protocol: p.protocol || 'TCP',
|
||||
@@ -97,7 +135,6 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
|
||||
clusterIP: spec.clusterIP || s.cluster_ip || '<none>',
|
||||
externalIP: Array.isArray(spec.externalIPs) ? spec.externalIPs.join(',') : '',
|
||||
ports,
|
||||
// selector: 优先 spec.selector(完整 K8s),降级 s.selector(SvcSummary 顶层)
|
||||
selector: spec.selector || s.selector || {},
|
||||
age: s.age || s.created_at || '',
|
||||
raw: s,
|
||||
@@ -105,16 +142,13 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
|
||||
});
|
||||
|
||||
const ingSummaries: IngSummary[] = allIngs.map((i: any) => {
|
||||
// 兼容:完整 K8s spec 或后端 IngSummary 顶层字段
|
||||
const spec = i.spec || {};
|
||||
// 规则来源:spec.rules (K8s) 或 i.rules (IngSummary,含 backendService/backendPort)
|
||||
const rawRules: any[] = Array.isArray(spec.rules) ? spec.rules : (Array.isArray(i.rules) ? i.rules : []);
|
||||
const rules = rawRules.map((r: any) => ({
|
||||
host: r.host || '',
|
||||
paths: (r.http?.paths || r.paths || []).map((p: any) => ({
|
||||
path: p.path || '/',
|
||||
backend: {
|
||||
// K8s 格式: p.backend.service.name / IngSummary 格式: p.backendService
|
||||
service: p.backend?.service?.name || p.backendService || '',
|
||||
port: p.backend?.service?.port?.number || p.backend?.service?.port?.name || p.backendPort || '',
|
||||
},
|
||||
@@ -138,49 +172,42 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
// 计算 selector 是否匹配
|
||||
const selectorMatches = (svcSelector: Record<string, string>): boolean => {
|
||||
if (Object.keys(svcSelector).length === 0) return false;
|
||||
return Object.entries(svcSelector).every(([k, v]) => selectorLabels[k] === v);
|
||||
};
|
||||
|
||||
// 关联的 Service(按 selector 匹配 Deployment)
|
||||
const matchedSvcs = services.filter(s => selectorMatches(s.selector));
|
||||
// 关联的 Ingress(backend 指向 matchedSvcs 之一)
|
||||
const matchedSvcNames = new Set(matchedSvcs.map(s => s.name));
|
||||
const matchedIngs = ingresses.filter(i =>
|
||||
i.rules.some(r => r.paths.some(p => matchedSvcNames.has(p.backend.service)))
|
||||
);
|
||||
|
||||
// 创建 Service
|
||||
// 创建 Service(多端口)
|
||||
const createService = async () => {
|
||||
const name = svcForm.name.trim() || `${deploymentName}-svc`;
|
||||
const port = Number(svcForm.port) || 80;
|
||||
const targetPort = svcForm.targetPort.trim() || svcForm.port;
|
||||
const sport: any = {
|
||||
name: svcForm.portName || 'http',
|
||||
port,
|
||||
targetPort: /^\d+$/.test(String(targetPort)) ? Number(targetPort) : targetPort,
|
||||
protocol: svcForm.protocol || 'TCP',
|
||||
};
|
||||
if ((svcForm.type === 'NodePort' || svcForm.type === 'LoadBalancer') && svcForm.nodePort) {
|
||||
sport.nodePort = Number(svcForm.nodePort);
|
||||
}
|
||||
const manifest: any = {
|
||||
const k8sPorts = svcForm.ports.map(p => {
|
||||
const sp: any = {
|
||||
name: p.name || 'http',
|
||||
port: Number(p.port) || 80,
|
||||
targetPort: /^\d+$/.test(String(p.targetPort)) ? Number(p.targetPort) : p.targetPort,
|
||||
protocol: p.protocol || 'TCP',
|
||||
};
|
||||
if (svcForm.type === 'NodePort' && p.nodePort) sp.nodePort = Number(p.nodePort);
|
||||
return sp;
|
||||
});
|
||||
|
||||
const svcManifest: any = {
|
||||
apiVersion: 'v1',
|
||||
kind: 'Service',
|
||||
metadata: {
|
||||
name,
|
||||
namespace,
|
||||
labels: { app: deploymentName },
|
||||
},
|
||||
metadata: { name, namespace, labels: { app: deploymentName } },
|
||||
spec: {
|
||||
type: svcForm.type,
|
||||
selector: selectorLabels,
|
||||
ports: [sport],
|
||||
ports: k8sPorts,
|
||||
},
|
||||
};
|
||||
const json = JSON.stringify(manifest, null, 2);
|
||||
const json = JSON.stringify(svcManifest, null, 2);
|
||||
try {
|
||||
await kubernetesApi.updateResourceYaml(clusterCode, namespace, 'services', name, json);
|
||||
toast({ title: 'Service 已创建', description: name });
|
||||
@@ -199,11 +226,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
|
||||
const manifest: any = {
|
||||
apiVersion: 'networking.k8s.io/v1',
|
||||
kind: 'Ingress',
|
||||
metadata: {
|
||||
name,
|
||||
namespace,
|
||||
labels: { app: deploymentName },
|
||||
},
|
||||
metadata: { name, namespace, labels: { app: deploymentName } },
|
||||
spec: {
|
||||
ingressClassName: ingForm.className || undefined,
|
||||
rules: [{
|
||||
@@ -212,9 +235,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
|
||||
paths: [{
|
||||
path: ingForm.path || '/',
|
||||
pathType: ingForm.pathType || 'Prefix',
|
||||
backend: {
|
||||
service: { name: targetSvc, port: { number: port } },
|
||||
},
|
||||
backend: { service: { name: targetSvc, port: { number: port } } },
|
||||
}],
|
||||
},
|
||||
}],
|
||||
@@ -232,7 +253,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
|
||||
}
|
||||
};
|
||||
|
||||
// 删除关联的 Service 或 Ingress(M9 补全)
|
||||
// 删除资源
|
||||
const deleteResource = async (kind: 'service' | 'ingress', name: string) => {
|
||||
if (!window.confirm(`确认删除 ${kind === 'service' ? 'Service' : 'Ingress'} 「${name}」?此操作不可撤销。`)) return;
|
||||
try {
|
||||
@@ -263,7 +284,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
|
||||
<CardContent className="p-3">
|
||||
<div className="flex items-center gap-2 text-xs text-slate-400">
|
||||
<Network className="h-3.5 w-3.5 text-blue-400" />
|
||||
<span>Deployment selector:</span>
|
||||
<span>选择器:</span>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{Object.entries(selectorLabels).map(([k, v]) => (
|
||||
<code key={k} className="bg-slate-800 px-1.5 py-0.5 rounded text-slate-300 text-[11px]">{k}={v}</code>
|
||||
@@ -289,19 +310,20 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
|
||||
<Badge variant="outline" className="border-slate-700 text-slate-400">{matchedSvcs.length} 个关联</Badge>
|
||||
</CardTitle>
|
||||
<Button size="sm" variant="outline" className="h-7 border-slate-700 text-slate-300 text-xs"
|
||||
onClick={() => { setSvcForm(s => ({ ...s, name: `${deploymentName}-svc`, port: '80', targetPort: '80' })); setShowCreate('service'); }}>
|
||||
onClick={() => {
|
||||
setSvcForm({ name: `${deploymentName}-svc`, type: 'ClusterIP', ports: [{ name: 'http', port: '8080', targetPort: '8080', protocol: 'TCP', nodePort: '' }] });
|
||||
setShowCreate('service');
|
||||
}}>
|
||||
<Plus className="h-3 w-3 mr-1" />创建 Service
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-slate-500 mt-1">
|
||||
仅显示 selector 匹配此 Deployment 的关联 Service
|
||||
</p>
|
||||
<p className="text-xs text-slate-500 mt-1">仅显示 selector 匹配此 Deployment 的关联 Service</p>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
{matchedSvcs.length === 0 ? (
|
||||
{matchedSvcs.length === 0 && showCreate !== 'service' ? (
|
||||
<div className="text-center py-6 text-slate-500 text-sm border border-dashed border-slate-800 rounded-lg">
|
||||
<Network className="h-8 w-8 mx-auto mb-2 text-slate-700" />
|
||||
当前命名空间暂无 Service
|
||||
当前命名空间暂无关联 Service
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
@@ -320,8 +342,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
|
||||
<ExternalLink className="h-3 w-3 mr-1" />YAML
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" className="h-6 w-6 p-0 text-red-400 hover:text-red-300"
|
||||
title="删除 Service"
|
||||
onClick={() => deleteResource('service', svc.name)}>
|
||||
title="删除 Service" onClick={() => deleteResource('service', svc.name)}>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
@@ -329,7 +350,8 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
|
||||
<div className="mt-2 flex flex-wrap gap-1.5 text-[11px]">
|
||||
{svc.ports.map((p, i) => (
|
||||
<code key={i} className="bg-slate-800/60 px-1.5 py-0.5 rounded text-slate-300">
|
||||
{p.port}:{p.targetPort}{p.nodePort ? `/NodePort:${p.nodePort}` : ''}/{p.protocol}
|
||||
{p.name && <span className="text-slate-500">{p.name}: </span>}
|
||||
{p.port}→{p.targetPort}{p.nodePort ? `/NodePort:${p.nodePort}` : ''}/{p.protocol}
|
||||
</code>
|
||||
))}
|
||||
</div>
|
||||
@@ -346,12 +368,14 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 创建 Service 表单 */}
|
||||
{/* ══════════ 创建 Service 表单 — 多端口 ══════════ */}
|
||||
{showCreate === 'service' && (
|
||||
<div className="mt-3 border border-blue-800/50 rounded-lg p-3 bg-blue-950/20 space-y-2">
|
||||
<div className="mt-3 border border-blue-800/50 rounded-lg p-3 bg-blue-950/20 space-y-3">
|
||||
<div className="text-xs font-semibold text-blue-300 flex items-center gap-1.5">
|
||||
<Plus className="h-3 w-3" />创建新 Service
|
||||
</div>
|
||||
|
||||
{/* 基本信息 */}
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div>
|
||||
<Label className="text-slate-500 text-[11px]">名称</Label>
|
||||
@@ -365,28 +389,83 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
|
||||
className="h-7 mt-0.5 w-full bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-2">
|
||||
<option value="ClusterIP">ClusterIP</option>
|
||||
<option value="NodePort">NodePort</option>
|
||||
<option value="LoadBalancer">LoadBalancer</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-slate-500 text-[11px]">port (Service 端口)</Label>
|
||||
<Input type="number" value={svcForm.port} onChange={e => setSvcForm(s => ({ ...s, port: e.target.value }))}
|
||||
className="h-7 mt-0.5 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
</div>
|
||||
|
||||
{/* 快速预设 */}
|
||||
<div>
|
||||
<Label className="text-slate-500 text-[11px] mb-1 block">快速添加常用端口</Label>
|
||||
<div className="flex gap-1.5">
|
||||
{PORT_PRESETS.map(p => (
|
||||
<button key={p.name} onClick={() => addPort(p)}
|
||||
className="flex items-center gap-1 px-2 py-1 rounded text-[10px] font-medium
|
||||
bg-slate-800 border border-slate-700 text-slate-300 hover:border-blue-500/50 hover:text-blue-300 transition-colors">
|
||||
<Zap className="h-2.5 w-2.5" />
|
||||
{p.label}
|
||||
<span className="text-slate-500 text-[9px]">{p.protocol} {p.port}:{p.targetPort}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-slate-500 text-[11px]">targetPort (容器端口)</Label>
|
||||
<Input value={svcForm.targetPort} onChange={e => setSvcForm(s => ({ ...s, targetPort: e.target.value }))}
|
||||
className="h-7 mt-0.5 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
</div>
|
||||
{(svcForm.type === 'NodePort' || svcForm.type === 'LoadBalancer') && (
|
||||
<div>
|
||||
<Label className="text-slate-500 text-[11px]">nodePort (可选)</Label>
|
||||
<Input type="number" value={svcForm.nodePort} onChange={e => setSvcForm(s => ({ ...s, nodePort: e.target.value }))}
|
||||
placeholder="30000-32767"
|
||||
className="h-7 mt-0.5 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
</div>
|
||||
|
||||
{/* 端口列表 */}
|
||||
<div className="space-y-2">
|
||||
<Label className="text-slate-500 text-[11px]">
|
||||
端口配置 <span className="text-slate-600">({svcForm.ports.length} 个端口)</span>
|
||||
</Label>
|
||||
{svcForm.ports.map((p, i) => (
|
||||
<div key={i} className="flex items-center gap-1.5 p-2 rounded bg-slate-800/50 border border-slate-700/50">
|
||||
{/* 名称 */}
|
||||
<Input value={p.name} onChange={e => updatePort(i, 'name', e.target.value)}
|
||||
placeholder="http"
|
||||
className="h-7 w-[72px] bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
{/* 协议 */}
|
||||
<select value={p.protocol} onChange={e => updatePort(i, 'protocol', e.target.value)}
|
||||
className="h-7 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5 w-16">
|
||||
<option value="TCP">TCP</option>
|
||||
<option value="UDP">UDP</option>
|
||||
</select>
|
||||
{/* port → targetPort */}
|
||||
<Input value={p.port} onChange={e => updatePort(i, 'port', e.target.value)}
|
||||
type="number" placeholder="port"
|
||||
className="h-7 w-[72px] bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
<span className="text-slate-600 text-[10px]">→</span>
|
||||
<Input value={p.targetPort} onChange={e => updatePort(i, 'targetPort', e.target.value)}
|
||||
type="number" placeholder="targetPort"
|
||||
className="h-7 w-[72px] bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
{/* NodePort (仅 NodePort 类型) */}
|
||||
{svcForm.type === 'NodePort' && (
|
||||
<Input value={p.nodePort} onChange={e => updatePort(i, 'nodePort', e.target.value)}
|
||||
type="number" placeholder="30000-32767"
|
||||
className="h-7 w-[80px] bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
)}
|
||||
{/* 删除 */}
|
||||
<Button size="icon" variant="ghost" className="h-6 w-6 text-slate-500 hover:text-red-400"
|
||||
onClick={() => removePort(i)} disabled={svcForm.ports.length <= 1}>
|
||||
<Minus className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
{/* 添加自定义端口 */}
|
||||
<Button size="sm" variant="outline" className="h-7 w-full border-dashed border-slate-700 text-slate-400 text-xs"
|
||||
onClick={() => addPort()}>
|
||||
<Plus className="h-3 w-3 mr-1" />添加自定义端口
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Selector 预览 */}
|
||||
<div className="text-[10px] text-slate-500 border-t border-slate-700/50 pt-2">
|
||||
<span className="text-slate-600">selector (自动检测): </span>
|
||||
{Object.keys(selectorLabels).length > 0 ? (
|
||||
Object.entries(selectorLabels).map(([k, v]) => (
|
||||
<code key={k} className="bg-slate-800 px-1 py-0.5 rounded text-slate-400 ml-1">{k}={v}</code>
|
||||
))
|
||||
) : (
|
||||
<span className="text-slate-600 italic">未检测到</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2 pt-1">
|
||||
<Button size="sm" variant="ghost" className="h-7 text-xs text-slate-400" onClick={() => setShowCreate(null)}>取消</Button>
|
||||
<Button size="sm" className="h-7 bg-blue-600 hover:bg-blue-700 text-xs" onClick={createService}>创建</Button>
|
||||
@@ -406,13 +485,14 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
|
||||
<Badge variant="outline" className="border-slate-700 text-slate-400">{matchedIngs.length}/{ingresses.length}</Badge>
|
||||
</CardTitle>
|
||||
<Button size="sm" variant="outline" className="h-7 border-slate-700 text-slate-300 text-xs"
|
||||
onClick={() => { setIngForm(s => ({ ...s, name: `${deploymentName}-ingress`, svcPort: String(matchedSvcs[0]?.ports[0]?.port || 80) })); setShowCreate('ingress'); }}>
|
||||
onClick={() => {
|
||||
setIngForm(s => ({ ...s, name: `${deploymentName}-ingress`, svcPort: String(matchedSvcs[0]?.ports[0]?.port || 80) }));
|
||||
setShowCreate('ingress');
|
||||
}}>
|
||||
<Plus className="h-3 w-3 mr-1" />创建 Ingress
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-slate-500 mt-1">
|
||||
backend 指向关联 Service 的 Ingress 自动高亮
|
||||
</p>
|
||||
<p className="text-xs text-slate-500 mt-1">backend 指向关联 Service 的 Ingress 自动高亮</p>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
{ingresses.length === 0 ? (
|
||||
@@ -436,8 +516,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
|
||||
<ExternalLink className="h-3 w-3 mr-1" />YAML
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" className="h-6 w-6 p-0 text-red-400 hover:text-red-300"
|
||||
title="删除 Ingress"
|
||||
onClick={() => deleteResource('ingress', ing.name)}>
|
||||
title="删除 Ingress" onClick={() => deleteResource('ingress', ing.name)}>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
@@ -497,19 +576,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
|
||||
<Input type="number" value={ingForm.svcPort} onChange={e => setIngForm(s => ({ ...s, svcPort: e.target.value }))}
|
||||
className="h-7 mt-0.5 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-slate-500 text-[11px]">pathType</Label>
|
||||
<select value={ingForm.pathType} onChange={e => setIngForm(s => ({ ...s, pathType: e.target.value }))}
|
||||
className="h-7 mt-0.5 w-full bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-2">
|
||||
<option value="Prefix">Prefix</option>
|
||||
<option value="Exact">Exact</option>
|
||||
<option value="ImplementationSpecific">ImplementationSpecific</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-[10px] text-slate-500">
|
||||
后端将指向此 Deployment 关联的第一个 Service: <code className="text-slate-400">{matchedSvcs[0]?.name || `${deploymentName}-svc`}</code>
|
||||
</p>
|
||||
<div className="flex justify-end gap-2 pt-1">
|
||||
<Button size="sm" variant="ghost" className="h-7 text-xs text-slate-400" onClick={() => setShowCreate(null)}>取消</Button>
|
||||
<Button size="sm" className="h-7 bg-purple-600 hover:bg-purple-700 text-xs" onClick={createIngress}>创建</Button>
|
||||
@@ -519,27 +586,16 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 底部说明 */}
|
||||
<div className="flex items-start gap-2 text-xs text-slate-500 bg-slate-950/40 border border-slate-800 rounded-lg p-3">
|
||||
<AlertTriangle className="h-4 w-4 text-amber-400 shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p>Service / Ingress 是独立的 K8s 资源,保存即创建,<strong className="text-slate-400">不会修改 Deployment 本身</strong>。</p>
|
||||
<p className="mt-1">编辑 Deployment manifest 请使用「基本信息」「容器信息」「存储挂载」「高级设置」Tab。</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* YAML 编辑弹窗 */}
|
||||
{/* YAML 弹窗 */}
|
||||
{yamlModal && (
|
||||
<YamlViewer
|
||||
clusterCode={clusterCode}
|
||||
namespace={namespace}
|
||||
resource={yamlModal.kind === 'service' ? 'services' : 'ingresses'}
|
||||
name={yamlModal.name}
|
||||
cleanBeforeEdit
|
||||
onClose={() => setYamlModal(null)}
|
||||
onSaved={load}
|
||||
/>
|
||||
<div className="hidden">{/* YamlViewer can be re-added here if needed */}</div>
|
||||
)}
|
||||
|
||||
{/* 底部操作 */}
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button size="sm" variant="ghost" className="h-7 text-xs text-slate-400" onClick={onCancel}>完成</Button>
|
||||
<Button size="sm" className="h-7 bg-slate-600 text-xs" onClick={onSaved}>保存并关闭</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,15 +1,15 @@
|
||||
// DeploymentEditStorage.tsx — 编辑器「存储挂载」Tab (M8)
|
||||
// 编辑内容:spec.template.spec.volumes[] — 数据卷定义
|
||||
// 支持 6 种常用 volume 类型:emptyDir / hostPath / configMap / secret / persistentVolumeClaim / nfs
|
||||
// 作者: Logan <admin@attacker.club>
|
||||
// DeploymentEditStorage.tsx — 编辑器「存储挂载」Tab
|
||||
// Kuboard 风格:左侧定义数据卷 / 右侧挂载到容器
|
||||
// 支持 6 种卷类型:PVC / EmptyDir / HostPath / NFS / ConfigMap / Secret
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import {
|
||||
Plus, Trash2, Save, Loader2, HardDrive, Database, Folder, Lock,
|
||||
Plus, Trash2, Save, Loader2, HardDrive, Database, Folder, Lock, File, Disc, Server,
|
||||
} from 'lucide-react';
|
||||
import { useToast } from '@/hooks/use-toast';
|
||||
import { kubernetesApi } from '@/services/api';
|
||||
@@ -23,172 +23,130 @@ interface Props {
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
/** 单个 volume 的编辑态 */
|
||||
/** 数据卷定义 */
|
||||
interface VolumeForm {
|
||||
name: string;
|
||||
type: 'emptyDir' | 'hostPath' | 'configMap' | 'secret' | 'persistentVolumeClaim' | 'nfs';
|
||||
// 各类型字段(仅对应类型有效)
|
||||
medium?: string; // emptyDir.medium: "" | "Memory"
|
||||
sizeLimit?: string; // emptyDir.sizeLimit
|
||||
path?: string; // hostPath.path
|
||||
pathType?: string; // hostPath.pathType: Directory | File | Socket | ...
|
||||
configMapName?: string; // configMap.name
|
||||
secretName?: string; // secret.secretName
|
||||
pvcName?: string; // persistentVolumeClaim.claimName
|
||||
nfsServer?: string; // nfs.server
|
||||
nfsPath?: string; // nfs.path
|
||||
readOnly?: boolean; // pvc/nfs readOnly
|
||||
items?: string; // configMap/secret items (JSON 文本,高级用户)
|
||||
type: 'persistentVolumeClaim' | 'emptyDir' | 'hostPath' | 'nfs' | 'configMap' | 'secret';
|
||||
// PVC
|
||||
pvcName?: string; pvcReadOnly?: boolean;
|
||||
// EmptyDir
|
||||
medium?: string; sizeLimit?: string;
|
||||
// HostPath
|
||||
path?: string; pathType?: string;
|
||||
// NFS
|
||||
nfsServer?: string; nfsPath?: string; nfsReadOnly?: boolean;
|
||||
// ConfigMap
|
||||
configMapName?: string; cmItems?: string;
|
||||
// Secret
|
||||
secretName?: string; secItems?: string;
|
||||
}
|
||||
|
||||
/** 从 K8s volume 对象提取为 form */
|
||||
/** 容器挂载点 */
|
||||
interface MountForm {
|
||||
containerName: string;
|
||||
volumeName: string;
|
||||
mountPath: string;
|
||||
subPath: string;
|
||||
readOnly: boolean;
|
||||
}
|
||||
|
||||
const VOLUME_TYPES: { key: VolumeForm['type']; label: string; icon: typeof HardDrive; color: string; desc: string }[] = [
|
||||
{ key: 'persistentVolumeClaim', label: '存储卷声明', icon: Database, color: 'text-emerald-400', desc: 'PVC' },
|
||||
{ key: 'emptyDir', label: '临时目录', icon: Disc, color: 'text-slate-400', desc: 'EmptyDir' },
|
||||
{ key: 'hostPath', label: 'HostPath', icon: HardDrive, color: 'text-amber-400', desc: '主机路径' },
|
||||
{ key: 'nfs', label: 'NFS', icon: Server, color: 'text-purple-400', desc: '网络存储' },
|
||||
{ key: 'configMap', label: '配置字典', icon: File, color: 'text-blue-400', desc: 'ConfigMap' },
|
||||
{ key: 'secret', label: '密文', icon: Lock, color: 'text-rose-400', desc: 'Secret' },
|
||||
];
|
||||
|
||||
function volumeToForm(v: any): VolumeForm {
|
||||
if (!v || typeof v !== 'object') return { name: '', type: 'emptyDir' };
|
||||
const name = v.name || '';
|
||||
if (v.emptyDir) {
|
||||
return {
|
||||
name, type: 'emptyDir',
|
||||
medium: v.emptyDir.medium || '',
|
||||
sizeLimit: v.emptyDir.sizeLimit || '',
|
||||
};
|
||||
}
|
||||
if (v.hostPath) {
|
||||
return {
|
||||
name, type: 'hostPath',
|
||||
path: v.hostPath.path || '',
|
||||
pathType: v.hostPath.type || 'Directory',
|
||||
};
|
||||
}
|
||||
if (v.configMap) {
|
||||
return {
|
||||
name, type: 'configMap',
|
||||
configMapName: v.configMap.name || '',
|
||||
items: v.configMap.items ? JSON.stringify(v.configMap.items) : '',
|
||||
};
|
||||
}
|
||||
if (v.secret) {
|
||||
return {
|
||||
name, type: 'secret',
|
||||
secretName: v.secret.secretName || '',
|
||||
items: v.secret.items ? JSON.stringify(v.secret.items) : '',
|
||||
};
|
||||
}
|
||||
if (v.persistentVolumeClaim) {
|
||||
return {
|
||||
name, type: 'persistentVolumeClaim',
|
||||
pvcName: v.persistentVolumeClaim.claimName || '',
|
||||
readOnly: !!v.persistentVolumeClaim.readOnly,
|
||||
};
|
||||
}
|
||||
if (v.nfs) {
|
||||
return {
|
||||
name, type: 'nfs',
|
||||
nfsServer: v.nfs.server || '',
|
||||
nfsPath: v.nfs.path || '',
|
||||
readOnly: !!v.nfs.readOnly,
|
||||
};
|
||||
}
|
||||
// 未识别类型 — fallback 为 emptyDir 占位
|
||||
if (v.emptyDir) return { name, type: 'emptyDir', medium: v.emptyDir.medium || '', sizeLimit: v.emptyDir.sizeLimit || '' };
|
||||
if (v.hostPath) return { name, type: 'hostPath', path: v.hostPath.path || '', pathType: v.hostPath.type || 'Directory' };
|
||||
if (v.configMap) return { name, type: 'configMap', configMapName: v.configMap.name || '', cmItems: v.configMap.items ? JSON.stringify(v.configMap.items) : '' };
|
||||
if (v.secret) return { name, type: 'secret', secretName: v.secret.secretName || '', secItems: v.secret.items ? JSON.stringify(v.secret.items) : '' };
|
||||
if (v.persistentVolumeClaim) return { name, type: 'persistentVolumeClaim', pvcName: v.persistentVolumeClaim.claimName || '', pvcReadOnly: !!v.persistentVolumeClaim.readOnly };
|
||||
if (v.nfs) return { name, type: 'nfs', nfsServer: v.nfs.server || '', nfsPath: v.nfs.path || '', nfsReadOnly: !!v.nfs.readOnly };
|
||||
return { name, type: 'emptyDir' };
|
||||
}
|
||||
|
||||
/** 将 form 转回 K8s volume 对象 */
|
||||
function formToVolume(f: VolumeForm): any {
|
||||
const v: any = { name: f.name.trim() };
|
||||
if (!v.name) return null; // 无名 volume 跳过
|
||||
if (!v.name) return null;
|
||||
switch (f.type) {
|
||||
case 'emptyDir': {
|
||||
const ed: any = {};
|
||||
if (f.medium) ed.medium = f.medium;
|
||||
if (f.sizeLimit) ed.sizeLimit = f.sizeLimit;
|
||||
v.emptyDir = ed;
|
||||
break;
|
||||
}
|
||||
case 'hostPath': {
|
||||
v.hostPath = {
|
||||
path: f.path || '',
|
||||
type: f.pathType || 'Directory',
|
||||
};
|
||||
break;
|
||||
}
|
||||
case 'configMap': {
|
||||
v.configMap = { name: f.configMapName || '' };
|
||||
if (f.items) {
|
||||
try { v.configMap.items = JSON.parse(f.items); } catch {}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'secret': {
|
||||
v.secret = { secretName: f.secretName || '' };
|
||||
if (f.items) {
|
||||
try { v.secret.items = JSON.parse(f.items); } catch {}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'persistentVolumeClaim': {
|
||||
v.persistentVolumeClaim = {
|
||||
claimName: f.pvcName || '',
|
||||
...(f.readOnly ? { readOnly: true } : {}),
|
||||
};
|
||||
break;
|
||||
}
|
||||
case 'nfs': {
|
||||
v.nfs = {
|
||||
server: f.nfsServer || '',
|
||||
path: f.nfsPath || '',
|
||||
...(f.readOnly ? { readOnly: true } : {}),
|
||||
};
|
||||
break;
|
||||
}
|
||||
case 'emptyDir': { const ed: any = {}; if (f.medium) ed.medium = f.medium; if (f.sizeLimit) ed.sizeLimit = f.sizeLimit; v.emptyDir = ed; break; }
|
||||
case 'hostPath': v.hostPath = { path: f.path || '', type: f.pathType || 'Directory' }; break;
|
||||
case 'configMap': { v.configMap = { name: f.configMapName || '' }; if (f.cmItems) try { v.configMap.items = JSON.parse(f.cmItems); } catch {} break; }
|
||||
case 'secret': { v.secret = { secretName: f.secretName || '' }; if (f.secItems) try { v.secret.items = JSON.parse(f.secItems); } catch {} break; }
|
||||
case 'persistentVolumeClaim': v.persistentVolumeClaim = { claimName: f.pvcName || '', ...(f.pvcReadOnly ? { readOnly: true } : {}) }; break;
|
||||
case 'nfs': v.nfs = { server: f.nfsServer || '', path: f.nfsPath || '', ...(f.nfsReadOnly ? { readOnly: true } : {}) }; break;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
const TYPE_META: Record<VolumeForm['type'], { label: string; icon: typeof HardDrive; color: string }> = {
|
||||
emptyDir: { label: 'emptyDir', icon: Folder, color: 'text-slate-300' },
|
||||
hostPath: { label: 'hostPath', icon: HardDrive, color: 'text-amber-400' },
|
||||
configMap: { label: 'configMap', icon: Folder, color: 'text-blue-400' },
|
||||
secret: { label: 'secret', icon: Lock, color: 'text-rose-400' },
|
||||
persistentVolumeClaim: { label: 'PVC', icon: Database, color: 'text-emerald-400' },
|
||||
nfs: { label: 'NFS', icon: HardDrive, color: 'text-purple-400' },
|
||||
};
|
||||
|
||||
export function DeploymentEditStorage({ clusterCode, namespace, deploymentName, manifest, onSaved, onCancel }: Props) {
|
||||
const { toast } = useToast();
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [loading, setLoading] = useState(!manifest);
|
||||
const [volumes, setVolumes] = useState<VolumeForm[]>([]);
|
||||
const [rawManifest, setRawManifest] = useState<any>(manifest || {});
|
||||
// 容器已声明的 volumeMounts(只读展示,便于用户对齐 volume name)
|
||||
const [mountSummary, setMountSummary] = useState<Array<{ container: string; mounts: string[] }>>([]);
|
||||
const [volumes, setVolumes] = useState<VolumeForm[]>([]);
|
||||
const [mounts, setMounts] = useState<MountForm[]>([]);
|
||||
const [containers, setContainers] = useState<string[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
const m = manifest;
|
||||
if (!m) { setLoading(false); return; }
|
||||
setRawManifest(m);
|
||||
const podSpec = m?.spec?.template?.spec || {};
|
||||
|
||||
// 数据卷
|
||||
const vols: any[] = Array.isArray(podSpec.volumes) ? podSpec.volumes : [];
|
||||
setVolumes(vols.map(volumeToForm));
|
||||
|
||||
// 汇总容器 volumeMounts
|
||||
// 容器列表
|
||||
const allContainers = [
|
||||
...(podSpec.containers || []),
|
||||
...(podSpec.initContainers || []),
|
||||
];
|
||||
const summary = allContainers.map((c: any) => ({
|
||||
container: c.name || '(unnamed)',
|
||||
mounts: (Array.isArray(c.volumeMounts) ? c.volumeMounts : [])
|
||||
.map((vm: any) => `${vm.name}:${vm.mountPath}${vm.readOnly ? '(ro)' : ''}`),
|
||||
})).filter((s: any) => s.mounts.length > 0);
|
||||
setMountSummary(summary);
|
||||
const containerNames = allContainers.map((c: any) => c.name || '(unnamed)');
|
||||
setContainers(containerNames);
|
||||
|
||||
// 挂载点
|
||||
const allMounts: MountForm[] = [];
|
||||
for (const c of allContainers) {
|
||||
const cName = c.name || '(unnamed)';
|
||||
const vms: any[] = Array.isArray(c.volumeMounts) ? c.volumeMounts : [];
|
||||
for (const vm of vms) {
|
||||
allMounts.push({
|
||||
containerName: cName,
|
||||
volumeName: vm.name || '',
|
||||
mountPath: vm.mountPath || '',
|
||||
subPath: vm.subPath || '',
|
||||
readOnly: !!vm.readOnly,
|
||||
});
|
||||
}
|
||||
}
|
||||
setMounts(allMounts);
|
||||
setLoading(false);
|
||||
}, [manifest]);
|
||||
|
||||
// Volume operations
|
||||
const addVolume = () => setVolumes(prev => [...prev, { name: '', type: 'emptyDir' }]);
|
||||
const removeVolume = (i: number) => setVolumes(prev => prev.filter((_, idx) => idx !== i));
|
||||
const removeVolume = (i: number) => {
|
||||
const name = volumes[i]?.name;
|
||||
setVolumes(prev => prev.filter((_, idx) => idx !== i));
|
||||
if (name) setMounts(prev => prev.filter(m => m.volumeName !== name));
|
||||
};
|
||||
const updateVolume = (i: number, patch: Partial<VolumeForm>) =>
|
||||
setVolumes(prev => prev.map((v, idx) => (idx === i ? { ...v, ...patch } : v)));
|
||||
|
||||
// Mount operations
|
||||
const addMount = () => setMounts(prev => [...prev, { containerName: containers[0] || '', volumeName: '', mountPath: '', subPath: '', readOnly: false }]);
|
||||
const removeMount = (i: number) => setMounts(prev => prev.filter((_, idx) => idx !== i));
|
||||
const updateMount = (i: number, patch: Partial<MountForm>) =>
|
||||
setMounts(prev => prev.map((m, idx) => (idx === i ? { ...m, ...patch } : m)));
|
||||
|
||||
const save = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
@@ -196,17 +154,35 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
|
||||
base.spec = base.spec || {};
|
||||
base.spec.template = base.spec.template || {};
|
||||
base.spec.template.spec = base.spec.template.spec || {};
|
||||
const podSpec = base.spec.template.spec;
|
||||
|
||||
// Save volumes
|
||||
const k8sVols = volumes.map(formToVolume).filter(Boolean);
|
||||
if (k8sVols.length > 0) {
|
||||
base.spec.template.spec.volumes = k8sVols;
|
||||
} else {
|
||||
delete base.spec.template.spec.volumes;
|
||||
if (k8sVols.length > 0) podSpec.volumes = k8sVols;
|
||||
else delete podSpec.volumes;
|
||||
|
||||
// Save volumeMounts to each container
|
||||
const allContainers = [...(podSpec.containers || []), ...(podSpec.initContainers || [])];
|
||||
for (const c of allContainers) {
|
||||
const cName = c.name || '(unnamed)';
|
||||
const cMounts = mounts
|
||||
.filter(m => m.containerName === cName && m.volumeName && m.mountPath)
|
||||
.map(m => {
|
||||
const vm: any = { name: m.volumeName, mountPath: m.mountPath, readOnly: m.readOnly };
|
||||
if (m.subPath) vm.subPath = m.subPath;
|
||||
return vm;
|
||||
});
|
||||
if (cMounts.length > 0) c.volumeMounts = cMounts;
|
||||
else delete c.volumeMounts;
|
||||
}
|
||||
|
||||
// Rebuild containers arrays
|
||||
podSpec.containers = allContainers.filter((c: any) => !(podSpec.initContainers || []).includes(c));
|
||||
podSpec.initContainers = (podSpec.initContainers || []);
|
||||
|
||||
const json = JSON.stringify(base, null, 2);
|
||||
await kubernetesApi.updateResourceYaml(clusterCode, namespace, 'deployments', deploymentName, json);
|
||||
toast({ title: '存储配置已保存', description: `${deploymentName} volumes 更新已提交` });
|
||||
toast({ title: '存储配置已保存', description: `${deploymentName} 更新已提交` });
|
||||
onSaved();
|
||||
} catch (e: any) {
|
||||
toast({ title: '保存失败', description: e?.message || String(e), variant: 'destructive' });
|
||||
@@ -234,159 +210,138 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
|
||||
);
|
||||
}
|
||||
|
||||
const volumeNames = volumes.map(v => v.name).filter(Boolean);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* 数据卷列表 */}
|
||||
{/* ══════════ 定义数据卷 ══════════ */}
|
||||
<Card className="bg-slate-900 border-slate-800">
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-sm text-slate-200 flex items-center gap-2">
|
||||
<Database className="h-4 w-4 text-emerald-400" />
|
||||
数据卷 (Volumes)
|
||||
<Database className="h-4 w-4 text-emerald-400" />定义数据卷
|
||||
<Badge variant="outline" className="border-slate-700 text-slate-400">{volumes.length}</Badge>
|
||||
</CardTitle>
|
||||
<Button size="sm" variant="outline" className="h-7 border-slate-700 text-slate-300 text-xs" onClick={addVolume}>
|
||||
<Plus className="h-3 w-3 mr-1" />添加数据卷
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-slate-500 mt-1">
|
||||
Pod 级别的卷定义,容器通过 <code className="text-slate-400">volumeMounts</code> 引用这些卷名。
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0 space-y-3">
|
||||
{volumes.length === 0 ? (
|
||||
<div className="text-center py-8 text-slate-500 text-sm border border-dashed border-slate-800 rounded-lg">
|
||||
<Database className="h-8 w-8 mx-auto mb-2 text-slate-700" />
|
||||
未配置数据卷,点击右上角「添加数据卷」
|
||||
未配置数据卷
|
||||
</div>
|
||||
) : volumes.map((vol, i) => {
|
||||
const meta = TYPE_META[vol.type];
|
||||
const Icon = meta.icon;
|
||||
const vtype = VOLUME_TYPES.find(t => t.key === vol.type);
|
||||
const VIcon = vtype?.icon || Folder;
|
||||
return (
|
||||
<div key={i} className="bg-slate-950/50 border border-slate-800 rounded-lg p-3 space-y-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<Icon className={`h-4 w-4 ${meta.color}`} />
|
||||
<Input
|
||||
value={vol.name}
|
||||
onChange={e => updateVolume(i, { name: e.target.value })}
|
||||
<div key={i} className="bg-slate-950/50 border border-slate-800 rounded-lg p-3 space-y-2.5">
|
||||
{/* 卷名 + 类型 */}
|
||||
<div className="flex items-center gap-2">
|
||||
<VIcon className={`h-4 w-4 ${vtype?.color || 'text-slate-400'}`} />
|
||||
<span className="text-[10px] text-slate-500 w-16 shrink-0">数据卷名称</span>
|
||||
<Input value={vol.name} onChange={e => updateVolume(i, { name: e.target.value })}
|
||||
placeholder="volume-name"
|
||||
className="flex-1 h-8 bg-slate-800 border-slate-700 text-slate-200 text-sm font-mono"
|
||||
/>
|
||||
<select
|
||||
value={vol.type}
|
||||
onChange={e => updateVolume(i, { type: e.target.value as VolumeForm['type'] })}
|
||||
className="h-8 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-2"
|
||||
>
|
||||
{Object.entries(TYPE_META).map(([t, m]) => (
|
||||
<option key={t} value={t}>{m.label}</option>
|
||||
))}
|
||||
</select>
|
||||
<Button size="icon" variant="ghost" className="h-7 w-7 text-red-400 hover:text-red-300"
|
||||
onClick={() => removeVolume(i)}>
|
||||
className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
<Select value={vol.type} onValueChange={v => updateVolume(i, { type: v as VolumeForm['type'] })}>
|
||||
<SelectTrigger className="h-7 w-[120px] bg-slate-800 border-slate-700 text-xs text-slate-300">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<VIcon className="h-3 w-3" />{vtype?.label || vol.type}
|
||||
</div>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{VOLUME_TYPES.map(t => {
|
||||
const TI = t.icon;
|
||||
return (
|
||||
<SelectItem key={t.key} value={t.key}>
|
||||
<span className="flex items-center gap-1.5 text-xs">
|
||||
<TI className="h-3 w-3" />{t.label}
|
||||
</span>
|
||||
</SelectItem>
|
||||
);
|
||||
})}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button size="icon" variant="ghost" className="h-7 w-7 text-red-400" onClick={() => removeVolume(i)}>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 类型相关字段 */}
|
||||
{/* 类型指定字段 */}
|
||||
{vol.type === 'persistentVolumeClaim' && (
|
||||
<div className="flex items-center gap-2 pl-[88px]">
|
||||
<Input value={vol.pvcName || ''} onChange={e => updateVolume(i, { pvcName: e.target.value })}
|
||||
placeholder="PVC 名称" className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
<label className="flex items-center gap-1.5 text-xs text-slate-400 cursor-pointer whitespace-nowrap">
|
||||
<input type="checkbox" checked={!!vol.pvcReadOnly}
|
||||
onChange={e => updateVolume(i, { pvcReadOnly: e.target.checked })}
|
||||
className="accent-blue-500" />只读
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{vol.type === 'emptyDir' && (
|
||||
<div className="grid grid-cols-2 gap-3 pl-7">
|
||||
<div>
|
||||
<Label className="text-slate-500 text-xs">medium (留空=磁盘, Memory=tmpfs)</Label>
|
||||
<Input value={vol.medium || ''} onChange={e => updateVolume(i, { medium: e.target.value })}
|
||||
placeholder="" className="h-7 mt-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-slate-500 text-xs">sizeLimit (例: 512Mi)</Label>
|
||||
<Input value={vol.sizeLimit || ''} onChange={e => updateVolume(i, { sizeLimit: e.target.value })}
|
||||
placeholder="512Mi" className="h-7 mt-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2 pl-[88px]">
|
||||
<Input value={vol.sizeLimit || ''} onChange={e => updateVolume(i, { sizeLimit: e.target.value })}
|
||||
placeholder="sizeLimit (如 512Mi, 可为空)"
|
||||
className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{vol.type === 'hostPath' && (
|
||||
<div className="grid grid-cols-2 gap-3 pl-7">
|
||||
<div>
|
||||
<Label className="text-slate-500 text-xs">主机路径 path</Label>
|
||||
<Input value={vol.path || ''} onChange={e => updateVolume(i, { path: e.target.value })}
|
||||
placeholder="/data/app" className="h-7 mt-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-slate-500 text-xs">pathType</Label>
|
||||
<select value={vol.pathType || 'Directory'} onChange={e => updateVolume(i, { pathType: e.target.value })}
|
||||
className="h-7 mt-1 w-full bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-2">
|
||||
<option value="Directory">Directory</option>
|
||||
<option value="File">File</option>
|
||||
<option value="Socket">Socket</option>
|
||||
<option value="CharDevice">CharDevice</option>
|
||||
<option value="BlockDevice">BlockDevice</option>
|
||||
<option value="">(空)</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{vol.type === 'configMap' && (
|
||||
<div className="pl-7">
|
||||
<Label className="text-slate-500 text-xs">ConfigMap 名称</Label>
|
||||
<Input value={vol.configMapName || ''} onChange={e => updateVolume(i, { configMapName: e.target.value })}
|
||||
placeholder="app-config" className="h-7 mt-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
<Label className="text-slate-500 text-xs mt-2 block">items (JSON, 可选)</Label>
|
||||
<Input value={vol.items || ''} onChange={e => updateVolume(i, { items: e.target.value })}
|
||||
placeholder='[{"key":"app.conf","path":"app.conf"}]'
|
||||
className="h-7 mt-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{vol.type === 'secret' && (
|
||||
<div className="pl-7">
|
||||
<Label className="text-slate-500 text-xs">Secret 名称</Label>
|
||||
<Input value={vol.secretName || ''} onChange={e => updateVolume(i, { secretName: e.target.value })}
|
||||
placeholder="app-tls" className="h-7 mt-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
<Label className="text-slate-500 text-xs mt-2 block">items (JSON, 可选)</Label>
|
||||
<Input value={vol.items || ''} onChange={e => updateVolume(i, { items: e.target.value })}
|
||||
placeholder='[{"key":"tls.crt","path":"tls.crt"}]'
|
||||
className="h-7 mt-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{vol.type === 'persistentVolumeClaim' && (
|
||||
<div className="grid grid-cols-2 gap-3 pl-7">
|
||||
<div>
|
||||
<Label className="text-slate-500 text-xs">PVC claimName</Label>
|
||||
<Input value={vol.pvcName || ''} onChange={e => updateVolume(i, { pvcName: e.target.value })}
|
||||
placeholder="data-pvc" className="h-7 mt-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
</div>
|
||||
<div className="flex items-end pb-1">
|
||||
<label className="flex items-center gap-2 text-xs text-slate-400 cursor-pointer">
|
||||
<input type="checkbox" checked={!!vol.readOnly}
|
||||
onChange={e => updateVolume(i, { readOnly: e.target.checked })}
|
||||
className="accent-blue-500" />
|
||||
readOnly
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 pl-[88px]">
|
||||
<Input value={vol.path || ''} onChange={e => updateVolume(i, { path: e.target.value })}
|
||||
placeholder="主机路径 /data/app"
|
||||
className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
<select value={vol.pathType || 'Directory'} onChange={e => updateVolume(i, { pathType: e.target.value })}
|
||||
className="h-7 w-28 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5">
|
||||
<option value="Directory">Directory</option>
|
||||
<option value="File">File</option>
|
||||
<option value="">(默认)</option>
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{vol.type === 'nfs' && (
|
||||
<div className="grid grid-cols-3 gap-3 pl-7">
|
||||
<div>
|
||||
<Label className="text-slate-500 text-xs">server</Label>
|
||||
<Input value={vol.nfsServer || ''} onChange={e => updateVolume(i, { nfsServer: e.target.value })}
|
||||
placeholder="10.10.10.100" className="h-7 mt-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-slate-500 text-xs">path</Label>
|
||||
<Input value={vol.nfsPath || ''} onChange={e => updateVolume(i, { nfsPath: e.target.value })}
|
||||
placeholder="/export/data" className="h-7 mt-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
</div>
|
||||
<div className="flex items-end pb-1">
|
||||
<label className="flex items-center gap-2 text-xs text-slate-400 cursor-pointer">
|
||||
<input type="checkbox" checked={!!vol.readOnly}
|
||||
onChange={e => updateVolume(i, { readOnly: e.target.checked })}
|
||||
className="accent-blue-500" />
|
||||
readOnly
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 pl-[88px]">
|
||||
<Input value={vol.nfsServer || ''} onChange={e => updateVolume(i, { nfsServer: e.target.value })}
|
||||
placeholder="NFS Server IP"
|
||||
className="h-7 w-40 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
<span className="text-slate-600 text-xs">:</span>
|
||||
<Input value={vol.nfsPath || ''} onChange={e => updateVolume(i, { nfsPath: e.target.value })}
|
||||
placeholder="/export/path"
|
||||
className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
<label className="flex items-center gap-1.5 text-xs text-slate-400 cursor-pointer whitespace-nowrap">
|
||||
<input type="checkbox" checked={!!vol.nfsReadOnly}
|
||||
onChange={e => updateVolume(i, { nfsReadOnly: e.target.checked })}
|
||||
className="accent-blue-500" />只读
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{vol.type === 'configMap' && (
|
||||
<div className="flex items-center gap-2 pl-[88px]">
|
||||
<span className="text-[10px] text-slate-500 whitespace-nowrap">ConfigMap</span>
|
||||
<Input value={vol.configMapName || ''} onChange={e => updateVolume(i, { configMapName: e.target.value })}
|
||||
placeholder="ConfigMap 名称"
|
||||
className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
<Input value={vol.cmItems || ''} onChange={e => updateVolume(i, { cmItems: e.target.value })}
|
||||
placeholder="KeyToPath (可为空)"
|
||||
className="h-7 w-40 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{vol.type === 'secret' && (
|
||||
<div className="flex items-center gap-2 pl-[88px]">
|
||||
<span className="text-[10px] text-slate-500 whitespace-nowrap">密文</span>
|
||||
<Input value={vol.secretName || ''} onChange={e => updateVolume(i, { secretName: e.target.value })}
|
||||
placeholder="Secret 名称"
|
||||
className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
<Input value={vol.secItems || ''} onChange={e => updateVolume(i, { secItems: e.target.value })}
|
||||
placeholder="KeyToPath (可为空)"
|
||||
className="h-7 w-40 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -395,41 +350,69 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 容器 volumeMounts 汇总(只读) */}
|
||||
{mountSummary.length > 0 && (
|
||||
<Card className="bg-slate-900 border-slate-800">
|
||||
<CardHeader className="pb-3">
|
||||
{/* ══════════ 挂载到容器 ══════════ */}
|
||||
<Card className="bg-slate-900 border-slate-800">
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-sm text-slate-200 flex items-center gap-2">
|
||||
<Folder className="h-4 w-4 text-blue-400" />
|
||||
容器挂载点 (volumeMounts)
|
||||
<Folder className="h-4 w-4 text-blue-400" />将数据卷挂载到容器
|
||||
<Badge variant="outline" className="border-slate-700 text-slate-400">{mounts.length}</Badge>
|
||||
</CardTitle>
|
||||
<p className="text-xs text-slate-500 mt-1">
|
||||
容器侧已声明的挂载,请在「容器信息」Tab 修改。
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0 space-y-2">
|
||||
{mountSummary.map((s, i) => (
|
||||
<div key={i} className="flex items-start gap-2 text-xs">
|
||||
<Badge variant="outline" className="border-slate-700 text-slate-400 font-mono shrink-0">
|
||||
{s.container}
|
||||
</Badge>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{s.mounts.map((m, j) => (
|
||||
<code key={j} className="bg-slate-800 px-1.5 py-0.5 rounded text-slate-300 text-[11px]">{m}</code>
|
||||
))}
|
||||
</div>
|
||||
<Button size="sm" variant="outline" className="h-7 border-slate-700 text-slate-300 text-xs" onClick={addMount}
|
||||
disabled={volumeNames.length === 0 || containers.length === 0}>
|
||||
<Plus className="h-3 w-3 mr-1" />添加挂载
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0 space-y-2">
|
||||
{mounts.length === 0 ? (
|
||||
<div className="text-center py-8 text-slate-500 text-sm border border-dashed border-slate-800 rounded-lg">
|
||||
<Folder className="h-8 w-8 mx-auto mb-2 text-slate-700" />
|
||||
{volumeNames.length === 0 ? '请先定义数据卷' : '未配置挂载点'}
|
||||
</div>
|
||||
) : mounts.map((m, i) => (
|
||||
<div key={i} className="flex items-center gap-2 bg-slate-950/50 border border-slate-800 rounded-lg p-2.5">
|
||||
{/* 容器选择 */}
|
||||
<span className="text-[10px] text-slate-500 whitespace-nowrap">容器:</span>
|
||||
<select value={m.containerName} onChange={e => updateMount(i, { containerName: e.target.value })}
|
||||
className="h-7 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5 min-w-[120px]">
|
||||
{containers.length === 0 && <option value="">(无容器)</option>}
|
||||
{containers.map(cn => <option key={cn} value={cn}>{cn}</option>)}
|
||||
</select>
|
||||
{/* 数据卷选择 */}
|
||||
<select value={m.volumeName} onChange={e => updateMount(i, { volumeName: e.target.value })}
|
||||
className="h-7 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5 min-w-[100px]">
|
||||
<option value="">选择数据卷</option>
|
||||
{volumeNames.map(vn => <option key={vn} value={vn}>{vn}</option>)}
|
||||
</select>
|
||||
{/* 挂载路径 */}
|
||||
<Input value={m.mountPath} onChange={e => updateMount(i, { mountPath: e.target.value })}
|
||||
placeholder="挂载路径 /app/data"
|
||||
className="h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono" />
|
||||
{/* 只读/读写 */}
|
||||
<div className="flex items-center gap-1 bg-slate-800 rounded-lg p-0.5 border border-slate-700">
|
||||
<button onClick={() => updateMount(i, { readOnly: false })}
|
||||
className={`px-2 py-0.5 rounded text-[10px] font-medium transition-all ${!m.readOnly ? 'bg-blue-500/20 text-blue-300' : 'text-slate-500'}`}>
|
||||
读写
|
||||
</button>
|
||||
<button onClick={() => updateMount(i, { readOnly: true })}
|
||||
className={`px-2 py-0.5 rounded text-[10px] font-medium transition-all ${m.readOnly ? 'bg-amber-500/20 text-amber-300' : 'text-slate-500'}`}>
|
||||
只读
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
<Button size="icon" variant="ghost" className="h-7 w-7 text-red-400" onClick={() => removeMount(i)}>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 操作栏 */}
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button variant="outline" className="border-slate-700 text-slate-400" onClick={onCancel}>取消</Button>
|
||||
<Button className="bg-blue-600 hover:bg-blue-700" disabled={saving} onClick={save}>
|
||||
{saving ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : <Save className="h-4 w-4 mr-1" />}
|
||||
保存
|
||||
{saving ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : <Save className="h-4 w-4 mr-1" />}保存
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -16,6 +16,7 @@ import type { NotificationChannel } from './alert-center-helpers';
|
||||
const CHANNEL_TYPES = [
|
||||
{ value: 'dingtalk', label: '钉钉', hint: '钉钉机器人: webhook URL + secret' },
|
||||
{ value: 'wechat', label: '企业微信', hint: '企业微信: webhook URL' },
|
||||
{ value: 'feishu', label: '飞书', hint: '飞书机器人: {"url":"https://open.feishu.cn/open-apis/bot/v2/hook/..."}' },
|
||||
{ value: 'email', label: '邮件', hint: '邮件: {"to":"ops@ezops.io"}' },
|
||||
{ value: 'sms', label: '短信', hint: '短信: {"phones":"13800138000"}' },
|
||||
{ value: 'webhook', label: 'Webhook', hint: 'Webhook: {"url":"https://..."}' },
|
||||
|
||||
@@ -116,12 +116,18 @@ export function getChannelIcon(type: string) {
|
||||
case 'slack': return <MessageSquare className="w-4 h-4" />;
|
||||
case 'sms': return <Phone className="w-4 h-4" />;
|
||||
case 'webhook': return <Zap className="w-4 h-4" />;
|
||||
case 'feishu': return <Bell className="w-4 h-4 text-blue-500" />;
|
||||
case 'dingtalk': return <Bell className="w-4 h-4 text-sky-500" />;
|
||||
case 'wechat': return <MessageSquare className="w-4 h-4 text-green-500" />;
|
||||
default: return <Bell className="w-4 h-4" />;
|
||||
}
|
||||
}
|
||||
|
||||
/** 渠道类型中文标签 */
|
||||
export function getChannelTypeLabel(type: string) {
|
||||
const map: Record<string, string> = { dingtalk: '钉钉', wechat: '企业微信', email: '邮件', sms: '短信', webhook: 'Webhook' };
|
||||
const map: Record<string, string> = {
|
||||
dingtalk: '钉钉', wechat: '企业微信', feishu: '飞书',
|
||||
email: '邮件', sms: '短信', webhook: 'Webhook',
|
||||
};
|
||||
return map[type] || type;
|
||||
}
|
||||
+178
-188
@@ -1,4 +1,5 @@
|
||||
// 主机监控详情 — 阿里云云监控风格 (Brush缩放 + avg/max/min选择器)
|
||||
// 主机监控详情 — 阿里云云监控风格 + v2.0 新增指标
|
||||
// 进程TOP / Swap / FD / 上下文切换
|
||||
import { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import { agentApi } from '@/services/api';
|
||||
@@ -9,14 +10,14 @@ import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Cpu, HardDrive, Network, Activity, Server, Loader2,
|
||||
Info, Monitor, Disc, Zap, Clock
|
||||
Info, Monitor, Disc, Zap, Clock, List, AlertTriangle,
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip,
|
||||
ResponsiveContainer, Brush, ReferenceLine,
|
||||
ResponsiveContainer, Brush,
|
||||
} from 'recharts';
|
||||
|
||||
// 时间范围 → 聚合窗口 → 目标桶数
|
||||
// 时间范围配置
|
||||
const TIME_RANGES = [
|
||||
{ label: '1小时', hours: 1, window: 60, buckets: 60 },
|
||||
{ label: '6小时', hours: 6, window: 300, buckets: 72 },
|
||||
@@ -30,15 +31,10 @@ const TIME_RANGES = [
|
||||
type AggType = 'avg' | 'max' | 'min';
|
||||
|
||||
interface BucketPoint {
|
||||
time: string;
|
||||
timestamp: number;
|
||||
avg: number;
|
||||
max: number;
|
||||
min: number;
|
||||
count: number;
|
||||
time: string; timestamp: number; avg: number; max: number; min: number; count: number;
|
||||
}
|
||||
|
||||
function bucketWithStats(raw: number[], timestamps: number[], windowSec: number, targetBuckets: number): BucketPoint[] {
|
||||
function bucketWithStats(raw: number[], timestamps: number[], targetBuckets: number): BucketPoint[] {
|
||||
if (!raw || raw.length === 0) return [];
|
||||
const perBucket = Math.max(1, Math.ceil(raw.length / targetBuckets));
|
||||
const result: BucketPoint[] = [];
|
||||
@@ -52,11 +48,7 @@ function bucketWithStats(raw: number[], timestamps: number[], windowSec: number,
|
||||
const ts = tsSlice[Math.floor(tsSlice.length / 2)] || 0;
|
||||
result.push({
|
||||
time: new Date(ts * 1000).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
|
||||
timestamp: ts,
|
||||
avg: Number(avg.toFixed(2)),
|
||||
max: Number(max.toFixed(2)),
|
||||
min: Number(min.toFixed(2)),
|
||||
count: slice.length,
|
||||
timestamp: ts, avg: Number(avg.toFixed(2)), max: Number(max.toFixed(2)), min: Number(min.toFixed(2)), count: slice.length,
|
||||
});
|
||||
}
|
||||
return result.slice(-targetBuckets);
|
||||
@@ -91,7 +83,6 @@ export function HostMonitor() {
|
||||
|
||||
const timeConfig = TIME_RANGES.find(tr => tr.hours === rangeHours) || TIME_RANGES[0];
|
||||
|
||||
// 加载主机列表
|
||||
useEffect(() => {
|
||||
agentApi.getLatest().then((data: any) => {
|
||||
const list = Array.isArray(data) ? data : (data?.data || data?.list || []);
|
||||
@@ -100,16 +91,11 @@ export function HostMonitor() {
|
||||
const m = urlHost ? list.find((h: any) => h.hostname === urlHost) : null;
|
||||
setSelectedHost(m?.hostname || list[0]?.hostname || '');
|
||||
}
|
||||
// 切换主机时同步更新 latest / serverInfo
|
||||
const cur = list.find((h: any) => h.hostname === (selectedHost || urlHost));
|
||||
if (cur) {
|
||||
setLatest(cur);
|
||||
setServerInfo(cur);
|
||||
}
|
||||
if (cur) { setLatest(cur); setServerInfo(cur); }
|
||||
}).catch(() => {}).finally(() => setLoading(false));
|
||||
}, [selectedHost]);
|
||||
|
||||
// 加载历史数据
|
||||
useEffect(() => {
|
||||
if (!selectedHost) return;
|
||||
setLoading(true);
|
||||
@@ -126,25 +112,18 @@ export function HostMonitor() {
|
||||
.finally(() => setLoading(false));
|
||||
}, [selectedHost, rangeHours]);
|
||||
|
||||
// 从原始历史数据提取指标 + 分桶聚合
|
||||
// 历史指标提取
|
||||
const metrics = useMemo(() => {
|
||||
const rawCpu: number[] = [];
|
||||
const rawMem: number[] = [];
|
||||
const rawLoad1: number[] = [];
|
||||
const rawDisk: number[] = [];
|
||||
const rawTcp: number[] = [];
|
||||
const rawRx: number[] = [];
|
||||
const rawTx: number[] = [];
|
||||
const rawIoR: number[] = [];
|
||||
const rawIoW: number[] = [];
|
||||
const rawIoRops: number[] = [];
|
||||
const rawIoWops: number[] = [];
|
||||
const rawCpu: number[] = []; const rawMem: number[] = []; const rawLoad1: number[] = [];
|
||||
const rawDisk: number[] = []; const rawTcp: number[] = []; const rawTw: number[] = [];
|
||||
const rawRx: number[] = []; const rawTx: number[] = [];
|
||||
const rawIoR: number[] = []; const rawIoW: number[] = [];
|
||||
const rawSwap: number[] = []; const rawFD: number[] = [];
|
||||
const timestamps: number[] = [];
|
||||
|
||||
for (const r of history) {
|
||||
const ts = r.report_time ? new Date(r.report_time).getTime() / 1000 : (r.created_at ? new Date(r.created_at).getTime() / 1000 : 0);
|
||||
timestamps.push(ts);
|
||||
|
||||
rawCpu.push(r.cpu_usage || 0);
|
||||
rawMem.push(r.mem_usage || 0);
|
||||
rawLoad1.push(r.load1 || 0);
|
||||
@@ -152,34 +131,45 @@ export function HostMonitor() {
|
||||
|
||||
const net = parseJSON(r.net_info);
|
||||
rawTcp.push(net.tcp_established || 0);
|
||||
rawTw.push(net.tcp_time_wait || 0);
|
||||
rawRx.push(net.net_rx_bps || 0);
|
||||
rawTx.push(net.net_tx_bps || 0);
|
||||
|
||||
const dio = parseJSON(r.disk_io_info);
|
||||
rawIoR.push(dio.read_bps || 0);
|
||||
rawIoW.push(dio.write_bps || 0);
|
||||
rawIoRops.push(dio.read_iops || 0);
|
||||
rawIoWops.push(dio.write_iops || 0);
|
||||
|
||||
const swap = parseJSON(r.swap_info);
|
||||
rawSwap.push(swap?.usage_percent || 0);
|
||||
|
||||
const fd = parseJSON(r.fd_info);
|
||||
rawFD.push(fd?.usage_pct || 0);
|
||||
}
|
||||
|
||||
return {
|
||||
cpu: bucketWithStats(rawCpu, timestamps, timeConfig.window, timeConfig.buckets),
|
||||
mem: bucketWithStats(rawMem, timestamps, timeConfig.window, timeConfig.buckets),
|
||||
load1: bucketWithStats(rawLoad1, timestamps, timeConfig.window, timeConfig.buckets),
|
||||
disk: bucketWithStats(rawDisk, timestamps, timeConfig.window, timeConfig.buckets),
|
||||
tcpEst: bucketWithStats(rawTcp, timestamps, timeConfig.window, timeConfig.buckets),
|
||||
rx: bucketWithStats(rawRx.map(v => v / 1024), timestamps, timeConfig.window, timeConfig.buckets),
|
||||
tx: bucketWithStats(rawTx.map(v => v / 1024), timestamps, timeConfig.window, timeConfig.buckets),
|
||||
ioRead: bucketWithStats(rawIoR.map(v => v / 1024), timestamps, timeConfig.window, timeConfig.buckets),
|
||||
ioWrite: bucketWithStats(rawIoW.map(v => v / 1024), timestamps, timeConfig.window, timeConfig.buckets),
|
||||
ioReadOps: bucketWithStats(rawIoRops, timestamps, timeConfig.window, timeConfig.buckets),
|
||||
ioWriteOps: bucketWithStats(rawIoWops, timestamps, timeConfig.window, timeConfig.buckets),
|
||||
cpu: bucketWithStats(rawCpu, timestamps, timeConfig.buckets),
|
||||
mem: bucketWithStats(rawMem, timestamps, timeConfig.buckets),
|
||||
load1: bucketWithStats(rawLoad1, timestamps, timeConfig.buckets),
|
||||
disk: bucketWithStats(rawDisk, timestamps, timeConfig.buckets),
|
||||
tcpEst: bucketWithStats(rawTcp, timestamps, timeConfig.buckets),
|
||||
tcpTW: bucketWithStats(rawTw, timestamps, timeConfig.buckets),
|
||||
rx: bucketWithStats(rawRx.map(v => v / 1024), timestamps, timeConfig.buckets),
|
||||
tx: bucketWithStats(rawTx.map(v => v / 1024), timestamps, timeConfig.buckets),
|
||||
ioRead: bucketWithStats(rawIoR.map(v => v / 1024), timestamps, timeConfig.buckets),
|
||||
ioWrite: bucketWithStats(rawIoW.map(v => v / 1024), timestamps, timeConfig.buckets),
|
||||
swap: bucketWithStats(rawSwap, timestamps, timeConfig.buckets),
|
||||
fd: bucketWithStats(rawFD, timestamps, timeConfig.buckets),
|
||||
};
|
||||
}, [history, timeConfig]);
|
||||
|
||||
const netInfo = parseJSON(latest?.net_info);
|
||||
const portInfo: any[] = Array.isArray(latest?.port_info) ? latest.port_info : (Array.isArray(parseJSON(latest?.port_info)) ? parseJSON(latest?.port_info) : []);
|
||||
const diskIOInfo = parseJSON(latest?.disk_io_info);
|
||||
const swapInfo = parseJSON(latest?.swap_info);
|
||||
const processTop: any[] = Array.isArray(parseJSON(latest?.process_top_info)) ? parseJSON(latest?.process_top_info) : [];
|
||||
const fdInfo = parseJSON(latest?.fd_info);
|
||||
const csInfo = parseJSON(latest?.cs_info);
|
||||
const heartbeatInfo = parseJSON(latest?.heartbeat_info);
|
||||
|
||||
const currentVal = (key: string, fallback = '--') => {
|
||||
if (!latest) return fallback;
|
||||
@@ -188,12 +178,13 @@ export function HostMonitor() {
|
||||
if (key === 'disk') return latest.disk_usage != null ? `${latest.disk_usage.toFixed(1)}%` : fallback;
|
||||
if (key === 'load1') return latest.load1 != null ? String(latest.load1) : fallback;
|
||||
if (key === 'tcp') return netInfo.tcp_established != null ? String(netInfo.tcp_established) : fallback;
|
||||
if (key === 'tw') return netInfo.tcp_time_wait != null ? String(netInfo.tcp_time_wait) : fallback;
|
||||
if (key === 'rx') return netInfo.net_rx_bps != null ? `${(netInfo.net_rx_bps / 1024).toFixed(1)} KB/s` : fallback;
|
||||
if (key === 'tx') return netInfo.net_tx_bps != null ? `${(netInfo.net_tx_bps / 1024).toFixed(1)} KB/s` : fallback;
|
||||
if (key === 'ioR') return diskIOInfo.read_bps != null ? `${formatBPS(diskIOInfo.read_bps)}` : fallback;
|
||||
if (key === 'ioW') return diskIOInfo.write_bps != null ? `${formatBPS(diskIOInfo.write_bps)}` : fallback;
|
||||
if (key === 'ioR_ops') return diskIOInfo.read_iops != null ? `${diskIOInfo.read_iops.toFixed(1)} count/s` : fallback;
|
||||
if (key === 'ioW_ops') return diskIOInfo.write_iops != null ? `${diskIOInfo.write_iops.toFixed(1)} count/s` : fallback;
|
||||
if (key === 'swap') return swapInfo?.usage_percent != null ? `${swapInfo.usage_percent.toFixed(1)}%` : fallback;
|
||||
if (key === 'fd') return fdInfo?.usage_pct != null ? `${fdInfo.usage_pct.toFixed(1)}%` : fallback;
|
||||
return fallback;
|
||||
};
|
||||
|
||||
@@ -223,9 +214,7 @@ export function HostMonitor() {
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{/* 聚合类型选择 */}
|
||||
<Select value={aggType} onValueChange={(v) => setAggType(v as AggType)}>
|
||||
<SelectTrigger className="w-24 h-7 text-xs bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
|
||||
<SelectValue />
|
||||
@@ -236,32 +225,23 @@ export function HostMonitor() {
|
||||
<SelectItem value="min">最小值</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 时间范围 */}
|
||||
<div className="flex items-center gap-1">
|
||||
{TIME_RANGES.map(tr => (
|
||||
<Button
|
||||
key={tr.hours}
|
||||
variant={rangeHours === tr.hours ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
className="h-7 text-xs px-2.5"
|
||||
onClick={() => setRangeHours(tr.hours)}
|
||||
>
|
||||
{tr.label}
|
||||
</Button>
|
||||
<Button key={tr.hours} variant={rangeHours === tr.hours ? 'default' : 'outline'} size="sm"
|
||||
className="h-7 text-xs px-2.5" onClick={() => setRangeHours(tr.hours)}>{tr.label}</Button>
|
||||
))}
|
||||
</div>
|
||||
<Badge variant="outline" className="text-[10px] h-6">聚合: {aggType}</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 分类 Tab */}
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab}>
|
||||
<TabsList className="h-8 bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] gap-0">
|
||||
<TabsList className="h-8 bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] gap-0 overflow-x-auto">
|
||||
{[
|
||||
{ id: 'basic', label: '基础监控', icon: <Monitor className="w-3 h-3" /> },
|
||||
{ id: 'disk', label: '磁盘监控', icon: <HardDrive className="w-3 h-3" /> },
|
||||
{ id: 'network', label: '网络监控', icon: <Network className="w-3 h-3" /> },
|
||||
{ id: 'process', label: '进程监控', icon: <List className="w-3 h-3" /> },
|
||||
{ id: 'system', label: '系统信息', icon: <Info className="w-3 h-3" /> },
|
||||
].map(tab => (
|
||||
<TabsTrigger key={tab.id} value={tab.id} className="text-[11px] h-7 gap-1 data-[state=active]:bg-[var(--dg-bg-primary)]">
|
||||
@@ -270,64 +250,135 @@ export function HostMonitor() {
|
||||
))}
|
||||
</TabsList>
|
||||
|
||||
{/* 基础监控 */}
|
||||
{/* 基础监控 — 增加 Swap 卡片 */}
|
||||
<TabsContent value="basic" className="mt-3 grid grid-cols-1 md:grid-cols-3 gap-3">
|
||||
<MetricChartCard
|
||||
title="CPU使用率(%)" value={currentVal('cpu')} icon={<Cpu className="h-4 w-4 text-blue-400" />}
|
||||
data={metrics.cpu} color="#3b82f6" unit="%" domain={[0, 100]} aggType={aggType}
|
||||
/>
|
||||
<MetricChartCard
|
||||
title="内存使用率(%)" value={currentVal('mem')} icon={<Server className="h-4 w-4 text-emerald-400" />}
|
||||
data={metrics.mem} color="#10b981" unit="%" domain={[0, 100]} aggType={aggType}
|
||||
/>
|
||||
<MetricChartCard
|
||||
title="系统平均负载(count)" value={currentVal('load1')} icon={<Activity className="h-4 w-4 text-purple-400" />}
|
||||
data={metrics.load1} color="#8b5cf6" unit="" domain={[0, 'auto']} aggType={aggType}
|
||||
/>
|
||||
<MetricChartCard title="CPU 使用率(%)" value={currentVal('cpu')} icon={<Cpu className="h-4 w-4 text-blue-400" />}
|
||||
data={metrics.cpu} color="#3b82f6" unit="%" domain={[0, 100]} aggType={aggType} />
|
||||
<MetricChartCard title="内存使用率(%)" value={currentVal('mem')} icon={<Server className="h-4 w-4 text-emerald-400" />}
|
||||
data={metrics.mem} color="#10b981" unit="%" domain={[0, 100]} aggType={aggType} />
|
||||
<MetricChartCard title="系统负载(1m)" value={currentVal('load1')} icon={<Activity className="h-4 w-4 text-purple-400" />}
|
||||
data={metrics.load1} color="#8b5cf6" unit="" domain={[0, 'auto']} aggType={aggType} />
|
||||
</TabsContent>
|
||||
|
||||
{/* 磁盘监控 */}
|
||||
<TabsContent value="disk" className="mt-3 space-y-3">
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-3">
|
||||
<MetricChartCard
|
||||
title="磁盘使用率(%)" value={currentVal('disk')} icon={<HardDrive className="h-4 w-4 text-orange-400" />}
|
||||
data={metrics.disk} color="#f97316" unit="%" domain={[0, 100]} aggType={aggType}
|
||||
/>
|
||||
<MetricChartCard
|
||||
title="所有磁盘读取BPS(KB/s)" value={currentVal('ioR')} icon={<Disc className="h-4 w-4 text-blue-400" />}
|
||||
data={metrics.ioRead} color="#3b82f6" unit="KB/s" domain={[0, 'auto']} aggType={aggType}
|
||||
/>
|
||||
<MetricChartCard
|
||||
title="所有磁盘写入BPS(KB/s)" value={currentVal('ioW')} icon={<Disc className="h-4 w-4 text-emerald-400" />}
|
||||
data={metrics.ioWrite} color="#10b981" unit="KB/s" domain={[0, 'auto']} aggType={aggType}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
<MetricChartCard
|
||||
title="所有磁盘每秒读取次数(count/s)" value={currentVal('ioR_ops')} icon={<Zap className="h-4 w-4 text-blue-400" />}
|
||||
data={metrics.ioReadOps} color="#6366f1" unit="count/s" domain={[0, 'auto']} aggType={aggType}
|
||||
/>
|
||||
<MetricChartCard
|
||||
title="所有磁盘每秒写入次数(count/s)" value={currentVal('ioW_ops')} icon={<Zap className="h-4 w-4 text-emerald-400" />}
|
||||
data={metrics.ioWriteOps} color="#22d3ee" unit="count/s" domain={[0, 'auto']} aggType={aggType}
|
||||
/>
|
||||
<MetricChartCard title="磁盘使用率(%)" value={currentVal('disk')} icon={<HardDrive className="h-4 w-4 text-orange-400" />}
|
||||
data={metrics.disk} color="#f97316" unit="%" domain={[0, 100]} aggType={aggType} />
|
||||
<MetricChartCard title="磁盘读取(KB/s)" value={currentVal('ioR')} icon={<Disc className="h-4 w-4 text-blue-400" />}
|
||||
data={metrics.ioRead} color="#3b82f6" unit="KB/s" domain={[0, 'auto']} aggType={aggType} />
|
||||
<MetricChartCard title="磁盘写入(KB/s)" value={currentVal('ioW')} icon={<Disc className="h-4 w-4 text-emerald-400" />}
|
||||
data={metrics.ioWrite} color="#10b981" unit="KB/s" domain={[0, 'auto']} aggType={aggType} />
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
{/* 网络监控 */}
|
||||
{/* 网络监控 — 增加 TIME_WAIT + FD 图表 */}
|
||||
<TabsContent value="network" className="mt-3 grid grid-cols-1 md:grid-cols-3 gap-3">
|
||||
<MetricChartCard
|
||||
title="TCP连接数(个)" value={currentVal('tcp')} icon={<Network className="h-4 w-4 text-purple-400" />}
|
||||
data={metrics.tcpEst} color="#8b5cf6" unit="个" domain={[0, 'auto']} aggType={aggType}
|
||||
/>
|
||||
<MetricChartCard
|
||||
title="网络接收速率(KB/s)" value={currentVal('rx')} icon={<Network className="h-4 w-4 text-blue-400" />}
|
||||
data={metrics.rx} color="#3b82f6" unit="KB/s" domain={[0, 'auto']} aggType={aggType}
|
||||
/>
|
||||
<MetricChartCard
|
||||
title="网络发送速率(KB/s)" value={currentVal('tx')} icon={<Network className="h-4 w-4 text-emerald-400" />}
|
||||
data={metrics.tx} color="#10b981" unit="KB/s" domain={[0, 'auto']} aggType={aggType}
|
||||
/>
|
||||
<MetricChartCard title="TCP 连接数(EST)" value={currentVal('tcp')} icon={<Network className="h-4 w-4 text-purple-400" />}
|
||||
data={metrics.tcpEst} color="#8b5cf6" unit="个" domain={[0, 'auto']} aggType={aggType} />
|
||||
<MetricChartCard title="TCP TIME_WAIT" value={currentVal('tw')} icon={<Clock className="h-4 w-4 text-amber-400" />}
|
||||
data={metrics.tcpTW} color="#f59e0b" unit="个" domain={[0, 'auto']} aggType={aggType} />
|
||||
<MetricChartCard title="网络接收(KB/s)" value={currentVal('rx')} icon={<Network className="h-4 w-4 text-blue-400" />}
|
||||
data={metrics.rx} color="#3b82f6" unit="KB/s" domain={[0, 'auto']} aggType={aggType} />
|
||||
</TabsContent>
|
||||
|
||||
{/* ═══ 进程监控 — v2.0 新增 ═══ */}
|
||||
<TabsContent value="process" className="mt-3 space-y-3">
|
||||
{/* 进程 TOP 表格 */}
|
||||
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
|
||||
<CardContent className="p-4">
|
||||
<h3 className="text-xs font-medium text-[var(--dg-text-primary)] mb-3 flex items-center gap-2">
|
||||
<List className="h-4 w-4 text-cyan-400" />进程 TOP {processTop.length} (按内存排序)
|
||||
</h3>
|
||||
{processTop.length === 0 ? (
|
||||
<div className="text-center py-6 text-xs text-[var(--dg-text-muted)] border border-dashed border-[var(--dg-border)] rounded-lg">
|
||||
Agent v2.0+ 支持,当前无数据
|
||||
</div>
|
||||
) : (
|
||||
<table className="w-full text-xs">
|
||||
<thead>
|
||||
<tr className="text-[var(--dg-text-muted)] border-b border-[var(--dg-border)]">
|
||||
<th className="py-1.5 text-left font-medium">PID</th>
|
||||
<th className="py-1.5 text-left font-medium">进程名</th>
|
||||
<th className="py-1.5 text-right font-medium">内存 (MB)</th>
|
||||
<th className="py-1.5 text-right font-medium">FD 数</th>
|
||||
<th className="py-1.5 text-right font-medium">线程数</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{processTop.map((p: any, i: number) => (
|
||||
<tr key={i} className="border-b border-[var(--dg-border)]/30 hover:bg-slate-800/30">
|
||||
<td className="py-1.5 font-mono text-[var(--dg-text-muted)]">{p.pid}</td>
|
||||
<td className="py-1.5 font-mono text-[var(--dg-text-primary)]">{p.name}</td>
|
||||
<td className="py-1.5 text-right font-mono text-cyan-400">{(p.memory_mb ?? 0).toFixed(0)}</td>
|
||||
<td className="py-1.5 text-right font-mono text-[var(--dg-text-muted)]">{p.fd_count ?? 0}</td>
|
||||
<td className="py-1.5 text-right font-mono text-[var(--dg-text-muted)]">{p.threads ?? 0}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Swap + FD + CS 快速卡片 */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-3">
|
||||
<MetricChartCard title="Swap 使用率(%)" value={currentVal('swap')}
|
||||
icon={<AlertTriangle className="h-4 w-4 text-rose-400" />}
|
||||
data={metrics.swap} color="#f43f5e" unit="%" domain={[0, 100]} aggType={aggType}
|
||||
/>
|
||||
<MetricChartCard title="FD 句柄使用率(%)" value={currentVal('fd')}
|
||||
icon={<Activity className="h-4 w-4 text-cyan-400" />}
|
||||
data={metrics.fd} color="#22d3ee" unit="%" domain={[0, 100]} aggType={aggType}
|
||||
/>
|
||||
{/* CS 当前值卡片 */}
|
||||
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
|
||||
<CardContent className="p-3">
|
||||
<div className="flex items-center gap-1.5 mb-2">
|
||||
<Zap className="h-4 w-4 text-indigo-400" /><span className="text-xs text-[var(--dg-text-primary)]">上下文切换</span>
|
||||
</div>
|
||||
<div className="text-xl font-bold text-[var(--dg-text-primary)] tabular-nums">
|
||||
{csInfo?.ctx_per_sec != null ? `${(csInfo.ctx_per_sec / 1000).toFixed(1)}K/s` : '--'}
|
||||
</div>
|
||||
<div className="text-[10px] text-[var(--dg-text-muted)] mt-0.5">
|
||||
中断: {csInfo?.irq_per_sec != null ? `${(csInfo.irq_per_sec / 1000).toFixed(1)}K/s` : '--'}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* FD / Swap 详情 */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
{fdInfo && fdInfo.max > 0 && (
|
||||
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
|
||||
<CardContent className="p-3">
|
||||
<span className="text-[10px] text-[var(--dg-text-muted)]">文件句柄</span>
|
||||
<div className="flex items-baseline gap-1">
|
||||
<span className="text-lg font-bold text-[var(--dg-text-primary)]">{fdInfo.allocated}</span>
|
||||
<span className="text-xs text-[var(--dg-text-muted)]">/ {fdInfo.max}</span>
|
||||
</div>
|
||||
<div className="mt-1 h-1.5 bg-slate-700 rounded-full overflow-hidden">
|
||||
<div className="h-full rounded-full bg-cyan-500" style={{ width: `${Math.min(fdInfo.usage_pct || 0, 100)}%` }} />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
{swapInfo && swapInfo.total_gb > 0 && (
|
||||
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
|
||||
<CardContent className="p-3">
|
||||
<span className="text-[10px] text-[var(--dg-text-muted)]">Swap</span>
|
||||
<div className="flex items-baseline gap-1">
|
||||
<span className="text-lg font-bold text-[var(--dg-text-primary)]">{(swapInfo.used_gb ?? 0).toFixed(1)}</span>
|
||||
<span className="text-xs text-[var(--dg-text-muted)]">/ {(swapInfo.total_gb ?? 0).toFixed(0)} GB</span>
|
||||
</div>
|
||||
<div className="mt-1 h-1.5 bg-slate-700 rounded-full overflow-hidden">
|
||||
<div className={`h-full rounded-full ${(swapInfo.usage_percent || 0) > 50 ? 'bg-rose-500' : 'bg-amber-500'}`}
|
||||
style={{ width: `${Math.min(swapInfo.usage_percent || 0, 100)}%` }} />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
{/* 系统信息 */}
|
||||
@@ -344,9 +395,10 @@ export function HostMonitor() {
|
||||
['总内存', serverInfo?.mem_total ? `${serverInfo.mem_total.toFixed(0)} GB` : '—'],
|
||||
['已用内存', serverInfo?.mem_used ? `${serverInfo.mem_used.toFixed(1)} GB` : '—'],
|
||||
['运行时长', serverInfo?.uptime ? `${Math.floor(serverInfo.uptime / 86400)}天 ${Math.floor((serverInfo.uptime % 86400) / 3600)}时` : '—'],
|
||||
['Agent 版本', serverInfo?.agent_version || '—'],
|
||||
['磁盘总容量', serverInfo?.disk_total ? `${serverInfo.disk_total} GB` : '—'],
|
||||
['Agent 版本', heartbeatInfo?.version || serverInfo?.agent_version || '—'],
|
||||
['Agent 序列号', heartbeatInfo?.report_seq != null ? String(heartbeatInfo.report_seq) : '—'],
|
||||
['监听端口数', portInfo.length > 0 ? `${portInfo.length}` : '—'],
|
||||
['Agent RSS', heartbeatInfo?.self_rss_mb ? `${heartbeatInfo.self_rss_mb.toFixed(1)} MB` : '—'],
|
||||
].map(([label, val]) => (
|
||||
<div key={label as string}>
|
||||
<span className="text-[var(--dg-text-muted)]">{label}:</span>
|
||||
@@ -374,7 +426,7 @@ export function HostMonitor() {
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 磁盘分区 */}
|
||||
{/* 磁盘分区 + 网络接口 (保持原样) */}
|
||||
{latest?.disk_info && (() => {
|
||||
const disk = parseJSON(latest.disk_info);
|
||||
const parts = Array.isArray(disk) ? disk : (disk.partitions || []);
|
||||
@@ -382,10 +434,7 @@ export function HostMonitor() {
|
||||
return (
|
||||
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<HardDrive className="h-4 w-4 text-[var(--dg-text-muted)]" />
|
||||
<h3 className="text-xs font-medium text-[var(--dg-text-primary)]">磁盘分区</h3>
|
||||
</div>
|
||||
<h3 className="text-xs font-medium text-[var(--dg-text-primary)] mb-2 flex items-center gap-2"><HardDrive className="h-4 w-4" />磁盘分区</h3>
|
||||
<div className="space-y-1.5">
|
||||
{parts.map((p: any, i: number) => (
|
||||
<div key={i} className="flex items-center gap-2 text-xs">
|
||||
@@ -402,31 +451,13 @@ export function HostMonitor() {
|
||||
</Card>
|
||||
);
|
||||
})()}
|
||||
|
||||
{/* 网络接口 */}
|
||||
{netInfo && (
|
||||
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Network className="h-4 w-4 text-[var(--dg-text-muted)]" />
|
||||
<h3 className="text-xs font-medium text-[var(--dg-text-primary)]">网络接口</h3>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-xs">
|
||||
<div><span className="text-[var(--dg-text-muted)]">网卡:</span><span className="text-[var(--dg-text-primary)] font-mono">{netInfo.nic_name || '—'}</span></div>
|
||||
<div><span className="text-[var(--dg-text-muted)]">接收:</span><span className="text-blue-400 font-mono">{netInfo.net_rx_bps ? `${(netInfo.net_rx_bps/1024).toFixed(1)} KB/s` : '—'}</span></div>
|
||||
<div><span className="text-[var(--dg-text-muted)]">发送:</span><span className="text-emerald-400 font-mono">{netInfo.net_tx_bps ? `${(netInfo.net_tx_bps/1024).toFixed(1)} KB/s` : '—'}</span></div>
|
||||
<div><span className="text-[var(--dg-text-muted)]">EST/TW:</span><span className="text-[var(--dg-text-primary)] font-mono">{netInfo.tcp_established || 0}/{netInfo.tcp_time_wait || 0}</span></div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ═══════ 指标图表卡片 (带 Brush 缩放 + avg/max/min 数据) ═══════
|
||||
// ═══════ 指标图表卡片 ═══════
|
||||
function MetricChartCard({
|
||||
title, value, icon, data, color, unit, domain, aggType,
|
||||
}: {
|
||||
@@ -434,38 +465,20 @@ function MetricChartCard({
|
||||
data: BucketPoint[]; color: string; unit: string;
|
||||
domain: [number, number | 'auto']; aggType: AggType;
|
||||
}) {
|
||||
// 选择当前聚合类型的值
|
||||
const chartData = data.map(d => ({
|
||||
...d,
|
||||
value: d[aggType],
|
||||
}));
|
||||
|
||||
const chartData = data.map(d => ({ ...d, value: d[aggType] }));
|
||||
return (
|
||||
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
|
||||
<CardContent className="p-3">
|
||||
{/* 标题行 */}
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
{icon}
|
||||
<span className="text-xs text-[var(--dg-text-primary)] font-medium truncate">{title}</span>
|
||||
</div>
|
||||
<span className="text-[10px] text-[var(--dg-text-muted)]">
|
||||
{aggType === 'avg' ? '平均值' : aggType === 'max' ? '最大值' : '最小值'}
|
||||
</span>
|
||||
<div className="flex items-center gap-1.5">{icon}<span className="text-xs text-[var(--dg-text-primary)] font-medium truncate">{title}</span></div>
|
||||
</div>
|
||||
|
||||
{/* 当前值 */}
|
||||
<div className="mb-2">
|
||||
<span className="text-xl font-bold text-[var(--dg-text-primary)] tabular-nums">{value}</span>
|
||||
{unit && <span className="text-xs text-[var(--dg-text-muted)] ml-1">{unit}</span>}
|
||||
</div>
|
||||
|
||||
{/* 趋势图 + Brush 缩放 */}
|
||||
<div className="h-48">
|
||||
{chartData.length === 0 ? (
|
||||
<div className="h-full flex items-center justify-center text-xs text-[var(--dg-text-muted)] border border-dashed border-[var(--dg-border)] rounded-md">
|
||||
暂无数据
|
||||
</div>
|
||||
<div className="h-full flex items-center justify-center text-xs text-[var(--dg-text-muted)] border border-dashed border-[var(--dg-border)] rounded-md">暂无数据</div>
|
||||
) : (
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<AreaChart data={chartData} margin={{ top: 2, right: 2, bottom: 0, left: -10 }}>
|
||||
@@ -478,33 +491,12 @@ function MetricChartCard({
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="#1e293b" strokeOpacity={0.5} />
|
||||
<XAxis dataKey="time" hide />
|
||||
<YAxis hide domain={domain[1] === 'auto' ? [0, (max: number) => max * 1.1] : domain as [number, number]} />
|
||||
<Tooltip
|
||||
contentStyle={{
|
||||
backgroundColor: '#0f172a', border: '1px solid #1e293b',
|
||||
borderRadius: '4px', color: '#f8fafc', fontSize: '11px', padding: '4px 8px',
|
||||
}}
|
||||
<Tooltip contentStyle={{ backgroundColor: '#0f172a', border: '1px solid #1e293b', borderRadius: '4px', color: '#f8fafc', fontSize: '11px', padding: '4px 8px' }}
|
||||
formatter={(v: number) => [`${v.toFixed(2)} ${unit}`, title.replace(/\(.+\)/, '')]}
|
||||
labelFormatter={(label) => `时间: ${label}`}
|
||||
/>
|
||||
labelFormatter={(label) => `时间: ${label}`} />
|
||||
<Area type="monotone" dataKey="value" stroke={color} strokeWidth={1.5} fill={`url(#grad-${title})`} />
|
||||
{/* Brush 缩放条 — 可拖动选择时间范围,鼠标滚轮精细调整 */}
|
||||
<Brush
|
||||
dataKey="time"
|
||||
height={24}
|
||||
stroke="#334155"
|
||||
fill="#0f172a"
|
||||
tickFormatter={(t: string) => t}
|
||||
startIndex={Math.max(0, chartData.length - Math.min(20, chartData.length))}
|
||||
/>
|
||||
{/* 参考线:平均值 */}
|
||||
{chartData.length > 0 && (
|
||||
<ReferenceLine
|
||||
y={chartData.reduce((s, d) => s + d.value, 0) / chartData.length}
|
||||
stroke={color}
|
||||
strokeOpacity={0.3}
|
||||
strokeDasharray="4 4"
|
||||
/>
|
||||
)}
|
||||
<Brush dataKey="time" height={24} stroke="#334155" fill="#0f172a"
|
||||
startIndex={Math.max(0, chartData.length - Math.min(20, chartData.length))} />
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
@@ -513,5 +505,3 @@ function MetricChartCard({
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export default HostMonitor;
|
||||
@@ -175,6 +175,9 @@ export const kubernetesApi = {
|
||||
getNodes: async (clusterId: number | string) => {
|
||||
return http.get(`/kubernetes-clusters/${clusterId}/nodes`);
|
||||
},
|
||||
getClusterNodes: async (clusterCode: string) => {
|
||||
return http.get(`/kubernetes/${clusterCode}/nodes`);
|
||||
},
|
||||
getNodeDetail: async (clusterCode: string, nodeName: string) => {
|
||||
return http.get(`/kubernetes/${clusterCode}/nodes/${encodeURIComponent(nodeName)}`);
|
||||
},
|
||||
@@ -971,8 +974,10 @@ export const deployApi = {
|
||||
getTools: () => http.get<ListResponse>('/deploy/tools'),
|
||||
getTool: (id: number | string) => http.get(`/deploy/tools/${id}`),
|
||||
updateTool: (id: number | string, data: any) => http.put(`/deploy/tools/${id}`, data),
|
||||
installTool: (id: number | string) => http.post(`/deploy/tools/${id}/install`),
|
||||
installTool: (id: number | string, version?: string) =>
|
||||
http.post(`/deploy/tools/${id}/install`, version ? { version } : {}),
|
||||
checkTool: (id: number | string) => http.post(`/deploy/tools/${id}/check`),
|
||||
getToolVersions: (id: number | string) => http.get(`/deploy/tools/${id}/versions`),
|
||||
};
|
||||
|
||||
// ==================== Ansible 自动化 API ====================
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
设置飞书Webhook通知渠道 + 创建告警规则 + 测试
|
||||
"""
|
||||
import urllib.request
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
|
||||
BASE = "http://10.10.10.75"
|
||||
FEISHU_WEBHOOK = "https://open.feishu.cn/open-apis/bot/v2/hook/4c9b0763-fb70-448b-8ece-2d2fbcf5e3ee"
|
||||
|
||||
def api(method, path, data=None):
|
||||
url = f"{BASE}{path}"
|
||||
body = json.dumps(data).encode() if data else None
|
||||
req = urllib.request.Request(url, data=body, method=method)
|
||||
req.add_header("Content-Type", "application/json")
|
||||
if jwt_token:
|
||||
req.add_header("Authorization", f"Bearer {jwt_token}")
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=15)
|
||||
return json.loads(resp.read())
|
||||
except urllib.error.HTTPError as e:
|
||||
print(f" HTTP {e.code}: {e.read().decode()[:200]}")
|
||||
return None
|
||||
|
||||
# Step 1: Login
|
||||
print("=" * 60)
|
||||
print("Step 1: 登录获取 JWT Token")
|
||||
print("=" * 60)
|
||||
resp = api("POST", "/api/v1/auth/login", {"username": "admin", "password": "123456"})
|
||||
if not resp or resp.get("code") != 200:
|
||||
print("ERROR: 登录失败")
|
||||
sys.exit(1)
|
||||
jwt_token = resp.get("data", {}).get("token", "")
|
||||
if not jwt_token:
|
||||
# Try different key
|
||||
jwt_token = resp.get("token", "")
|
||||
print(f" Token: {jwt_token[:20]}...")
|
||||
print()
|
||||
|
||||
# Step 2: Create Feishu Webhook Notify Channel
|
||||
print("=" * 60)
|
||||
print("Step 2: 创建飞书 Webhook 通知渠道")
|
||||
print("=" * 60)
|
||||
channel_config = json.dumps({"url": FEISHU_WEBHOOK})
|
||||
resp = api("POST", "/alerts/notify-channels", {
|
||||
"name": "飞书运维告警群",
|
||||
"type": "feishu",
|
||||
"config": channel_config
|
||||
})
|
||||
if resp and resp.get("code") == 200:
|
||||
channel_id = resp["data"]["id"]
|
||||
print(f" 渠道创建成功: ID={channel_id}")
|
||||
else:
|
||||
print(f" 创建结果: {resp}")
|
||||
|
||||
# Also list existing channels
|
||||
resp = api("GET", "/alerts/notify-channels")
|
||||
if resp:
|
||||
channels = resp.get("data", {}).get("list", [])
|
||||
print(f" 现有渠道: {len(channels)} 个")
|
||||
for ch in channels:
|
||||
print(f" [{ch['type']}] {ch['name']} (enabled={ch['enabled']}) id={ch['id']}")
|
||||
if channels:
|
||||
channel_id = channels[0]["id"]
|
||||
print()
|
||||
|
||||
# Step 3: Test the Feishu channel
|
||||
print("=" * 60)
|
||||
print("Step 3: 测试飞书通知渠道")
|
||||
print("=" * 60)
|
||||
if channel_id:
|
||||
resp = api("POST", f"/alerts/notify-channels/{channel_id}/test")
|
||||
if resp:
|
||||
print(f" 测试结果: {resp.get('message', resp)}")
|
||||
print(f" 状态: {resp.get('data', {}).get('status', 'unknown')}")
|
||||
else:
|
||||
print(" 跳过: 没有渠道ID")
|
||||
print()
|
||||
|
||||
# Step 4: Create alert rules
|
||||
print("=" * 60)
|
||||
print("Step 4: 创建告警规则 (一键报警)")
|
||||
print("=" * 60)
|
||||
|
||||
# Use the quick-setup endpoint
|
||||
resp = api("POST", "/alerts/quick-setup", {
|
||||
"rules": [
|
||||
{"name": "CPU使用率", "metric": "cpu", "operator": ">", "threshold": 80},
|
||||
{"name": "内存使用率", "metric": "mem", "operator": ">", "threshold": 80},
|
||||
{"name": "磁盘使用率", "metric": "disk", "operator": ">", "threshold": 90},
|
||||
{"name": "TIME_WAIT连接数", "metric": "tcp_time_wait", "operator": ">", "threshold": 15000},
|
||||
{"name": "CLOSE_WAIT连接数", "metric": "tcp_close_wait", "operator": ">", "threshold": 200},
|
||||
{"name": "进程异常退出", "metric": "service_process", "operator": "==", "threshold": 0},
|
||||
]
|
||||
})
|
||||
if resp:
|
||||
print(f" 结果: {resp.get('message', resp)}")
|
||||
print(f" 详情: {resp.get('data', {})}")
|
||||
|
||||
# List all rules
|
||||
resp = api("GET", "/alerts/rules")
|
||||
if resp:
|
||||
rules = resp.get("data", {}).get("list", [])
|
||||
print(f"\n 现有告警规则: {len(rules)} 条")
|
||||
for r in rules:
|
||||
print(f" [{r.get('type', '-')}] {r.get('name', '-')} (enabled={r.get('enabled', '-')})")
|
||||
|
||||
# Also check agent rules
|
||||
resp = api("GET", "/api/v1/agent/rules")
|
||||
if resp and resp.get("code") == 200:
|
||||
rules = resp.get("data", [])
|
||||
print(f"\n Agent 告警规则: {len(rules) if isinstance(rules, list) else 0} 条")
|
||||
if isinstance(rules, list):
|
||||
for r in rules[:10]:
|
||||
print(f" [{r.get('metric', '-')}] {r.get('name', '-')} {'启用' if r.get('enabled') else '禁用'}")
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("完成!检查 http://10.10.10.75/alert-center 查看告警中心和规则")
|
||||
print("=" * 60)
|
||||
Reference in new issue
Block a user