diff --git a/agent/collector/proctop.go b/agent/collector/proctop.go new file mode 100644 index 0000000..acfa7ef --- /dev/null +++ b/agent/collector/proctop.go @@ -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//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//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//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) +} diff --git a/agent/collector/swap.go b/agent/collector/swap.go new file mode 100644 index 0000000..681849b --- /dev/null +++ b/agent/collector/swap.go @@ -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 +} diff --git a/agent/main.go b/agent/main.go index 3a93cc6..eeb2ba9 100644 --- a/agent/main.go +++ b/agent/main.go @@ -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 +} diff --git a/agent/model/model.go b/agent/model/model.go index e257f1d..ef9bb53 100644 --- a/agent/model/model.go +++ b/agent/model/model.go @@ -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 相关指标 diff --git a/agent/model/model_ext.go b/agent/model/model_ext.go index c757b44..60b8fd6 100644 --- a/agent/model/model_ext.go +++ b/agent/model/model_ext.go @@ -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 (最大进程数) } diff --git a/agent/model/model_proctop.go b/agent/model/model_proctop.go new file mode 100644 index 0000000..d258ff4 --- /dev/null +++ b/agent/model/model_proctop.go @@ -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"` // 线程数 +} diff --git a/backend/aiops-backend b/backend/aiops-backend new file mode 100755 index 0000000..8f22d5f Binary files /dev/null and b/backend/aiops-backend differ diff --git a/backend/internal/api/handlers/agent.go b/backend/internal/api/handlers/agent.go index 7344699..d40b640 100644 --- a/backend/internal/api/handlers/agent.go +++ b/backend/internal/api/handlers/agent.go @@ -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 diff --git a/backend/internal/api/handlers/alert_channels.go b/backend/internal/api/handlers/alert_channels.go index 6cc81b0..710c26b 100644 --- a/backend/internal/api/handlers/alert_channels.go +++ b/backend/internal/api/handlers/alert_channels.go @@ -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"), + ) +} diff --git a/backend/internal/api/handlers/alert_engine.go b/backend/internal/api/handlers/alert_engine.go index 404f5df..cdb9169 100644 --- a/backend/internal/api/handlers/alert_engine.go +++ b/backend/internal/api/handlers/alert_engine.go @@ -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) + } + } +} diff --git a/backend/internal/api/handlers/alert_rules.go b/backend/internal/api/handlers/alert_rules.go index 776d711..2e2c15e 100644 --- a/backend/internal/api/handlers/alert_rules.go +++ b/backend/internal/api/handlers/alert_rules.go @@ -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}, + }) +} diff --git a/backend/internal/api/handlers/pipeline_executor.go b/backend/internal/api/handlers/pipeline_executor.go index 8512888..6a8f416 100644 --- a/backend/internal/api/handlers/pipeline_executor.go +++ b/backend/internal/api/handlers/pipeline_executor.go @@ -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] diff --git a/backend/internal/api/handlers/tool_config.go b/backend/internal/api/handlers/tool_config.go index c6acdf0..147d11c 100644 --- a/backend/internal/api/handlers/tool_config.go +++ b/backend/internal/api/handlers/tool_config.go @@ -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 + } +} diff --git a/backend/internal/api/routes/routes.go b/backend/internal/api/routes/routes.go index 220385e..899aaa2 100644 --- a/backend/internal/api/routes/routes.go +++ b/backend/internal/api/routes/routes.go @@ -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) } // 自动化运维路由 diff --git a/backend/internal/models/agent.go b/backend/internal/models/agent.go index 48f5354..d5805ef 100644 --- a/backend/internal/models/agent.go +++ b/backend/internal/models/agent.go @@ -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"` diff --git a/backend/internal/models/agent_task.go b/backend/internal/models/agent_task.go index 76f7451..ec3669b 100644 --- a/backend/internal/models/agent_task.go +++ b/backend/internal/models/agent_task.go @@ -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 专用 diff --git a/backend/internal/models/alert.go b/backend/internal/models/alert.go index 0e15d09..c9289aa 100644 --- a/backend/internal/models/alert.go +++ b/backend/internal/models/alert.go @@ -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"` +} diff --git a/backend/internal/models/cicd.go b/backend/internal/models/cicd.go index 89e0f54..00c9a98 100644 --- a/backend/internal/models/cicd.go +++ b/backend/internal/models/cicd.go @@ -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"` diff --git a/backend/internal/models/deploy_tool.go b/backend/internal/models/deploy_tool.go index 1750e64..26f0529 100644 --- a/backend/internal/models/deploy_tool.go +++ b/backend/internal/models/deploy_tool.go @@ -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, }, } } diff --git a/frontend/src/components/deploy/PipelineManager.tsx b/frontend/src/components/deploy/PipelineManager.tsx index 03b1810..61810d7 100644 --- a/frontend/src/components/deploy/PipelineManager.tsx +++ b/frontend/src/components/deploy/PipelineManager.tsx @@ -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([]); @@ -288,33 +288,46 @@ export function PipelineManager() { ))} - {/* ══════════ 全流程可视化横幅 // Logan.Li ══════════ */} -
-
- - Git 代码 + {/* ══════════ 全流程可视化横幅 — 双路径 ══════════ */} +
+ {/* 路径 1: SSH 传统主机部署 */} +
+
+ + 构建 + + + 部署 + +
+ + SSH 主机 +
+
+

传统主机 SCP 部署 · 无需镜像仓库

- -
- - 构建 + {/* 分隔 */} +
+ {/* 路径 2: Kubernetes 容器部署 */} +
+
+ + 构建 + + + 镜像仓库 + + + 部署 + +
+ + Kubernetes +
+
+

容器化部署 · 需镜像仓库推送

- -
- - 镜像仓库 -
- -
- - 部署 -
- -
- - K8s -
- 全流程可视化 + 全流程可视化
@@ -401,7 +414,7 @@ export function PipelineManager() { )}
{pipeline.deploy_mode === 'tag' ? 'Tag发版' : pipeline.branch || 'main'} - {(pipeline.deploy_target || 'ssh') === 'k8s' ? <>K8s : <>SSH} + {(pipeline.deploy_target || 'ssh') === 'k8s' ? <>Kubernetes : <>SSH 主机} {repo && {repo.name}} {registry && {registry.name}} {pipeline.last_run_at && {new Date(pipeline.last_run_at).toLocaleString('zh-CN')}} @@ -560,7 +573,7 @@ export function PipelineManager() {
{[ { 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() {
-

设为 1 则按顺序串行执行,超过 1 可并发构建

+

设为 1 则按顺序串行执行,默认 2 可并发构建

@@ -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; diff --git a/frontend/src/components/deploy/ToolConfigTab.tsx b/frontend/src/components/deploy/ToolConfigTab.tsx index 7c1a0f2..d05c949 100644 --- a/frontend/src/components/deploy/ToolConfigTab.tsx +++ b/frontend/src/components/deploy/ToolConfigTab.tsx @@ -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 = { - k8s: 'K8s', build: '构建', deploy: '部署', automation: '自动化', other: '其他', + build: '构建', deploy: '部署', automation: '自动化', other: '其他', }; const categoryColor: Record = { - 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 = { 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([]); const [loading, setLoading] = useState(false); const [installing, setInstalling] = useState(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(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 (
@@ -117,84 +165,164 @@ export default function ToolConfigTab() { - {tools.map(tool => ( - - -
{tool.display_name}
-
{tool.name}
- {tool.installed_version && tool.status === 'installed' && ( -
v{tool.installed_version}
- )} - {tool.error_msg && ( -
{tool.error_msg}
- )} - - - - {categoryLabel[tool.category] || tool.category} - - - - - - - {tool.status === 'installed' ? ( - - 已安装 - - ) : tool.status === 'installing' ? ( - - 安装中 - - ) : tool.status === 'failed' ? ( - - 失败 - - ) : ( - - 未安装 - - )} - - -
- {tool.install_method === 'lazy' && tool.status !== 'installed' && ( - + {tools.map(tool => { + const hasVersions = VERSIONED_TOOLS.includes(tool.name); + return ( + + +
{tool.display_name}
+
{tool.name}
+ {tool.description && ( +
{tool.description}
)} - -
- - - ))} + {tool.installed_version && tool.status === 'installed' && ( +
v{tool.installed_version}
+ )} + {tool.error_msg && ( +
{tool.error_msg}
+ )} + + + + {categoryLabel[tool.category] || tool.category} + + + + + + + {tool.status === 'installed' ? ( + + 已安装 + + ) : tool.status === 'installing' ? ( + + 安装中 + + ) : tool.status === 'failed' ? ( + + 失败 + + ) : ( + + 未安装 + + )} + + +
+ {tool.install_method === 'lazy' && tool.status !== 'installed' && ( + hasVersions ? ( + + ) : ( + + ) + )} + {tool.install_method === 'lazy' && ( + + )} + +
+ + + ); + })}
)} + + {/* ══════════ 版本选择弹框 ══════════ */} + setVersionDialog(null)}> + + + 选择安装版本 + + {versionDialog?.tool.display_name} — 请选择要安装的版本 + + +
+
+ {versionDialog?.versions.map((v, i) => ( + + ))} +
+
+ + +
+
+
+
); } diff --git a/frontend/src/components/deploy/releaseHelpers.tsx b/frontend/src/components/deploy/releaseHelpers.tsx index 3f5b4ac..e05b85f 100644 --- a/frontend/src/components/deploy/releaseHelpers.tsx +++ b/frontend/src/components/deploy/releaseHelpers.tsx @@ -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: '--' }, ]; diff --git a/frontend/src/components/kubernetes/DeploymentEditAdvanced.tsx b/frontend/src/components/kubernetes/DeploymentEditAdvanced.tsx index da6b62b..f1980ac 100644 --- a/frontend/src/components/kubernetes/DeploymentEditAdvanced.tsx +++ b/frontend/src/components/kubernetes/DeploymentEditAdvanced.tsx @@ -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>([]); + // ──── 调度策略 ──── + const [scheduleMode, setScheduleMode] = useState<'nodeName' | 'nodeSelector' | 'nodeAffinity'>('nodeSelector'); + const [nodeName, setNodeName] = useState(''); + const [availableNodes, setAvailableNodes] = useState }>>([]); + const [nodesLoading, setNodesLoading] = useState(false); + // 标签选择器 — key=value 列表(替代原 nodeSelectorKv) + const [labelSelectorKv, setLabelSelectorKv] = useState>([]); + // 预置标签(从节点聚合) + const [nodeLabels, setNodeLabels] = useState>({}); const [tolerations, setTolerations] = useState([]); 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 = {}; + 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 = {}; - 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 = {}; + 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, - {/* 调度:nodeSelector + tolerations */} + {/* 调度:节点名称 / 标签选择器 / 节点亲和性 */} - - 调度 (Scheduling) - - - - {/* nodeSelector */} -
-
- - +
+ + 调度 (Scheduling) + +
+ {([ + { key: 'nodeName' as const, label: '节点名称', desc: '指定节点' }, + { key: 'nodeSelector' as const, label: '标签选择器', desc: 'key=value' }, + { key: 'nodeAffinity' as const, label: '节点亲和性', desc: '高级规则' }, + ]).map(m => ( + + ))}
- {nodeSelectorKv.length === 0 ? ( -

未配置

- ) : nodeSelectorKv.map((n, i) => ( -
- 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" /> - : - 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" /> -
+

+ {scheduleMode === 'nodeName' && 'Pod 将直接调度到指定节点'} + {scheduleMode === 'nodeSelector' && 'Pod 将调度到匹配标签的节点'} + {scheduleMode === 'nodeAffinity' && '通过亲和性规则控制 Pod 调度到指定节点'} +

+ + + {/* 节点名称模式 */} + {scheduleMode === 'nodeName' && ( +
+ + {nodesLoading ? ( +
加载节点列表...
+ ) : ( + + )} + {nodeName && ( +
+ 已选择: {nodeName} +
+ )} +
+ )} + + {/* 标签选择器模式 */} + {scheduleMode === 'nodeSelector' && ( +
+
+ +
- ))} -
- - {/* tolerations */} -
-
- - -
- {tolerations.length === 0 ? ( -

未配置

- ) : tolerations.map((t, i) => ( -
-
- - 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" /> -
-
- - 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"> + + {Object.entries(nodeLabels).map(([k, vals]) => ( + + ))} -
-
- - 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" /> -
-
- - 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}> + + {(nodeLabels[n.key] || []).map(v => ( + + ))} -
-
- 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" /> -
+ ))} +
+ )} + + {/* 节点亲和性模式 */} + {scheduleMode === 'nodeAffinity' && ( +
+
+ +
- ))} -
+ {labelSelectorKv.length === 0 ? ( +

未配置亲和性规则

+ ) : labelSelectorKv.map((n, i) => ( +
+ + + +
+ ))} +
+ )}
diff --git a/frontend/src/components/kubernetes/DeploymentEditService.tsx b/frontend/src/components/kubernetes/DeploymentEditService.tsx index a649c67..84956b3 100644 --- a/frontend/src/components/kubernetes/DeploymentEditService.tsx +++ b/frontend/src/components/kubernetes/DeploymentEditService.tsx @@ -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 || '', 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): 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,
- Deployment selector: + 选择器:
{Object.entries(selectorLabels).map(([k, v]) => ( {k}={v} @@ -289,19 +310,20 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName, {matchedSvcs.length} 个关联
-

- 仅显示 selector 匹配此 Deployment 的关联 Service -

+

仅显示 selector 匹配此 Deployment 的关联 Service

- {matchedSvcs.length === 0 ? ( + {matchedSvcs.length === 0 && showCreate !== 'service' ? (
- 当前命名空间暂无 Service + 当前命名空间暂无关联 Service
) : (
@@ -320,8 +342,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName, YAML
@@ -329,7 +350,8 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
{svc.ports.map((p, i) => ( - {p.port}:{p.targetPort}{p.nodePort ? `/NodePort:${p.nodePort}` : ''}/{p.protocol} + {p.name && {p.name}: } + {p.port}→{p.targetPort}{p.nodePort ? `/NodePort:${p.nodePort}` : ''}/{p.protocol} ))}
@@ -346,12 +368,14 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
)} - {/* 创建 Service 表单 */} + {/* ══════════ 创建 Service 表单 — 多端口 ══════════ */} {showCreate === 'service' && ( -
+
创建新 Service
+ + {/* 基本信息 */}
@@ -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"> -
-
- - 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" /> +
+ + {/* 快速预设 */} +
+ +
+ {PORT_PRESETS.map(p => ( + + ))}
-
- - 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" /> -
- {(svcForm.type === 'NodePort' || svcForm.type === 'LoadBalancer') && ( -
- - 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" /> +
+ + {/* 端口列表 */} +
+ + {svcForm.ports.map((p, i) => ( +
+ {/* 名称 */} + 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" /> + {/* 协议 */} + + {/* port → targetPort */} + 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" /> + → + 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' && ( + 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" /> + )} + {/* 删除 */} +
+ ))} + {/* 添加自定义端口 */} + +
+ + {/* Selector 预览 */} +
+ selector (自动检测): + {Object.keys(selectorLabels).length > 0 ? ( + Object.entries(selectorLabels).map(([k, v]) => ( + {k}={v} + )) + ) : ( + 未检测到 )}
+
@@ -406,13 +485,14 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName, {matchedIngs.length}/{ingresses.length}
-

- backend 指向关联 Service 的 Ingress 自动高亮 -

+

backend 指向关联 Service 的 Ingress 自动高亮

{ingresses.length === 0 ? ( @@ -436,8 +516,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName, YAML
@@ -497,19 +576,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName, 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" />
-
- - -
-

- 后端将指向此 Deployment 关联的第一个 Service: {matchedSvcs[0]?.name || `${deploymentName}-svc`} -

@@ -519,27 +586,16 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName, - {/* 底部说明 */} -
- -
-

Service / Ingress 是独立的 K8s 资源,保存即创建,不会修改 Deployment 本身。

-

编辑 Deployment manifest 请使用「基本信息」「容器信息」「存储挂载」「高级设置」Tab。

-
-
- - {/* YAML 编辑弹窗 */} + {/* YAML 弹窗 */} {yamlModal && ( - setYamlModal(null)} - onSaved={load} - /> +
{/* YamlViewer can be re-added here if needed */}
)} + + {/* 底部操作 */} +
+ + +
); } diff --git a/frontend/src/components/kubernetes/DeploymentEditStorage.tsx b/frontend/src/components/kubernetes/DeploymentEditStorage.tsx index c21f5f4..a3813f3 100644 --- a/frontend/src/components/kubernetes/DeploymentEditStorage.tsx +++ b/frontend/src/components/kubernetes/DeploymentEditStorage.tsx @@ -1,15 +1,15 @@ -// DeploymentEditStorage.tsx — 编辑器「存储挂载」Tab (M8) -// 编辑内容:spec.template.spec.volumes[] — 数据卷定义 -// 支持 6 种常用 volume 类型:emptyDir / hostPath / configMap / secret / persistentVolumeClaim / nfs -// 作者: Logan +// 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 = { - 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([]); const [rawManifest, setRawManifest] = useState(manifest || {}); - // 容器已声明的 volumeMounts(只读展示,便于用户对齐 volume name) - const [mountSummary, setMountSummary] = useState>([]); + const [volumes, setVolumes] = useState([]); + const [mounts, setMounts] = useState([]); + const [containers, setContainers] = useState([]); 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) => 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) => + 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 (
- {/* 数据卷列表 */} + {/* ══════════ 定义数据卷 ══════════ */}
- - 数据卷 (Volumes) + 定义数据卷 {volumes.length}
-

- Pod 级别的卷定义,容器通过 volumeMounts 引用这些卷名。 -

{volumes.length === 0 ? (
- 未配置数据卷,点击右上角「添加数据卷」 + 未配置数据卷
) : 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 ( -
-
- - updateVolume(i, { name: e.target.value })} +
+ {/* 卷名 + 类型 */} +
+ + 数据卷名称 + 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" - /> - -
- {/* 类型相关字段 */} + {/* 类型指定字段 */} + {vol.type === 'persistentVolumeClaim' && ( +
+ 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" /> + +
+ )} + {vol.type === 'emptyDir' && ( -
-
- - 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" /> -
-
- - 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" /> -
+
+ 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" />
)} {vol.type === 'hostPath' && ( -
-
- - 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" /> -
-
- - -
-
- )} - - {vol.type === 'configMap' && ( -
- - 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" /> - - 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" /> -
- )} - - {vol.type === 'secret' && ( -
- - 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" /> - - 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" /> -
- )} - - {vol.type === 'persistentVolumeClaim' && ( -
-
- - 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" /> -
-
- -
+
+ 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" /> +
)} {vol.type === 'nfs' && ( -
-
- - 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" /> -
-
- - 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" /> -
-
- -
+
+ 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" /> + : + 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" /> + +
+ )} + + {vol.type === 'configMap' && ( +
+ ConfigMap + 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" /> + 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" /> +
+ )} + + {vol.type === 'secret' && ( +
+ 密文 + 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" /> + 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" />
)}
@@ -395,41 +350,69 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName, - {/* 容器 volumeMounts 汇总(只读) */} - {mountSummary.length > 0 && ( - - + {/* ══════════ 挂载到容器 ══════════ */} + + +
- - 容器挂载点 (volumeMounts) + 将数据卷挂载到容器 + {mounts.length} -

- 容器侧已声明的挂载,请在「容器信息」Tab 修改。 -

- - - {mountSummary.map((s, i) => ( -
- - {s.container} - -
- {s.mounts.map((m, j) => ( - {m} - ))} -
+ +
+ + + {mounts.length === 0 ? ( +
+ + {volumeNames.length === 0 ? '请先定义数据卷' : '未配置挂载点'} +
+ ) : mounts.map((m, i) => ( +
+ {/* 容器选择 */} + 容器: + + {/* 数据卷选择 */} + + {/* 挂载路径 */} + 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" /> + {/* 只读/读写 */} +
+ +
- ))} - - - )} + +
+ ))} +
+ {/* 操作栏 */}
diff --git a/frontend/src/components/monitor/alert-center/AlertChannelDialog.tsx b/frontend/src/components/monitor/alert-center/AlertChannelDialog.tsx index 794f79a..ce5e50a 100644 --- a/frontend/src/components/monitor/alert-center/AlertChannelDialog.tsx +++ b/frontend/src/components/monitor/alert-center/AlertChannelDialog.tsx @@ -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://..."}' }, diff --git a/frontend/src/components/monitor/alert-center/alert-center-helpers.tsx b/frontend/src/components/monitor/alert-center/alert-center-helpers.tsx index a1932b6..e7e7900 100644 --- a/frontend/src/components/monitor/alert-center/alert-center-helpers.tsx +++ b/frontend/src/components/monitor/alert-center/alert-center-helpers.tsx @@ -116,12 +116,18 @@ export function getChannelIcon(type: string) { case 'slack': return ; case 'sms': return ; case 'webhook': return ; + case 'feishu': return ; + case 'dingtalk': return ; + case 'wechat': return ; default: return ; } } /** 渠道类型中文标签 */ export function getChannelTypeLabel(type: string) { - const map: Record = { dingtalk: '钉钉', wechat: '企业微信', email: '邮件', sms: '短信', webhook: 'Webhook' }; + const map: Record = { + dingtalk: '钉钉', wechat: '企业微信', feishu: '飞书', + email: '邮件', sms: '短信', webhook: 'Webhook', + }; return map[type] || type; } diff --git a/frontend/src/pages/HostMonitor.tsx b/frontend/src/pages/HostMonitor.tsx index 9f39d68..3999720 100644 --- a/frontend/src/pages/HostMonitor.tsx +++ b/frontend/src/pages/HostMonitor.tsx @@ -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() { )}
-
- {/* 聚合类型选择 */} - - {/* 时间范围 */}
{TIME_RANGES.map(tr => ( - + ))}
- 聚合: {aggType}
{/* 分类 Tab */} - + {[ { id: 'basic', label: '基础监控', icon: }, { id: 'disk', label: '磁盘监控', icon: }, { id: 'network', label: '网络监控', icon: }, + { id: 'process', label: '进程监控', icon: }, { id: 'system', label: '系统信息', icon: }, ].map(tab => ( @@ -270,64 +250,135 @@ export function HostMonitor() { ))} - {/* 基础监控 */} + {/* 基础监控 — 增加 Swap 卡片 */} - } - data={metrics.cpu} color="#3b82f6" unit="%" domain={[0, 100]} aggType={aggType} - /> - } - data={metrics.mem} color="#10b981" unit="%" domain={[0, 100]} aggType={aggType} - /> - } - data={metrics.load1} color="#8b5cf6" unit="" domain={[0, 'auto']} aggType={aggType} - /> + } + data={metrics.cpu} color="#3b82f6" unit="%" domain={[0, 100]} aggType={aggType} /> + } + data={metrics.mem} color="#10b981" unit="%" domain={[0, 100]} aggType={aggType} /> + } + data={metrics.load1} color="#8b5cf6" unit="" domain={[0, 'auto']} aggType={aggType} /> {/* 磁盘监控 */}
- } - data={metrics.disk} color="#f97316" unit="%" domain={[0, 100]} aggType={aggType} - /> - } - data={metrics.ioRead} color="#3b82f6" unit="KB/s" domain={[0, 'auto']} aggType={aggType} - /> - } - data={metrics.ioWrite} color="#10b981" unit="KB/s" domain={[0, 'auto']} aggType={aggType} - /> -
-
- } - data={metrics.ioReadOps} color="#6366f1" unit="count/s" domain={[0, 'auto']} aggType={aggType} - /> - } - data={metrics.ioWriteOps} color="#22d3ee" unit="count/s" domain={[0, 'auto']} aggType={aggType} - /> + } + data={metrics.disk} color="#f97316" unit="%" domain={[0, 100]} aggType={aggType} /> + } + data={metrics.ioRead} color="#3b82f6" unit="KB/s" domain={[0, 'auto']} aggType={aggType} /> + } + data={metrics.ioWrite} color="#10b981" unit="KB/s" domain={[0, 'auto']} aggType={aggType} />
- {/* 网络监控 */} + {/* 网络监控 — 增加 TIME_WAIT + FD 图表 */} - } - data={metrics.tcpEst} color="#8b5cf6" unit="个" domain={[0, 'auto']} aggType={aggType} - /> - } - data={metrics.rx} color="#3b82f6" unit="KB/s" domain={[0, 'auto']} aggType={aggType} - /> - } - data={metrics.tx} color="#10b981" unit="KB/s" domain={[0, 'auto']} aggType={aggType} - /> + } + data={metrics.tcpEst} color="#8b5cf6" unit="个" domain={[0, 'auto']} aggType={aggType} /> + } + data={metrics.tcpTW} color="#f59e0b" unit="个" domain={[0, 'auto']} aggType={aggType} /> + } + data={metrics.rx} color="#3b82f6" unit="KB/s" domain={[0, 'auto']} aggType={aggType} /> + + + {/* ═══ 进程监控 — v2.0 新增 ═══ */} + + {/* 进程 TOP 表格 */} + + +

+ 进程 TOP {processTop.length} (按内存排序) +

+ {processTop.length === 0 ? ( +
+ Agent v2.0+ 支持,当前无数据 +
+ ) : ( + + + + + + + + + + + + {processTop.map((p: any, i: number) => ( + + + + + + + + ))} + +
PID进程名内存 (MB)FD 数线程数
{p.pid}{p.name}{(p.memory_mb ?? 0).toFixed(0)}{p.fd_count ?? 0}{p.threads ?? 0}
+ )} +
+
+ + {/* Swap + FD + CS 快速卡片 */} +
+ } + data={metrics.swap} color="#f43f5e" unit="%" domain={[0, 100]} aggType={aggType} + /> + } + data={metrics.fd} color="#22d3ee" unit="%" domain={[0, 100]} aggType={aggType} + /> + {/* CS 当前值卡片 */} + + +
+ 上下文切换 +
+
+ {csInfo?.ctx_per_sec != null ? `${(csInfo.ctx_per_sec / 1000).toFixed(1)}K/s` : '--'} +
+
+ 中断: {csInfo?.irq_per_sec != null ? `${(csInfo.irq_per_sec / 1000).toFixed(1)}K/s` : '--'} +
+
+
+
+ + {/* FD / Swap 详情 */} +
+ {fdInfo && fdInfo.max > 0 && ( + + + 文件句柄 +
+ {fdInfo.allocated} + / {fdInfo.max} +
+
+
+
+ + + )} + {swapInfo && swapInfo.total_gb > 0 && ( + + + Swap +
+ {(swapInfo.used_gb ?? 0).toFixed(1)} + / {(swapInfo.total_gb ?? 0).toFixed(0)} GB +
+
+
50 ? 'bg-rose-500' : 'bg-amber-500'}`} + style={{ width: `${Math.min(swapInfo.usage_percent || 0, 100)}%` }} /> +
+ + + )} +
{/* 系统信息 */} @@ -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]) => (
{label}: @@ -374,7 +426,7 @@ export function HostMonitor() { )} - {/* 磁盘分区 */} + {/* 磁盘分区 + 网络接口 (保持原样) */} {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 ( -
- -

磁盘分区

-
+

磁盘分区

{parts.map((p: any, i: number) => (
@@ -402,31 +451,13 @@ export function HostMonitor() { ); })()} - - {/* 网络接口 */} - {netInfo && ( - - -
- -

网络接口

-
-
-
网卡:{netInfo.nic_name || '—'}
-
接收:{netInfo.net_rx_bps ? `${(netInfo.net_rx_bps/1024).toFixed(1)} KB/s` : '—'}
-
发送:{netInfo.net_tx_bps ? `${(netInfo.net_tx_bps/1024).toFixed(1)} KB/s` : '—'}
-
EST/TW:{netInfo.tcp_established || 0}/{netInfo.tcp_time_wait || 0}
-
-
-
- )}
); } -// ═══════ 指标图表卡片 (带 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 ( - {/* 标题行 */}
-
- {icon} - {title} -
- - {aggType === 'avg' ? '平均值' : aggType === 'max' ? '最大值' : '最小值'} - +
{icon}{title}
- - {/* 当前值 */}
{value} {unit && {unit}}
- - {/* 趋势图 + Brush 缩放 */}
{chartData.length === 0 ? ( -
- 暂无数据 -
+
暂无数据
) : ( @@ -478,33 +491,12 @@ function MetricChartCard({ max * 1.1] : domain as [number, number]} /> - [`${v.toFixed(2)} ${unit}`, title.replace(/\(.+\)/, '')]} - labelFormatter={(label) => `时间: ${label}`} - /> + labelFormatter={(label) => `时间: ${label}`} /> - {/* Brush 缩放条 — 可拖动选择时间范围,鼠标滚轮精细调整 */} - t} - startIndex={Math.max(0, chartData.length - Math.min(20, chartData.length))} - /> - {/* 参考线:平均值 */} - {chartData.length > 0 && ( - s + d.value, 0) / chartData.length} - stroke={color} - strokeOpacity={0.3} - strokeDasharray="4 4" - /> - )} + )} @@ -513,5 +505,3 @@ function MetricChartCard({ ); } - -export default HostMonitor; diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts index 783b2eb..564e22b 100644 --- a/frontend/src/services/api.ts +++ b/frontend/src/services/api.ts @@ -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('/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 ==================== diff --git a/scripts/test_feishu_alert.py b/scripts/test_feishu_alert.py new file mode 100644 index 0000000..c7629d0 --- /dev/null +++ b/scripts/test_feishu_alert.py @@ -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)