This commit is contained in:
Logan committed 2026-07-09 14:16:56 +08:00
1 parent 0690285147
commit 5618cd2738
154 files changed
+5021 -3161

No files matched your search

+18 -18
View File
@@ -61,29 +61,29 @@ func (h *AgentHandler) ReceiveReport(c *gin.Context) {
// 存储到数据库
report := model.AgentReport{
Hostname: req.Hostname,
CPUUsage: req.CPU.UsagePercent,
CPUIOwait: req.CPU.IOWait,
CPUCores: req.CPU.CoreCount,
Load1: req.CPU.Load1,
Load5: req.CPU.Load5,
Load15: req.CPU.Load15,
MemTotal: req.Memory.TotalGB,
MemUsed: req.Memory.UsedGB,
MemUsage: req.Memory.UsagePercent,
Hostname: req.Hostname,
CPUUsage: req.CPU.UsagePercent,
CPUIOwait: req.CPU.IOWait,
CPUCores: req.CPU.CoreCount,
Load1: req.CPU.Load1,
Load5: req.CPU.Load5,
Load15: req.CPU.Load15,
MemTotal: req.Memory.TotalGB,
MemUsed: req.Memory.UsedGB,
MemUsage: req.Memory.UsagePercent,
MemAvailable: req.Memory.AvailableGB,
MemSwapUsed: req.Memory.SwapUsedGB,
DiskInfo: string(diskJSON),
PortInfo: string(portJSON),
NetInfo: string(netJSON),
DiskIOInfo: string(dioJSON),
DiskInfo: string(diskJSON),
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,
ReportTime: reportTime,
}
if err := h.db.Create(&report).Error; err != nil {
@@ -99,9 +99,9 @@ func (h *AgentHandler) ReceiveReport(c *gin.Context) {
for _, d := range req.Disks {
totalDiskGB += d.TotalGB
}
memGB := math.Ceil(req.Memory.TotalGB) // 31.34 → 32, 62.79 → 63(物理内存向上取整)
memMB := int64(memGB * 1024) // GB → MB
diskGB := int64(totalDiskGB + 0.5) // 39.99 → 40
memGB := math.Ceil(req.Memory.TotalGB) // 31.34 → 32, 62.79 → 63(物理内存向上取整)
memMB := int64(memGB * 1024) // GB → MB
diskGB := int64(totalDiskGB + 0.5) // 39.99 → 40
clientIP := c.ClientIP()
+209 -37
View File
@@ -19,6 +19,7 @@ import (
"ezops/model"
"ezops/pkg/agentcli"
"ezops/pkg/agentcli/core"
"ezops/pkg/agentcli/guardrail"
"ezops/pkg/agentcli/llm"
"ezops/pkg/agentcli/safety"
"ezops/pkg/agentcli/tools"
@@ -86,7 +87,7 @@ type agentConn struct {
server model.Server
sshCfg remoteexec.SSHConfig
kubernetesCtx *kubernetesAgentContext
session *model.AgentCLISession
session *model.AIRun
taskCtx context.Context
cancel context.CancelFunc
totalTokens int
@@ -97,6 +98,9 @@ type agentConn struct {
convHistory []llm.Message
running bool
runningMu sync.Mutex
pendingSpans map[string]string
seq int
seqMu sync.Mutex
}
// Run WebSocket 入口 // Logan.Li
@@ -144,7 +148,7 @@ func (h *AgentCLIHandler) runHostWS(c *gin.Context) {
ac := &agentConn{
conn: conn, db: h.db, mode: agentcli.RunModeHost,
userID: middleware.GetUserID(c), server: server, sshCfg: sshCfg,
taskCtx: context.Background(), confirms: make(map[string]chan bool),
taskCtx: context.Background(), confirms: make(map[string]chan bool), pendingSpans: make(map[string]string),
}
ac.write(wsEvent{Type: "session", SessionID: 0,
Message: fmt.Sprintf("已连接主机 %s(%s),LLM: %s。请描述要执行的任务。", server.Hostname, server.IP, llmCfg.Model)})
@@ -181,7 +185,7 @@ func (h *AgentCLIHandler) runKubernetesWS(c *gin.Context) {
ac := &agentConn{
conn: conn, db: h.db, mode: agentcli.RunModeKubernetes,
userID: middleware.GetUserID(c), kubernetesCtx: kCtx,
taskCtx: context.Background(), confirms: make(map[string]chan bool),
taskCtx: context.Background(), confirms: make(map[string]chan bool), pendingSpans: make(map[string]string),
}
target := buildKubernetesTargetInfo(kCtx)
ac.write(wsEvent{Type: "session", SessionID: 0,
@@ -194,7 +198,9 @@ func (ac *agentConn) wsReadLoop() {
for {
_, data, err := ac.conn.ReadMessage()
if err != nil {
ac.abort()
if ac.isRunning() {
ac.abort()
}
return
}
var ctrl wsControl
@@ -256,20 +262,27 @@ func (ac *agentConn) startTask(query, safetyMode string) {
if r := []rune(title); len(r) > 60 {
title = string(r[:60]) + "..."
}
sess := &model.AgentCLISession{
UserID: ac.userID, Mode: ac.mode, Title: title, Status: "running",
sess := &model.AIRun{
RunID: guardrail.NewTraceID(), UserID: ac.userID, Feature: "agent_cli",
Mode: ac.mode, Title: title, Status: "running",
Provider: llmCfg.Provider, Model: llmCfg.Model,
SafetyMode: safetyMode, StartedAt: time.Now(),
}
if ac.mode == agentcli.RunModeKubernetes && ac.kubernetesCtx != nil {
sess.ClusterID = ac.kubernetesCtx.cluster.ID
sess.ClusterName = ac.kubernetesCtx.cluster.Name
sess.Namespace = ac.kubernetesCtx.namespace
sess.PodName = ac.kubernetesCtx.podName
sess.Container = ac.kubernetesCtx.container
sess.SubjectType = "k8s_cluster"
if ac.kubernetesCtx.podName != "" {
sess.SubjectType = "pod"
} else if ac.kubernetesCtx.namespace != "" {
sess.SubjectType = "namespace"
}
sess.SubjectID = fmt.Sprintf("%d", ac.kubernetesCtx.cluster.ID)
sess.SubjectName = ac.kubernetesCtx.cluster.Name
sess.SubjectScope = ac.kubernetesCtx.namespace
} else {
sess.ServerID = ac.server.ID
sess.ServerName = ac.server.Hostname
sess.ServerHost = ac.server.IP
sess.SubjectType = "host"
sess.SubjectID = fmt.Sprintf("%d", ac.server.ID)
sess.SubjectName = ac.server.Hostname
sess.SubjectScope = ac.server.IP
}
if err := ac.db.Create(sess).Error; err != nil {
ac.write(wsEvent{Type: "error", Message: "创建会话失败: " + err.Error()})
@@ -287,15 +300,15 @@ func (ac *agentConn) resumeSession(sessionID uint) {
ac.write(wsEvent{Type: "error", Message: "任务进行中,请等待完成或停止"})
return
}
var sess model.AgentCLISession
var sess model.AIRun
q := ac.db.Where("user_id = ?", ac.userID)
if ac.mode == agentcli.RunModeKubernetes {
q = q.Where("mode IN ?", []string{agentcli.RunModeKubernetes, "k8s"})
if ac.kubernetesCtx != nil {
q = q.Where("cluster_id = ? AND namespace = ?", ac.kubernetesCtx.cluster.ID, ac.kubernetesCtx.namespace)
q = q.Where("subject_id = ? AND subject_scope = ?", fmt.Sprintf("%d", ac.kubernetesCtx.cluster.ID), ac.kubernetesCtx.namespace)
}
} else {
q = q.Where("mode = ? AND server_id = ?", ac.mode, ac.server.ID)
q = q.Where("mode = ? AND subject_type = ? AND subject_id = ?", ac.mode, "host", fmt.Sprintf("%d", ac.server.ID))
}
if err := q.First(&sess, sessionID).Error; err != nil {
ac.write(wsEvent{Type: "error", Message: "会话不存在或无权访问"})
@@ -305,8 +318,8 @@ func (ac *agentConn) resumeSession(sessionID uint) {
ac.write(wsEvent{Type: "error", Message: "该会话仍在执行中,无法恢复"})
return
}
var msgs []model.AgentCLIMessage
ac.db.Where("session_id = ?", sessionID).Order("id ASC").Find(&msgs)
var msgs []model.AIRunMessage
ac.db.Where("run_id = ?", sess.RunID).Order("seq ASC, id ASC").Find(&msgs)
ac.session = &sess
ac.convHistory = buildConvHistoryFromMessages(msgs)
ac.setTotalTokens(sess.TotalTokens)
@@ -340,7 +353,7 @@ func (ac *agentConn) continueTask(query, safetyMode string) {
}
// runTask 执行一轮 ReAct(新建或追问共用) // Logan.Li
func (ac *agentConn) runTask(sess *model.AgentCLISession, query, safetyMode string, llmCfg model.LLMConfig, isContinue bool) {
func (ac *agentConn) runTask(sess *model.AIRun, query, safetyMode string, llmCfg model.LLMConfig, isContinue bool) {
if ac.isRunning() {
ac.write(wsEvent{Type: "error", Message: "任务进行中,请等待完成或停止"})
return
@@ -393,9 +406,9 @@ func (ac *agentConn) runTask(sess *model.AgentCLISession, query, safetyMode stri
ac.taskCtx = ctx
ac.cancel = cancel
ac.setRunning(true)
ac.db.Model(sess).Update("status", "running")
ac.db.Model(sess).Updates(map[string]interface{}{"status": "running", "safety_mode": safetyMode})
ac.persistMsg(sess.ID, 0, "user", "user", query, "", "", "", "", false, "", 0)
ac.persistMsg(sess.RunID, 0, "user", "user", query, "", "", "", "", false, "", 0)
targetInfo := ac.buildTargetInfo()
@@ -457,6 +470,9 @@ func (ac *agentConn) onEvent(e core.Event) {
if e.Type == core.EventProgress && e.Tokens > 0 {
ac.setTotalTokens(e.Tokens)
}
if e.Type == core.EventDone || e.Type == core.EventError {
ac.setRunning(false)
}
ev := wsEvent{
Type: string(e.Type), Phase: e.Phase, Summary: e.Summary,
@@ -474,23 +490,25 @@ func (ac *agentConn) onEvent(e core.Event) {
if ac.session == nil {
return
}
sid := ac.session.ID
runID := ac.session.RunID
switch e.Type {
case core.EventStatus:
// status 事件不改 DB schema:duration 字段在 type=status 时复用为 phase。
ac.persistMsg(sid, e.Round, "status", "system", e.Summary, e.ToolName, "", "", e.Risk, e.Phase != core.PhaseError && e.Phase != core.PhaseBlocked, e.Phase, e.Tokens)
ac.persistMsg(runID, e.Round, "status", "system", e.Summary, e.ToolName, "", "", e.Risk, e.Phase != core.PhaseError && e.Phase != core.PhaseBlocked, e.Phase, e.Tokens)
case core.EventThought:
ac.persistMsg(sid, e.Round, "thought", "assistant", e.Thought, "", "", "", "", false, "", 0)
ac.persistMsg(runID, e.Round, "thought", "assistant", e.Thought, "", "", "", "", false, "", 0)
case core.EventToolCall:
argsJSON, _ := json.Marshal(e.ToolArgs)
ac.persistMsg(sid, e.Round, "tool_call", "tool", "", e.ToolName, string(argsJSON), "", e.Risk, false, "", 0)
ac.persistMsg(runID, e.Round, "tool_call", "tool", string(argsJSON), e.ToolName, string(argsJSON), "", e.Risk, false, "", 0)
ac.startToolSpan(e, string(argsJSON))
case core.EventToolResult:
ac.persistMsg(sid, e.Round, "tool_result", "tool", e.Output, e.ToolName, "", "", "", e.Success, e.Duration, 0)
ac.persistMsg(runID, e.Round, "tool_result", "tool", e.Output, e.ToolName, "", "", "", e.Success, e.Duration, 0)
ac.finishToolSpan(e)
case core.EventDone:
ac.setTotalTokens(e.Tokens)
ac.persistMsg(sid, e.Round, "done", "assistant", e.Answer, "", "", "", "", true, "", e.Tokens)
ac.persistMsg(runID, e.Round, "done", "assistant", e.Answer, "", "", "", "", true, "", e.Tokens)
case core.EventError:
ac.persistMsg(sid, e.Round, "error", "assistant", e.Message, "", "", "", "", false, "", 0)
ac.persistMsg(runID, e.Round, "error", "assistant", e.Message, "", "", "", "", false, "", 0)
}
}
@@ -519,6 +537,7 @@ func (ac *agentConn) confirmFn(toolName string, args map[string]interface{}, ris
select {
case approved := <-ch:
ac.recordConfirmSpan(toolName, args, risk, approved)
return approved, nil
case <-ac.taskCtx.Done():
ac.delConfirm(confirmID)
@@ -529,6 +548,25 @@ func (ac *agentConn) confirmFn(toolName string, args map[string]interface{}, ris
}
}
func (ac *agentConn) recordConfirmSpan(toolName string, args map[string]interface{}, risk tools.RiskLevel, approved bool) {
if ac.session == nil {
return
}
decision := "rejected"
status := "skipped"
if approved {
decision = "approved"
status = "success"
}
argsJSON, _ := json.Marshal(args)
span := &model.AIRunSpan{
RunID: ac.session.RunID, SpanID: guardrail.NewSpanID(), Kind: "confirm", Name: toolName,
ToolSource: ac.toolSource(toolName), Input: guardrail.SanitizeJSON(string(argsJSON)),
Risk: risk.String(), Decision: decision, Status: status, StartedAt: time.Now(), CreatedAt: time.Now(),
}
_ = ac.db.Create(span).Error
}
// resolveConfirm 前端回传确认结果 // Logan.Li
func (ac *agentConn) resolveConfirm(confirmID string, approved bool) {
ac.cfMu.Lock()
@@ -571,13 +609,13 @@ func (ac *agentConn) lastRound() int {
return 0
}
var maxRound int
ac.db.Model(&model.AgentCLIMessage{}).Where("session_id = ?", ac.session.ID).
ac.db.Model(&model.AIRunMessage{}).Where("run_id = ?", ac.session.RunID).
Select("COALESCE(MAX(round),0)").Scan(&maxRound)
return maxRound
}
// finish 结束本轮执行并更新会话 DB // Logan.Li
func (ac *agentConn) finish(sess *model.AgentCLISession, status, errMsg string, rounds int, dur time.Duration) {
func (ac *agentConn) finish(sess *model.AIRun, status, errMsg string, rounds int, dur time.Duration) {
ac.setRunning(false)
tokens := ac.getTotalTokens()
// done/error 已由引擎 onEvent 推送;此处仅 aborted 需补推 WS(引擎初始化失败在 runTask 内单独推送) // Logan.Li
@@ -588,6 +626,10 @@ func (ac *agentConn) finish(sess *model.AgentCLISession, status, errMsg string,
"status": status, "rounds": rounds, "duration": dur.Milliseconds(),
"total_tokens": tokens,
}
if status == "done" || status == "error" || status == "aborted" {
now := time.Now()
updates["finished_at"] = &now
}
if errMsg != "" {
updates["error"] = errMsg
}
@@ -602,15 +644,145 @@ func (ac *agentConn) write(ev wsEvent) {
_ = ac.conn.WriteMessage(websocket.TextMessage, b)
}
// persistMsg 持久化一条消息 // Logan.Li
func (ac *agentConn) persistMsg(sid uint, round int, typ, role, content, toolName, args, output, risk string, success bool, dur string, tokens int) {
msg := &model.AgentCLIMessage{
SessionID: sid, Round: round, Type: typ, Role: role, Content: content,
ToolName: toolName, ToolArgs: args, ToolOutput: output, Risk: risk,
Success: success, Duration: dur, Tokens: tokens,
// persistMsg 持久化一条 AI Run 回放消息。 // Logan.Li
func (ac *agentConn) persistMsg(runID string, round int, typ, role, content, toolName, args, output, risk string, success bool, dur string, tokens int) {
content = guardrail.SanitizeText(content)
if typ == "tool_call" {
content = guardrail.SanitizeJSON(content)
}
msg := &model.AIRunMessage{
RunID: runID, Round: round, Seq: ac.nextSeq(),
Type: typ, Role: role, Content: content,
ToolName: toolName, Tokens: tokens,
}
if err := ac.db.Create(msg).Error; err != nil {
// 持久化失败不阻断主流程
_ = err
}
}
func (ac *agentConn) nextSeq() int {
ac.seqMu.Lock()
defer ac.seqMu.Unlock()
ac.seq++
return ac.seq
}
func (ac *agentConn) startToolSpan(e core.Event, argsJSON string) {
if ac.session == nil {
return
}
spanID := guardrail.NewSpanID()
key := ac.pendingSpanKey(e.Round, e.ToolName)
ac.runningMu.Lock()
ac.pendingSpans[key] = spanID
ac.runningMu.Unlock()
span := &model.AIRunSpan{
RunID: ac.session.RunID, SpanID: spanID, Kind: "tool", Name: e.ToolName,
ToolSource: ac.toolSource(e.ToolName), Input: guardrail.SanitizeJSON(argsJSON),
Risk: e.Risk, Decision: "auto", Status: "running",
StartedAt: time.Now(),
}
_ = ac.db.Create(span).Error
}
func (ac *agentConn) finishToolSpan(e core.Event) {
if ac.session == nil {
return
}
key := ac.pendingSpanKey(e.Round, e.ToolName)
ac.runningMu.Lock()
spanID := ac.pendingSpans[key]
delete(ac.pendingSpans, key)
ac.runningMu.Unlock()
if spanID == "" {
return
}
status := "success"
if !e.Success {
status = "error"
}
now := time.Now()
ac.db.Model(&model.AIRunSpan{}).Where("span_id = ?", spanID).Updates(map[string]interface{}{
"output": guardrail.SanitizeText(e.Output), "output_size": e.OutputSize,
"duration": parseDurationMillis(e.Duration), "status": status, "ended_at": &now,
})
ac.recordOpsCommand(e, spanID, status)
}
func (ac *agentConn) pendingSpanKey(round int, toolName string) string {
return fmt.Sprintf("%d:%s", round, toolName)
}
func (ac *agentConn) toolSource(toolName string) string {
switch toolName {
case "ssh_execute":
return "shell"
case "kubernetes_diagnose", "kubernetes_get", "pod_logs", "pod_execute", "kubernetes_action":
return "kubernetes"
case "aiops_asset_search", "aiops_alert_list", "aiops_metric_summary":
return "aiops"
default:
return "builtin"
}
}
func (ac *agentConn) recordOpsCommand(e core.Event, spanID, status string) {
if ac.session == nil {
return
}
command := e.ToolName
if e.ToolArgs != nil {
if cmd, ok := e.ToolArgs["command"].(string); ok && cmd != "" {
command = cmd
} else if action, ok := e.ToolArgs["action"]; ok {
command = fmt.Sprintf("%v %v", action, e.ToolArgs["name"])
}
}
targetType, targetID := ac.currentTarget()
cmd := &model.OpsCommand{
CommandID: guardrail.NewSpanID(), RunID: ac.session.RunID, SpanID: spanID,
UserID: ac.userID, ActorType: "ai", TargetType: targetType, TargetID: targetID,
CommandType: ac.commandType(e.ToolName), Command: guardrail.SanitizeText(command),
Risk: e.Risk, Decision: "auto", Status: status, OutputSize: e.OutputSize,
Duration: parseDurationMillis(e.Duration), ExecutedAt: time.Now(),
}
if !e.Success {
cmd.Error = guardrail.SanitizeText(e.Output)
}
_ = ac.db.Create(cmd).Error
}
func (ac *agentConn) currentTarget() (string, string) {
if ac.mode == agentcli.RunModeKubernetes && ac.kubernetesCtx != nil {
if ac.kubernetesCtx.podName != "" {
return "pod", fmt.Sprintf("%d/%s/%s", ac.kubernetesCtx.cluster.ID, ac.kubernetesCtx.namespace, ac.kubernetesCtx.podName)
}
return "k8s_cluster", fmt.Sprintf("%d", ac.kubernetesCtx.cluster.ID)
}
return "host", fmt.Sprintf("%d", ac.server.ID)
}
func (ac *agentConn) commandType(toolName string) string {
switch toolName {
case "ssh_execute", "pod_execute":
return "shell"
case "kubernetes_diagnose", "kubernetes_action", "kubernetes_get", "pod_logs":
return "kubernetes"
case "aiops_asset_search", "aiops_alert_list", "aiops_metric_summary":
return "api"
default:
return "tool"
}
}
func parseDurationMillis(raw string) int64 {
if raw == "" {
return 0
}
d, err := time.ParseDuration(raw)
if err != nil {
return 0
}
return d.Milliseconds()
}
+13 -11
View File
@@ -26,7 +26,7 @@ func (h *AgentCLIHandler) ListSessions(c *gin.Context) {
pageSize = 20
}
q := h.db.Model(&model.AgentCLISession{}).Where("user_id = ?", uid)
q := h.db.Model(&model.AIRun{}).Where("user_id = ? AND feature = ?", uid, "agent_cli")
if mode := c.Query("mode"); mode != "" {
mode = agentcli.NormalizeRunMode(mode)
if mode == agentcli.RunModeKubernetes {
@@ -36,18 +36,18 @@ func (h *AgentCLIHandler) ListSessions(c *gin.Context) {
}
}
if sid := c.Query("server_id"); sid != "" {
q = q.Where("server_id = ?", sid)
q = q.Where("subject_type = ? AND subject_id = ?", "host", sid)
}
if cid := c.Query("cluster_id"); cid != "" {
q = q.Where("cluster_id = ?", cid)
q = q.Where("subject_id = ?", cid)
}
if ns := c.Query("namespace"); ns != "" {
q = q.Where("namespace = ?", ns)
q = q.Where("subject_scope = ?", ns)
}
var total int64
q.Count(&total)
var sessions []model.AgentCLISession
var sessions []model.AIRun
if err := q.Order("created_at DESC").Offset((page - 1) * pageSize).Limit(pageSize).Find(&sessions).Error; err != nil {
c.JSON(http.StatusOK, model.Response{Code: 500, Message: "查询失败: " + err.Error()})
return
@@ -60,13 +60,13 @@ func (h *AgentCLIHandler) ListSessions(c *gin.Context) {
func (h *AgentCLIHandler) GetSession(c *gin.Context) {
uid := middleware.GetUserID(c)
id := c.Param("id")
var sess model.AgentCLISession
var sess model.AIRun
if err := h.db.Where("user_id = ?", uid).First(&sess, id).Error; err != nil {
c.JSON(http.StatusOK, model.Response{Code: 404, Message: "会话不存在"})
return
}
var msgs []model.AgentCLIMessage
h.db.Where("session_id = ?", id).Order("id ASC").Find(&msgs)
var msgs []model.AIRunMessage
h.db.Where("run_id = ?", sess.RunID).Order("seq ASC, id ASC").Find(&msgs)
c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{"session": sess, "messages": msgs}})
}
@@ -75,16 +75,18 @@ func (h *AgentCLIHandler) GetSession(c *gin.Context) {
func (h *AgentCLIHandler) DeleteSession(c *gin.Context) {
uid := middleware.GetUserID(c)
id := c.Param("id")
var sess model.AgentCLISession
var sess model.AIRun
if err := h.db.Where("user_id = ?", uid).First(&sess, id).Error; err != nil {
c.JSON(http.StatusOK, model.Response{Code: 404, Message: "会话不存在"})
return
}
if err := h.db.Where("session_id = ?", id).Delete(&model.AgentCLIMessage{}).Error; err != nil {
if err := h.db.Where("run_id = ?", sess.RunID).Delete(&model.AIRunMessage{}).Error; err != nil {
c.JSON(http.StatusOK, model.Response{Code: 500, Message: "删除消息失败: " + err.Error()})
return
}
if err := h.db.Delete(&model.AgentCLISession{}, id).Error; err != nil {
_ = h.db.Where("run_id = ?", sess.RunID).Delete(&model.AIRunSpan{}).Error
_ = h.db.Where("run_id = ?", sess.RunID).Delete(&model.OpsCommand{}).Error
if err := h.db.Delete(&model.AIRun{}, id).Error; err != nil {
c.JSON(http.StatusOK, model.Response{Code: 500, Message: "删除会话失败: " + err.Error()})
return
}
+3 -6
View File
@@ -10,7 +10,7 @@ import (
)
// buildConvHistoryFromMessages 将 DB 消息重建为追问用的 prior 历史(不含 system) // Logan.Li
func buildConvHistoryFromMessages(msgs []model.AgentCLIMessage) []llm.Message {
func buildConvHistoryFromMessages(msgs []model.AIRunMessage) []llm.Message {
var out []llm.Message
var pendingThought string
var pendingToolCalls []llm.ToolCall
@@ -40,7 +40,7 @@ func buildConvHistoryFromMessages(msgs []model.AgentCLIMessage) []llm.Message {
case "thought":
pendingThought = m.Content
case "tool_call":
args := validateToolArgsJSON(m.ToolArgs)
args := validateToolArgsJSON(m.Content)
tcID := fmt.Sprintf("hist-%d", m.ID)
pendingToolCalls = append(pendingToolCalls, llm.ToolCall{
ID: tcID, Type: "function",
@@ -56,9 +56,6 @@ func buildConvHistoryFromMessages(msgs []model.AgentCLIMessage) []llm.Message {
pendingToolCallIDs = pendingToolCallIDs[1:]
}
content := m.Content
if content == "" {
content = m.ToolOutput
}
out = append(out, llm.Message{
Role: "tool", Name: m.ToolName, Content: content, ToolCallID: toolID,
})
@@ -86,4 +83,4 @@ func validateToolArgsJSON(raw string) string {
return "{}"
}
return raw
}
}
+1 -1
View File
@@ -108,4 +108,4 @@ func kubernetesEvolveHostKey(ctx *kubernetesAgentContext) string {
return base + "/" + ctx.podName
}
return base
}
}
+1 -1
View File
@@ -339,7 +339,7 @@ func (h *AgentInstallHandler) InstallAgent(c *gin.Context) {
}
c.JSON(http.StatusOK, model.Response{
Code: 200,
Code: 200,
Message: func() string {
if installed {
return "Agent 安装成功,已自动启动并设置开机自启"
+11 -11
View File
@@ -25,7 +25,7 @@ func NewAgentTaskHandler(db *gorm.DB) *AgentTaskHandler {
func (h *AgentTaskHandler) CreateTask(c *gin.Context) {
var req struct {
Hostname string `json:"hostname"`
Type string `json:"type"` // command / script
Type string `json:"type"` // command / script
Command string `json:"command"`
Timeout int `json:"timeout"`
}
@@ -47,12 +47,12 @@ func (h *AgentTaskHandler) CreateTask(c *gin.Context) {
username, _ := c.Get("username")
task := model.AgentTask{
TaskID: uuid.New().String(),
Hostname: req.Hostname,
Type: req.Type,
Command: req.Command,
Timeout: req.Timeout,
Status: "pending",
TaskID: uuid.New().String(),
Hostname: req.Hostname,
Type: req.Type,
Command: req.Command,
Timeout: req.Timeout,
Status: "pending",
CreatedBy: fmt.Sprintf("%v", username),
}
@@ -180,11 +180,11 @@ func (h *AgentTaskHandler) QuickSetupRules(c *gin.Context) {
}
type ruleDef struct {
Name string
Metric string
Operator string
Name string
Metric string
Operator string
Threshold float64
Duration int
Duration int
}
defaultRules := []ruleDef{
-2
View File
@@ -473,5 +473,3 @@ func (h *AlertHandler) NotifyRecovery(ruleName, hostname, metric, message string
}
}
}
+21 -7
View File
@@ -60,11 +60,21 @@ func (h *AlertHandler) UpdateContact(c *gin.Context) {
return
}
updates := map[string]interface{}{}
if req.Name != "" { updates["name"] = req.Name }
if req.Phone != "" { updates["phone"] = req.Phone }
if req.Email != "" { updates["email"] = req.Email }
if req.ChannelType != "" { updates["channel_type"] = req.ChannelType }
if req.WebhookURL != "" { updates["webhook_url"] = req.WebhookURL }
if req.Name != "" {
updates["name"] = req.Name
}
if req.Phone != "" {
updates["phone"] = req.Phone
}
if req.Email != "" {
updates["email"] = req.Email
}
if req.ChannelType != "" {
updates["channel_type"] = req.ChannelType
}
if req.WebhookURL != "" {
updates["webhook_url"] = req.WebhookURL
}
h.db.Model(&contact).Updates(updates)
h.db.First(&contact, id)
c.JSON(http.StatusOK, model.Response{Code: 200, Message: "更新成功", Data: contact})
@@ -127,8 +137,12 @@ func (h *AlertHandler) UpdateContactGroup(c *gin.Context) {
return
}
updates := map[string]interface{}{}
if req.GroupName != "" { updates["group_name"] = req.GroupName }
if req.Notes != "" { updates["notes"] = req.Notes }
if req.GroupName != "" {
updates["group_name"] = req.GroupName
}
if req.Notes != "" {
updates["notes"] = req.Notes
}
if len(req.ContactIDs) > 0 {
idsJSON, _ := json.Marshal(req.ContactIDs)
updates["contact_ids"] = string(idsJSON)
+1 -1
View File
@@ -384,4 +384,4 @@ func isMiddlewareMetric(metric string) bool {
}
}
return false
}
}
+1 -1
View File
@@ -181,4 +181,4 @@ func (e *AlertEngine) fireSNMPAlert(rule model.MonitorAlertRule, device model.SN
// isSNMPMetric 判断 AgentAlert 是否属于 SNMP // Logan.Li
func isSNMPMetric(metric string) bool {
return len(metric) >= 5 && metric[:5] == "snmp_"
}
}
+1 -1
View File
@@ -104,4 +104,4 @@ var metricCatalog = []MetricCatalogCategory{
// GET /api/v1/alerts/metric-catalog
func (h *AlertHandler) GetMetricCatalog(c *gin.Context) {
c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{"categories": metricCatalog}})
}
}
+1 -1
View File
@@ -178,4 +178,4 @@ func fallbackNotifyRecovery(db *gorm.DB, ruleName, hostname, metric, message str
fmt.Printf("[AlertNotify] 飞书恢复回退失败 (渠道:%s): %v\n", ch.Name, err)
}
}
}
}
+11 -11
View File
@@ -79,16 +79,16 @@ func notifyTemplateVars(ruleName, hostname, metric, severity, message string, va
platform = defaultNotifyPlatformName
}
return map[string]string{
"time": time.Now().Format("2006-01-02 15:04:05"),
"platform": platform,
"rule_name": ruleName,
"hostname": hostname,
"metric": metric,
"severity": severity,
"severity_label": sevLabel,
"message": message,
"value": fmt.Sprintf("%.2f", value),
"threshold": fmt.Sprintf("%.2f", threshold),
"time": time.Now().Format("2006-01-02 15:04:05"),
"platform": platform,
"rule_name": ruleName,
"hostname": hostname,
"metric": metric,
"severity": severity,
"severity_label": sevLabel,
"message": message,
"value": fmt.Sprintf("%.2f", value),
"threshold": fmt.Sprintf("%.2f", threshold),
}
}
@@ -134,4 +134,4 @@ func buildAlertContent(ruleName, hostname, metric, severity, message string, val
"**规则名称:** %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"),
)
}
}
+1 -1
View File
@@ -126,4 +126,4 @@ func isValidNotifyCategory(cat model.AlertNotifyCategory) bool {
}
}
return false
}
}
+23 -23
View File
@@ -15,30 +15,30 @@ import (
// CreateSilenceRequest 创建静默规则请求
type CreateSilenceRequest struct {
Name string `json:"name" binding:"required"`
Description string `json:"description"`
RuleIDs []uint `json:"rule_ids"`
TargetIDs []uint `json:"target_ids"`
Name string `json:"name" binding:"required"`
Description string `json:"description"`
RuleIDs []uint `json:"rule_ids"`
TargetIDs []uint `json:"target_ids"`
Matchers []model.AlertSilenceMatcher `json:"matchers"`
SilenceType string `json:"silence_type"`
StartTime string `json:"start_time"`
EndTime string `json:"end_time" binding:"required"`
Weekdays []int `json:"weekdays"`
Status *int `json:"status"`
SilenceType string `json:"silence_type"`
StartTime string `json:"start_time"`
EndTime string `json:"end_time" binding:"required"`
Weekdays []int `json:"weekdays"`
Status *int `json:"status"`
}
// UpdateSilenceRequest 更新静默规则请求
type UpdateSilenceRequest struct {
Name string `json:"name"`
Description string `json:"description"`
RuleIDs []uint `json:"rule_ids"`
TargetIDs []uint `json:"target_ids"`
Name string `json:"name"`
Description string `json:"description"`
RuleIDs []uint `json:"rule_ids"`
TargetIDs []uint `json:"target_ids"`
Matchers []model.AlertSilenceMatcher `json:"matchers"`
SilenceType string `json:"silence_type"`
StartTime string `json:"start_time"`
EndTime string `json:"end_time"`
Weekdays []int `json:"weekdays"`
Status *int `json:"status"`
SilenceType string `json:"silence_type"`
StartTime string `json:"start_time"`
EndTime string `json:"end_time"`
Weekdays []int `json:"weekdays"`
Status *int `json:"status"`
}
// ListSilences GET /alerts/silences
@@ -60,11 +60,11 @@ func (h *AlertHandler) ListSilences(c *gin.Context) {
// 解析 JSON 字段为前端友好的格式
type SilenceWithParsed struct {
model.AlertSilence
RuleIDList []uint `json:"rule_id_list"`
TargetIDList []uint `json:"target_id_list"`
MatcherList []model.AlertSilenceMatcher `json:"matcher_list"`
WeekdayList []int `json:"weekday_list"`
IsActive bool `json:"is_active"`
RuleIDList []uint `json:"rule_id_list"`
TargetIDList []uint `json:"target_id_list"`
MatcherList []model.AlertSilenceMatcher `json:"matcher_list"`
WeekdayList []int `json:"weekday_list"`
IsActive bool `json:"is_active"`
}
var result []SilenceWithParsed
+14 -14
View File
@@ -13,19 +13,19 @@ import (
// UnifiedAlertItem 统一告警事件视图 // Logan.Li
type UnifiedAlertItem struct {
ID string `json:"id"`
SourceType string `json:"source_type"`
RuleName string `json:"rule_name"`
Title string `json:"title"`
Message string `json:"message"`
Severity string `json:"severity"`
Status string `json:"status"`
Target string `json:"target"`
Metric string `json:"metric"`
Value float64 `json:"value"`
Threshold float64 `json:"threshold"`
StartedAt string `json:"started_at"`
ResolvedAt *string `json:"resolved_at,omitempty"`
ID string `json:"id"`
SourceType string `json:"source_type"`
RuleName string `json:"rule_name"`
Title string `json:"title"`
Message string `json:"message"`
Severity string `json:"severity"`
Status string `json:"status"`
Target string `json:"target"`
Metric string `json:"metric"`
Value float64 `json:"value"`
Threshold float64 `json:"threshold"`
StartedAt string `json:"started_at"`
ResolvedAt *string `json:"resolved_at,omitempty"`
}
// ListUnifiedAlerts 统一告警列表(主机 + 中间件 + 站点 + 日志)
@@ -212,4 +212,4 @@ func countSeverityStatus(items []UnifiedAlertItem, sev, status string) int {
}
}
return n
}
}
+4 -4
View File
@@ -114,8 +114,8 @@ func (h *ApprovalHandler) CreateProcess(c *gin.Context) {
var workflowSteps []model.ApprovalWorkflowStep
stepCount := 1
var approvalSteps []struct {
name string
stepType string
name string
stepType string
approverIDs []uint
}
if workflow.ID > 0 {
@@ -126,8 +126,8 @@ func (h *ApprovalHandler) CreateProcess(c *gin.Context) {
}
stepCount++
approvalSteps = append(approvalSteps, struct {
name string
stepType string
name string
stepType string
approverIDs []uint
}{ws.Name, ws.StepType, ParseApproverIDs(ws.ApproverIDs)})
}
+16 -16
View File
@@ -111,14 +111,14 @@ func (h *WorkflowHandler) CreateWorkflow(c *gin.Context) {
for _, s := range req.Steps {
step := model.ApprovalWorkflowStep{
WorkflowID: workflow.ID,
StepNumber: s.StepNumber,
Name: s.Name,
StepType: s.StepType,
ApproverIDs: s.ApproverIDs,
IsRequired: s.IsRequired,
TimeoutHours: s.TimeoutHours,
AutoApprove: s.AutoApproveTimeout,
WorkflowID: workflow.ID,
StepNumber: s.StepNumber,
Name: s.Name,
StepType: s.StepType,
ApproverIDs: s.ApproverIDs,
IsRequired: s.IsRequired,
TimeoutHours: s.TimeoutHours,
AutoApprove: s.AutoApproveTimeout,
}
if step.TimeoutHours == 0 {
step.TimeoutHours = 24
@@ -195,14 +195,14 @@ func (h *WorkflowHandler) UpdateWorkflow(c *gin.Context) {
tx.Where("workflow_id = ?", workflow.ID).Delete(&model.ApprovalWorkflowStep{})
for _, s := range req.Steps {
step := model.ApprovalWorkflowStep{
WorkflowID: workflow.ID,
StepNumber: s.StepNumber,
Name: s.Name,
StepType: s.StepType,
ApproverIDs: s.ApproverIDs,
IsRequired: s.IsRequired,
TimeoutHours: s.TimeoutHours,
AutoApprove: s.AutoApproveTimeout,
WorkflowID: workflow.ID,
StepNumber: s.StepNumber,
Name: s.Name,
StepType: s.StepType,
ApproverIDs: s.ApproverIDs,
IsRequired: s.IsRequired,
TimeoutHours: s.TimeoutHours,
AutoApprove: s.AutoApproveTimeout,
}
if step.TimeoutHours == 0 {
step.TimeoutHours = 24
+1 -1
View File
@@ -82,4 +82,4 @@ func (h *BillingHandler) SyncAccountBilling(c *gin.Context) {
}
c.JSON(http.StatusOK, model.Response{Code: 200, Message: msg, Data: result})
}
}
+2 -2
View File
@@ -34,7 +34,7 @@ func (h *PipelineHandler) ListBuildNodes(c *gin.Context) {
c.JSON(http.StatusOK, model.Response{
Code: 200,
Data: map[string]interface{}{
"list": nodes,
"list": nodes,
"total": len(nodes),
"master": map[string]interface{}{
"name": "Master",
@@ -221,4 +221,4 @@ func (h *PipelineHandler) UpdateBuildMaster(c *gin.Context) {
"name": "Master", "max_executors": cfg.MaxExecutors, "running_count": running,
},
})
}
}
-1
View File
@@ -199,4 +199,3 @@ func (h *CloudAccountHandler) DeleteCloudAccount(c *gin.Context) {
Message: "删除成功",
})
}
-1
View File
@@ -227,4 +227,3 @@ func (h *DomainHandler) UpdateDomain(c *gin.Context) {
Data: domain,
})
}
-1
View File
@@ -129,4 +129,3 @@ func (h *PlatformHandler) DeletePlatform(c *gin.Context) {
}
c.JSON(http.StatusOK, model.Response{Code: 200, Message: "删除成功"})
}
+69 -28
View File
@@ -227,10 +227,28 @@ func (h *CloudSyncHandler) ImportInstances(c *gin.Context) {
ip = inst.InstanceID
}
// 检查是否已存在(按 IP 或 hostname)
var count int64
h.db.Model(&model.Server{}).Where("ip = ? OR hostname = ?", ip, inst.Hostname).Count(&count)
if count > 0 {
hostname := cloudImportHostname(inst)
alias := cloudImportAlias(inst)
// 检查是否已存在(优先实例 ID,其次 IP/hostname),重复导入只补空别名,避免覆盖人工命名。 // Logan.Li
var existing model.Server
existingQuery := h.db.Where("ip = ? OR hostname = ?", ip, hostname)
if inst.InstanceID != "" {
existingQuery = h.db.Where("cloud_instance_id = ? OR ip = ? OR hostname = ?", inst.InstanceID, ip, hostname)
}
if err := existingQuery.Take(&existing).Error; err == nil {
updates := map[string]interface{}{
"cloud_instance_name": inst.InstanceName,
"cloud_instance_id": inst.InstanceID,
"description": "从 " + account.Provider + " 导入 (" + inst.InstanceID + ")",
}
if existing.Alias == "" && alias != "" {
updates["alias"] = alias
}
h.db.Model(&existing).Updates(updates)
skipped++
continue
} else if err != gorm.ErrRecordNotFound {
skipped++
continue
}
@@ -264,33 +282,28 @@ func (h *CloudSyncHandler) ImportInstances(c *gin.Context) {
if ipAddr == "" {
ipAddr = inst.InstanceID
}
hostname := inst.Hostname
if hostname == "" {
hostname = inst.InstanceName
}
if hostname == "" {
hostname = inst.InstanceID
}
// 注意:servers 表的 cloud_id 外键引用的是 clouds 表(非 cloud_accounts),
// region_id 外键引用 regions 表。未找到关联时设为 NULL 避免外键约束失败。
server := model.Server{
Hostname: hostname,
IP: ipAddr,
PublicIP: inst.PublicIP,
Port: defaultPort,
Username: username,
AuthType: "password",
OSType: osType,
Protocol: protocol,
RDPPort: 3389,
OS: osName,
CPU: inst.CPU,
Memory: int64(inst.Memory),
Status: status,
RegionID: regionID, // nil = NULL
Description: "从 " + account.Provider + " 导入 (" + inst.InstanceID + ")",
AgentStatus: "offline",
Hostname: hostname,
Alias: alias,
CloudInstanceName: inst.InstanceName,
CloudInstanceID: inst.InstanceID,
IP: ipAddr,
PublicIP: inst.PublicIP,
Port: defaultPort,
Username: username,
AuthType: "password",
OSType: osType,
Protocol: protocol,
RDPPort: 3389,
OS: osName,
CPU: inst.CPU,
Memory: int64(inst.Memory),
Status: status,
RegionID: regionID, // nil = NULL
Description: "从 " + account.Provider + " 导入 (" + inst.InstanceID + ")",
AgentStatus: "offline",
}
if protocol == "rdp" && hasRDPCred {
applyCredential(rdpCred, rdpPlain, &server)
@@ -317,3 +330,31 @@ func (h *CloudSyncHandler) ImportInstances(c *gin.Context) {
},
})
}
func cloudImportHostname(inst cloud.CloudInstance) string {
// hostname 保留技术主机名;展示友好名称写入 alias/cloud_instance_name。 // Logan.Li
if inst.Hostname != "" && inst.Hostname != inst.InstanceID {
return inst.Hostname
}
if inst.InstanceName != "" && inst.InstanceName != inst.InstanceID {
return inst.InstanceName
}
if inst.PrivateIP != "" {
return inst.PrivateIP
}
if inst.PublicIP != "" {
return inst.PublicIP
}
if inst.InstanceName != "" {
return inst.InstanceName
}
return inst.InstanceID
}
func cloudImportAlias(inst cloud.CloudInstance) string {
// 云导入初始别名优先使用控制台实例名称,后续人工别名不被同步覆盖。 // Logan.Li
if inst.InstanceName != "" && inst.InstanceName != inst.InstanceID {
return inst.InstanceName
}
return ""
}
-258
View File
@@ -1,258 +0,0 @@
package controller
import (
"encoding/json"
"net/http"
"strconv"
ezops "ezops/model"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// CustomDashboardHandler 自定义监控仪表盘 handler // Logan.Li
type CustomDashboardHandler struct {
db *gorm.DB
}
// NewCustomDashboardHandler 创建 handler
func NewCustomDashboardHandler(db *gorm.DB) *CustomDashboardHandler {
return &CustomDashboardHandler{db: db}
}
// ============================================
// DTO
// ============================================
type CreateDashboardReq struct {
Name string `json:"name" binding:"required"`
Description string `json:"description"`
Datasource string `json:"datasource"`
DatasourceURL string `json:"datasource_url"`
Panels string `json:"panels"` // JSON string
IsDefault bool `json:"is_default"`
}
type UpdateDashboardReq struct {
Name *string `json:"name"`
Description *string `json:"description"`
Datasource *string `json:"datasource"`
DatasourceURL *string `json:"datasource_url"`
Panels *string `json:"panels"`
IsDefault *bool `json:"is_default"`
IsFavorite *bool `json:"is_favorite"`
}
// ============================================
// CRUD
// ============================================
// List 仪表盘列表
// GET /api/v1/custom-dashboards
func (h *CustomDashboardHandler) List(c *gin.Context) {
var dashboards []ezops.CustomDashboard
if err := h.db.Order("is_default DESC, updated_at DESC").Find(&dashboards).Error; err != nil {
c.JSON(http.StatusInternalServerError, ezops.Response{Code: 500, Message: "查询失败: " + err.Error()})
return
}
// 转换为前端期望的格式(id 转为 string,panels JSON 解析为数组)
result := make([]gin.H, 0, len(dashboards))
for _, d := range dashboards {
item := gin.H{
"id": strconv.Itoa(int(d.ID)),
"name": d.Name,
"description": d.Description,
"datasource": d.Datasource,
"datasourceUrl": d.DatasourceURL,
"datasource_url": d.DatasourceURL,
"createdAt": d.CreatedAt,
"updatedAt": d.UpdatedAt,
"createdBy": d.CreatedBy,
"isDefault": d.IsDefault,
"is_default": d.IsDefault,
}
// 解析 panels JSON
var panels []interface{}
if d.Panels != "" {
if err := json.Unmarshal([]byte(d.Panels), &panels); err == nil {
item["panels"] = panels
} else {
item["panels"] = []interface{}{}
}
} else {
item["panels"] = []interface{}{}
}
result = append(result, item)
}
c.JSON(http.StatusOK, ezops.Response{Code: 200, Data: gin.H{
"list": result,
"total": len(result),
}})
}
// Get 获取单个仪表盘
// GET /api/v1/custom-dashboards/:id
func (h *CustomDashboardHandler) Get(c *gin.Context) {
id := c.Param("id")
var d ezops.CustomDashboard
if err := h.db.First(&d, id).Error; err != nil {
c.JSON(http.StatusNotFound, ezops.Response{Code: 404, Message: "仪表盘不存在"})
return
}
var panels []interface{}
if d.Panels != "" {
json.Unmarshal([]byte(d.Panels), &panels)
}
if panels == nil {
panels = []interface{}{}
}
c.JSON(http.StatusOK, ezops.Response{Code: 200, Data: gin.H{
"id": strconv.Itoa(int(d.ID)),
"name": d.Name,
"description": d.Description,
"datasource": d.Datasource,
"datasourceUrl": d.DatasourceURL,
"datasource_url": d.DatasourceURL,
"panels": panels,
"createdAt": d.CreatedAt,
"updatedAt": d.UpdatedAt,
"createdBy": d.CreatedBy,
"isDefault": d.IsDefault,
"is_default": d.IsDefault,
}})
}
// Create 创建仪表盘
// POST /api/v1/custom-dashboards
func (h *CustomDashboardHandler) Create(c *gin.Context) {
var req CreateDashboardReq
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, ezops.Response{Code: 400, Message: "参数错误: " + err.Error()})
return
}
if req.Datasource == "" {
req.Datasource = "prometheus"
}
if req.Panels == "" {
req.Panels = "[]"
}
// 如果设为默认,先清除其他默认
if req.IsDefault {
h.db.Model(&ezops.CustomDashboard{}).Where("is_default = ?", true).Update("is_default", false)
}
// 从 JWT 获取用户名
username := "admin"
if u, exists := c.Get("username"); exists {
if s, ok := u.(string); ok {
username = s
}
}
d := ezops.CustomDashboard{
Name: req.Name,
Description: req.Description,
Datasource: req.Datasource,
DatasourceURL: req.DatasourceURL,
Panels: req.Panels,
CreatedBy: username,
IsDefault: req.IsDefault,
}
if err := h.db.Create(&d).Error; err != nil {
c.JSON(http.StatusInternalServerError, ezops.Response{Code: 500, Message: "创建失败: " + err.Error()})
return
}
c.JSON(http.StatusOK, ezops.Response{Code: 200, Message: "创建成功", Data: gin.H{
"success": true,
"id": strconv.Itoa(int(d.ID)),
}})
}
// Update 更新仪表盘
// PUT /api/v1/custom-dashboards/:id
func (h *CustomDashboardHandler) Update(c *gin.Context) {
id := c.Param("id")
var d ezops.CustomDashboard
if err := h.db.First(&d, id).Error; err != nil {
c.JSON(http.StatusNotFound, ezops.Response{Code: 404, Message: "仪表盘不存在"})
return
}
var req UpdateDashboardReq
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, ezops.Response{Code: 400, Message: "参数错误: " + err.Error()})
return
}
updates := map[string]interface{}{}
if req.Name != nil {
updates["name"] = *req.Name
}
if req.Description != nil {
updates["description"] = *req.Description
}
if req.Datasource != nil {
updates["datasource"] = *req.Datasource
}
if req.DatasourceURL != nil {
updates["datasource_url"] = *req.DatasourceURL
}
if req.Panels != nil {
updates["panels"] = *req.Panels
}
if req.IsFavorite != nil {
updates["is_favorite"] = *req.IsFavorite
}
if req.IsDefault != nil && *req.IsDefault {
// 设为默认前先清除其他默认
h.db.Model(&ezops.CustomDashboard{}).Where("is_default = ? AND id != ?", true, d.ID).Update("is_default", false)
updates["is_default"] = true
}
if len(updates) > 0 {
if err := h.db.Model(&d).Updates(updates).Error; err != nil {
c.JSON(http.StatusInternalServerError, ezops.Response{Code: 500, Message: "更新失败: " + err.Error()})
return
}
}
c.JSON(http.StatusOK, ezops.Response{Code: 200, Message: "更新成功", Data: gin.H{"success": true}})
}
// Delete 删除仪表盘
// DELETE /api/v1/custom-dashboards/:id
func (h *CustomDashboardHandler) Delete(c *gin.Context) {
id := c.Param("id")
if err := h.db.Delete(&ezops.CustomDashboard{}, id).Error; err != nil {
c.JSON(http.StatusInternalServerError, ezops.Response{Code: 500, Message: "删除失败: " + err.Error()})
return
}
c.JSON(http.StatusOK, ezops.Response{Code: 200, Message: "删除成功", Data: gin.H{"success": true}})
}
// SetDefault 设为默认仪表盘
// POST /api/v1/custom-dashboards/:id/default
func (h *CustomDashboardHandler) SetDefault(c *gin.Context) {
id := c.Param("id")
var d ezops.CustomDashboard
if err := h.db.First(&d, id).Error; err != nil {
c.JSON(http.StatusNotFound, ezops.Response{Code: 404, Message: "仪表盘不存在"})
return
}
// 清除其他默认
h.db.Model(&ezops.CustomDashboard{}).Where("is_default = ? AND id != ?", true, d.ID).Update("is_default", false)
// 设置当前为默认
h.db.Model(&d).Update("is_default", true)
c.JSON(http.StatusOK, ezops.Response{Code: 200, Message: "设置成功", Data: gin.H{"success": true}})
}
+1 -1
View File
@@ -359,7 +359,7 @@ func (h *DashboardHandler) GetRecentReleases(c *gin.Context) {
// @Success 200 {object} model.Response{data=[]model.MetricData}
// @Router /dashboard/metrics [get]
func (h *DashboardHandler) GetMetrics(c *gin.Context) {
hours := 6 // 默认6小时,减少扫描行数
hours := 6 // 默认6小时,减少扫描行数
if hv := c.Query("hours"); hv != "" {
if parsed, err := strconv.Atoi(hv); err == nil && parsed > 0 && parsed <= 168 {
hours = parsed
-164
View File
@@ -1,164 +0,0 @@
package controller
import (
"net/http"
"ezops/model"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// DeployHandler 发布系统处理器
type DeployHandler struct {
db *gorm.DB
}
func NewDeployHandler(db *gorm.DB) *DeployHandler {
return &DeployHandler{db: db}
}
// ==================== Git 仓库认证 ====================
func (h *DeployHandler) ListRepos(c *gin.Context) {
var items []model.PipelineRepo
h.db.Order("updated_at DESC").Find(&items)
c.JSON(http.StatusOK, model.Response{Code: 200, Data: model.ListResponse{List: items, Total: int64(len(items))}})
}
func (h *DeployHandler) GetRepo(c *gin.Context) {
var item model.PipelineRepo
if err := h.db.First(&item, c.Param("id")); err.Error != nil {
c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "不存在"})
return
}
c.JSON(http.StatusOK, model.Response{Code: 200, Data: item})
}
func (h *DeployHandler) CreateRepo(c *gin.Context) {
var req struct {
Name string `json:"name" binding:"required"`
Description string `json:"description"`
URL string `json:"url" binding:"required"`
AuthType model.RepoAuthType `json:"auth_type"`
CredentialID *uint `json:"credential_id"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()})
return
}
if req.AuthType == "" { req.AuthType = model.RepoAuthToken }
item := model.PipelineRepo{
Name: req.Name, Description: req.Description, URL: req.URL,
AuthType: req.AuthType, CredentialID: req.CredentialID,
CreatedBy: c.GetString("username"),
}
h.db.Create(&item)
c.JSON(http.StatusOK, model.Response{Code: 200, Data: item})
}
func (h *DeployHandler) UpdateRepo(c *gin.Context) {
var item model.PipelineRepo
if err := h.db.First(&item, c.Param("id")); err.Error != nil {
c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "不存在"})
return
}
var req struct {
Name *string `json:"name"`
Description *string `json:"description"`
URL *string `json:"url"`
AuthType *model.RepoAuthType `json:"auth_type"`
CredentialID *uint `json:"credential_id"`
Enabled *bool `json:"enabled"`
}
c.ShouldBindJSON(&req)
updates := map[string]interface{}{}
if req.Name != nil { updates["name"] = *req.Name }
if req.Description != nil { updates["description"] = *req.Description }
if req.URL != nil { updates["url"] = *req.URL }
if req.AuthType != nil { updates["auth_type"] = *req.AuthType }
if req.Enabled != nil { updates["enabled"] = *req.Enabled }
if req.CredentialID != nil { updates["credential_id"] = req.CredentialID }
h.db.Model(&item).Updates(updates)
h.db.First(&item, item.ID)
c.JSON(http.StatusOK, model.Response{Code: 200, Data: item})
}
func (h *DeployHandler) DeleteRepo(c *gin.Context) {
h.db.Delete(&model.PipelineRepo{}, c.Param("id"))
c.JSON(http.StatusOK, model.Response{Code: 200, Message: "已删除"})
}
// ==================== 镜像仓库认证 ====================
func (h *DeployHandler) ListRegistries(c *gin.Context) {
var items []model.PipelineRegistry
h.db.Order("updated_at DESC").Find(&items)
c.JSON(http.StatusOK, model.Response{Code: 200, Data: model.ListResponse{List: items, Total: int64(len(items))}})
}
func (h *DeployHandler) GetRegistry(c *gin.Context) {
var item model.PipelineRegistry
if err := h.db.First(&item, c.Param("id")); err.Error != nil {
c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "不存在"})
return
}
c.JSON(http.StatusOK, model.Response{Code: 200, Data: item})
}
func (h *DeployHandler) CreateRegistry(c *gin.Context) {
var req struct {
Name string `json:"name" binding:"required"`
Description string `json:"description"`
RegistryURL string `json:"registry_url" binding:"required"`
Namespace string `json:"namespace"`
AuthType model.RegistryAuthType `json:"auth_type"`
CredentialID *uint `json:"credential_id"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()})
return
}
if req.AuthType == "" { req.AuthType = model.RegistryAuthPassword }
item := model.PipelineRegistry{
Name: req.Name, Description: req.Description, RegistryURL: req.RegistryURL,
Namespace: req.Namespace, AuthType: req.AuthType, CredentialID: req.CredentialID,
CreatedBy: c.GetString("username"),
}
h.db.Create(&item)
c.JSON(http.StatusOK, model.Response{Code: 200, Data: item})
}
func (h *DeployHandler) UpdateRegistry(c *gin.Context) {
var item model.PipelineRegistry
if err := h.db.First(&item, c.Param("id")); err.Error != nil {
c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "不存在"})
return
}
var req struct {
Name *string `json:"name"`
Description *string `json:"description"`
RegistryURL *string `json:"registry_url"`
Namespace *string `json:"namespace"`
AuthType *model.RegistryAuthType `json:"auth_type"`
CredentialID *uint `json:"credential_id"`
Enabled *bool `json:"enabled"`
}
c.ShouldBindJSON(&req)
updates := map[string]interface{}{}
if req.Name != nil { updates["name"] = *req.Name }
if req.Description != nil { updates["description"] = *req.Description }
if req.RegistryURL != nil { updates["registry_url"] = *req.RegistryURL }
if req.Namespace != nil { updates["namespace"] = *req.Namespace }
if req.AuthType != nil { updates["auth_type"] = *req.AuthType }
if req.Enabled != nil { updates["enabled"] = *req.Enabled }
if req.CredentialID != nil { updates["credential_id"] = req.CredentialID }
h.db.Model(&item).Updates(updates)
h.db.First(&item, item.ID)
c.JSON(http.StatusOK, model.Response{Code: 200, Data: item})
}
func (h *DeployHandler) DeleteRegistry(c *gin.Context) {
h.db.Delete(&model.PipelineRegistry{}, c.Param("id"))
c.JSON(http.StatusOK, model.Response{Code: 200, Message: "已删除"})
}
+34 -14
View File
@@ -35,7 +35,9 @@ func (h *PipelineHandler) CreateEnvironment(c *gin.Context) {
c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()})
return
}
if req.Color == "" { req.Color = typeDefaultColor(req.Type) }
if req.Color == "" {
req.Color = typeDefaultColor(req.Type)
}
item := model.DeployEnvironment{
Name: req.Name, DisplayName: req.DisplayName,
Type: model.EnvironmentType(req.Type), Color: req.Color,
@@ -67,13 +69,27 @@ func (h *PipelineHandler) UpdateEnvironment(c *gin.Context) {
}
c.ShouldBindJSON(&req)
updates := map[string]interface{}{}
if req.Name != nil { updates["name"] = *req.Name }
if req.DisplayName != nil { updates["display_name"] = *req.DisplayName }
if req.Type != nil { updates["type"] = *req.Type }
if req.Color != nil { updates["color"] = *req.Color }
if req.SortOrder != nil { updates["sort_order"] = *req.SortOrder }
if req.Description != nil { updates["description"] = *req.Description }
if req.Enabled != nil { updates["enabled"] = *req.Enabled }
if req.Name != nil {
updates["name"] = *req.Name
}
if req.DisplayName != nil {
updates["display_name"] = *req.DisplayName
}
if req.Type != nil {
updates["type"] = *req.Type
}
if req.Color != nil {
updates["color"] = *req.Color
}
if req.SortOrder != nil {
updates["sort_order"] = *req.SortOrder
}
if req.Description != nil {
updates["description"] = *req.Description
}
if req.Enabled != nil {
updates["enabled"] = *req.Enabled
}
h.db.Model(&item).Updates(updates)
h.db.First(&item, id)
c.JSON(http.StatusOK, model.Response{Code: 200, Data: item})
@@ -87,10 +103,14 @@ func (h *PipelineHandler) DeleteEnvironment(c *gin.Context) {
func typeDefaultColor(t string) string {
switch t {
case "production": return "#EF4444"
case "staging": return "#F59E0B"
case "testing": return "#10B981"
default: return "#3B82F6" // development
case "production":
return "#EF4444"
case "staging":
return "#F59E0B"
case "testing":
return "#10B981"
default:
return "#3B82F6" // development
}
}
@@ -212,8 +232,8 @@ func (h *PipelineHandler) GetRunLog(c *gin.Context) {
}
c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{
"run": run,
"logs": logs,
"run": run,
"logs": logs,
}})
}
+6 -2
View File
@@ -53,8 +53,12 @@ func (h *PipelineHandler) UpdateGroup(c *gin.Context) {
}
c.ShouldBindJSON(&req)
updates := map[string]interface{}{}
if req.Name != nil { updates["name"] = *req.Name }
if req.Description != nil { updates["description"] = *req.Description }
if req.Name != nil {
updates["name"] = *req.Name
}
if req.Description != nil {
updates["description"] = *req.Description
}
h.db.Model(&group).Updates(updates)
h.db.First(&group, id)
c.JSON(http.StatusOK, model.Response{Code: 200, Data: group})
+20 -20
View File
@@ -216,28 +216,28 @@ func (h *KubernetesHandler) GetClusterDetail(c *gin.Context) {
Code: 200,
Message: "success",
Data: map[string]interface{}{
"id": cluster.ID,
"name": cluster.Name,
"code": cluster.Code,
"version": cluster.Version,
"status": cluster.Status,
"config_type": cluster.ConfigType,
"api_server": cluster.APIServer,
"api_endpoint": cluster.APIEndpoint,
"description": cluster.Description,
"has_token": cluster.Token != "",
"has_kube_config": cluster.KubeConfig != "",
"id": cluster.ID,
"name": cluster.Name,
"code": cluster.Code,
"version": cluster.Version,
"status": cluster.Status,
"config_type": cluster.ConfigType,
"api_server": cluster.APIServer,
"api_endpoint": cluster.APIEndpoint,
"description": cluster.Description,
"has_token": cluster.Token != "",
"has_kube_config": cluster.KubeConfig != "",
"node_count": cluster.NodeCount,
"pod_count": cluster.PodCount,
"service_count": cluster.ServiceCount,
"deployment_count": cluster.DeploymentCount,
"ingress_count": cluster.IngressCount,
"cpu_usage": cluster.CPUUsage,
"memory_usage": cluster.MemoryUsage,
"labels": cluster.Labels,
"last_sync_at": cluster.LastSyncAt,
"created_at": cluster.CreatedAt,
"updated_at": cluster.UpdatedAt,
"cpu_usage": cluster.CPUUsage,
"memory_usage": cluster.MemoryUsage,
"labels": cluster.Labels,
"last_sync_at": cluster.LastSyncAt,
"created_at": cluster.CreatedAt,
"updated_at": cluster.UpdatedAt,
},
})
}
@@ -320,7 +320,7 @@ func (h *KubernetesHandler) SyncCluster(c *gin.Context) {
// Sync nodes
if nodes, err := client.ListNodes(); err == nil {
// Use raw SQL for reliability (avoid GORM soft-delete / auto-timestamp issues)
h.db.Exec("DELETE FROM kubernetes_nodes WHERE cluster_id = ?", cluster.ID)
h.db.Exec("DELETE FROM k8s_nodes WHERE cluster_id = ?", cluster.ID)
for _, n := range nodes.Items {
role := "worker"
if _, ok := n.Metadata.Labels["node-role.kubernetes.io/master"]; ok {
@@ -358,7 +358,7 @@ func (h *KubernetesHandler) SyncCluster(c *gin.Context) {
memUsagePct = float64(memMi) / float64(memMB) * 100
}
}
err2 := h.db.Exec(`INSERT INTO kubernetes_nodes (cluster_id, name, ip, role, status, os, kubelet_version, cpu, memory, max_pods, cpu_usage, memory_usage, labels, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
err2 := h.db.Exec(`INSERT INTO k8s_nodes (cluster_id, name, ip, role, status, os, kubelet_version, cpu, memory, max_pods, cpu_usage, memory_usage, labels, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
cluster.ID, n.Metadata.Name, ip, role, nodeStatus, n.Status.NodeInfo.OSImage, n.Status.NodeInfo.KubeletVersion,
parseIntResource(n.Status.Capacity["cpu"]), parseMemResource(n.Status.Capacity["memory"]), parseIntResource(n.Status.Capacity["pods"]),
cpuUsagePct, memUsagePct, string(labelsJSON), now, now).Error
@@ -508,7 +508,7 @@ func (h *KubernetesHandler) SyncCluster(c *gin.Context) {
c.JSON(http.StatusOK, model.Response{
Code: 200,
Message: msg,
Data: result,
Data: result,
})
}
+30 -22
View File
@@ -14,27 +14,27 @@ func (h *KubernetesHandler) GetMultiClusterComparison(c *gin.Context) {
h.db.Find(&clusters)
type ClusterComparison struct {
ID uint `json:"id"`
Name string `json:"name"`
Code string `json:"code"`
Status string `json:"status"`
Version string `json:"version"`
NodeCount int `json:"node_count"`
PodCount int `json:"pod_count"`
DeploymentCount int `json:"deployment_count"`
ServiceCount int `json:"service_count"`
CPUUsage float64 `json:"cpu_usage"`
MemoryUsage float64 `json:"memory_usage"`
APIServer string `json:"api_server"`
LastSyncAt *time.Time `json:"last_sync_at"`
ID uint `json:"id"`
Name string `json:"name"`
Code string `json:"code"`
Status string `json:"status"`
Version string `json:"version"`
NodeCount int `json:"node_count"`
PodCount int `json:"pod_count"`
DeploymentCount int `json:"deployment_count"`
ServiceCount int `json:"service_count"`
CPUUsage float64 `json:"cpu_usage"`
MemoryUsage float64 `json:"memory_usage"`
APIServer string `json:"api_server"`
LastSyncAt *time.Time `json:"last_sync_at"`
// Node-level aggregated data from kubernetes_nodes table
TotalCPUCores int `json:"total_cpu_cores"`
TotalMemoryMB int64 `json:"total_memory_mb"`
MasterCount int `json:"master_count"`
WorkerCount int `json:"worker_count"`
HealthyNodes int `json:"healthy_nodes"`
UnhealthyNodes int `json:"unhealthy_nodes"`
// Node-level aggregated data from k8s_nodes table
TotalCPUCores int `json:"total_cpu_cores"`
TotalMemoryMB int64 `json:"total_memory_mb"`
MasterCount int `json:"master_count"`
WorkerCount int `json:"worker_count"`
HealthyNodes int `json:"healthy_nodes"`
UnhealthyNodes int `json:"unhealthy_nodes"`
}
// 2. 获取所有节点的聚合数据(按 cluster_id 分组)
@@ -64,8 +64,16 @@ func (h *KubernetesHandler) GetMultiClusterComparison(c *gin.Context) {
agg.TotalCPU += n.CPU
agg.TotalMemory += n.Memory
if n.CPUUsage > 0 || n.MemoryUsage > 0 {
if agg.AvgCPUUsage == 0 { agg.AvgCPUUsage = n.CPUUsage } else { agg.AvgCPUUsage = (agg.AvgCPUUsage*float64(agg.NodeCount-1) + n.CPUUsage) / float64(agg.NodeCount) }
if agg.AvgMemUsage == 0 { agg.AvgMemUsage = n.MemoryUsage } else { agg.AvgMemUsage = (agg.AvgMemUsage*float64(agg.NodeCount-1) + n.MemoryUsage) / float64(agg.NodeCount) }
if agg.AvgCPUUsage == 0 {
agg.AvgCPUUsage = n.CPUUsage
} else {
agg.AvgCPUUsage = (agg.AvgCPUUsage*float64(agg.NodeCount-1) + n.CPUUsage) / float64(agg.NodeCount)
}
if agg.AvgMemUsage == 0 {
agg.AvgMemUsage = n.MemoryUsage
} else {
agg.AvgMemUsage = (agg.AvgMemUsage*float64(agg.NodeCount-1) + n.MemoryUsage) / float64(agg.NodeCount)
}
}
if n.Role == "master" {
agg.MasterCount++
+15 -4
View File
@@ -14,14 +14,23 @@ import (
func (h *KubernetesHandler) ListEvents(c *gin.Context) {
clusterID := h.resolveClusterCode(c.Param("clusterCode"))
if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return }
if clusterID == 0 {
c.JSON(500, model.Response{Code: 500, Message: "cluster not found"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
ns := c.Query("namespace")
eventType := c.Query("type") // Normal or Warning
events, err := client.ListEvents(ns)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()})
return
}
type EventSummary struct {
Namespace string `json:"namespace"`
@@ -40,7 +49,9 @@ func (h *KubernetesHandler) ListEvents(c *gin.Context) {
}
result := []EventSummary{}
for _, e := range events.Items {
if eventType != "" && e.Type != eventType { continue }
if eventType != "" && e.Type != eventType {
continue
}
objectKind := e.InvolvedObject.Kind
objectName := e.InvolvedObject.Name
object := fmt.Sprintf("%s/%s", objectKind, objectName)
+154 -49
View File
@@ -246,30 +246,45 @@ func (h *KubernetesHandler) DeleteCronJobNS(c *gin.Context) {
}
func (h *KubernetesHandler) listHPAsWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
hpas, err := client.ListHPAs()
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()})
return
}
type HPASummary struct {
Namespace string `json:"namespace"`
Name string `json:"name"`
TargetKind string `json:"target_kind"`
TargetName string `json:"target_name"`
MinReplicas int `json:"min_replicas"`
MaxReplicas int `json:"max_replicas"`
CPUPercent int `json:"cpu_percent"`
MemPercent int `json:"mem_percent"`
Namespace string `json:"namespace"`
Name string `json:"name"`
TargetKind string `json:"target_kind"`
TargetName string `json:"target_name"`
MinReplicas int `json:"min_replicas"`
MaxReplicas int `json:"max_replicas"`
CPUPercent int `json:"cpu_percent"`
MemPercent int `json:"mem_percent"`
CurrentReplicas int `json:"current_replicas"`
}
result := []HPASummary{}
for _, h := range hpas.Items {
if h.Metadata.Namespace != ns { continue }
cpu := 0; mem := 0
if h.Metadata.Namespace != ns {
continue
}
cpu := 0
mem := 0
for _, m := range h.Spec.Metrics {
if m.Resource != nil {
if m.Resource.Name == "cpu" { cpu = m.Resource.Target.AverageUtilization }
if m.Resource.Name == "memory" { mem = m.Resource.Target.AverageUtilization }
if m.Resource.Name == "cpu" {
cpu = m.Resource.Target.AverageUtilization
}
if m.Resource.Name == "memory" {
mem = m.Resource.Target.AverageUtilization
}
}
}
result = append(result, HPASummary{
@@ -288,80 +303,165 @@ func (h *KubernetesHandler) listHPAsWithNS(c *gin.Context, ns string) {
}
func (h *KubernetesHandler) createHPAWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
var req k8sclient.CreateHPARequest
if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, model.Response{Code: 400, Message: "参数错误"}); return }
if req.Namespace == "" { req.Namespace = ns }
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, model.Response{Code: 400, Message: "参数错误"})
return
}
if req.Namespace == "" {
req.Namespace = ns
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
hpa, err := client.CreateHPA(req)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "创建失败: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "创建失败: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Data: hpa})
}
func (h *KubernetesHandler) deleteHPAWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err := client.DeleteHPA(ns, c.Param("name")); err != nil { c.JSON(500, model.Response{Code: 500, Message: "删除失败: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
if err := client.DeleteHPA(ns, c.Param("name")); err != nil {
c.JSON(500, model.Response{Code: 500, Message: "删除失败: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Message: "已删除"})
}
func (h *KubernetesHandler) listCronJobsWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
cjs, err := client.ListCronJobs()
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()})
return
}
filtered := []k8sclient.CronJobItem{}
for _, cj := range cjs.Items { if cj.Metadata.Namespace == ns { filtered = append(filtered, cj) } }
for _, cj := range cjs.Items {
if cj.Metadata.Namespace == ns {
filtered = append(filtered, cj)
}
}
c.JSON(200, model.Response{Code: 200, Data: filtered})
}
func (h *KubernetesHandler) createCronJobWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
var req k8sclient.CreateCronJobRequest
if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, model.Response{Code: 400, Message: "参数错误"}); return }
if req.Namespace == "" { req.Namespace = ns }
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, model.Response{Code: 400, Message: "参数错误"})
return
}
if req.Namespace == "" {
req.Namespace = ns
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
cj, err := client.CreateCronJob(req)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "创建失败: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "创建失败: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Data: cj})
}
func (h *KubernetesHandler) suspendCronJobWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
var req struct { Suspend bool `json:"suspend"` }; c.ShouldBindJSON(&req)
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
var req struct {
Suspend bool `json:"suspend"`
}
c.ShouldBindJSON(&req)
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err := client.SuspendCronJob(ns, c.Param("name"), req.Suspend); err != nil { c.JSON(500, model.Response{Code: 500, Message: "操作失败: " + err.Error()}); return }
action := "恢复"; if req.Suspend { action = "暂停" }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
if err := client.SuspendCronJob(ns, c.Param("name"), req.Suspend); err != nil {
c.JSON(500, model.Response{Code: 500, Message: "操作失败: " + err.Error()})
return
}
action := "恢复"
if req.Suspend {
action = "暂停"
}
c.JSON(200, model.Response{Code: 200, Message: "CronJob 已" + action})
}
func (h *KubernetesHandler) triggerCronJobWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err := client.TriggerCronJob(ns, c.Param("name")); err != nil { c.JSON(500, model.Response{Code: 500, Message: "触发失败: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
if err := client.TriggerCronJob(ns, c.Param("name")); err != nil {
c.JSON(500, model.Response{Code: 500, Message: "触发失败: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Message: "手动触发成功"})
}
func (h *KubernetesHandler) deleteCronJobWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err := client.DeleteCronJob(ns, c.Param("name")); err != nil { c.JSON(500, model.Response{Code: 500, Message: "删除失败: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
if err := client.DeleteCronJob(ns, c.Param("name")); err != nil {
c.JSON(500, model.Response{Code: 500, Message: "删除失败: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Message: "已删除"})
}
func (h *KubernetesHandler) ListHPAsAllNS(c *gin.Context) {
clusterID := h.resolveClusterCode(c.Param("clusterCode"))
if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return }
if clusterID == 0 {
c.JSON(500, model.Response{Code: 500, Message: "cluster not found"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
hpas, err := client.ListHPAs()
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()})
return
}
type HPASummary struct {
Namespace string `json:"namespace"`
Name string `json:"name"`
@@ -375,11 +475,16 @@ func (h *KubernetesHandler) ListHPAsAllNS(c *gin.Context) {
}
result := []HPASummary{}
for _, h := range hpas.Items {
cpu := 0; mem := 0
cpu := 0
mem := 0
for _, m := range h.Spec.Metrics {
if m.Resource != nil {
if m.Resource.Name == "cpu" { cpu = m.Resource.Target.AverageUtilization }
if m.Resource.Name == "memory" { mem = m.Resource.Target.AverageUtilization }
if m.Resource.Name == "cpu" {
cpu = m.Resource.Target.AverageUtilization
}
if m.Resource.Name == "memory" {
mem = m.Resource.Target.AverageUtilization
}
}
}
result = append(result, HPASummary{
+24 -18
View File
@@ -38,16 +38,16 @@ func (h *KubernetesHandler) ListNamespaces(c *gin.Context) {
// NamespaceDetail is the enriched namespace info for the management page
type NamespaceDetail struct {
Name string `json:"name"`
Status string `json:"status"`
Age string `json:"age"`
Labels map[string]string `json:"labels"`
Annotations map[string]string `json:"annotations,omitempty"`
ResourceCounts map[string]int `json:"resource_counts"`
HasResourceQuota bool `json:"has_resource_quota"`
HasLimitRange bool `json:"has_limit_range"`
ResourceQuotas []k8sclient.ResourceQuotaItem `json:"resource_quotas,omitempty"`
LimitRanges []k8sclient.LimitRangeItem `json:"limit_ranges,omitempty"`
Name string `json:"name"`
Status string `json:"status"`
Age string `json:"age"`
Labels map[string]string `json:"labels"`
Annotations map[string]string `json:"annotations,omitempty"`
ResourceCounts map[string]int `json:"resource_counts"`
HasResourceQuota bool `json:"has_resource_quota"`
HasLimitRange bool `json:"has_limit_range"`
ResourceQuotas []k8sclient.ResourceQuotaItem `json:"resource_quotas,omitempty"`
LimitRanges []k8sclient.LimitRangeItem `json:"limit_ranges,omitempty"`
}
// GetNamespacesDetail returns all namespaces with metadata, resource counts and quota info
@@ -110,11 +110,11 @@ func (h *KubernetesHandler) GetNamespacesDetail(c *gin.Context) {
for _, ns := range nsList.Items {
name := ns.Metadata.Name
nd := NamespaceDetail{
Name: name,
Status: ns.Status.Phase,
Age: formatAge(ns.Metadata.CreationTimestamp),
Labels: ns.Metadata.Labels,
Annotations: ns.Metadata.Annotations,
Name: name,
Status: ns.Status.Phase,
Age: formatAge(ns.Metadata.CreationTimestamp),
Labels: ns.Metadata.Labels,
Annotations: ns.Metadata.Annotations,
ResourceCounts: map[string]int{
"deployments": depCounts[name],
"pods": podCounts[name],
@@ -181,21 +181,27 @@ func (h *KubernetesHandler) GetNamespaceDetailHandler(c *gin.Context) {
if deps, err := client.ListDeployments(); err == nil {
count := 0
for _, d := range deps.Items {
if d.Metadata.Namespace == nsName { count++ }
if d.Metadata.Namespace == nsName {
count++
}
}
nd.ResourceCounts["deployments"] = count
}
if pods, err := client.ListPods(); err == nil {
count := 0
for _, p := range pods.Items {
if p.Metadata.Namespace == nsName { count++ }
if p.Metadata.Namespace == nsName {
count++
}
}
nd.ResourceCounts["pods"] = count
}
if svcs, err := client.ListServices(); err == nil {
count := 0
for _, s := range svcs.Items {
if s.Metadata.Namespace == nsName { count++ }
if s.Metadata.Namespace == nsName {
count++
}
}
nd.ResourceCounts["services"] = count
}
+44 -33
View File
@@ -305,20 +305,20 @@ func (h *KubernetesHandler) GetNodeDetail(c *gin.Context) {
}
detail := map[string]interface{}{
"name": node.Metadata.Name,
"role": role,
"status": nodeStatus,
"creation_time": node.Metadata.CreationTimestamp,
"internal_ip": internalIP,
"external_ip": externalIP,
"hostname": hostname,
"pod_cidr": node.Spec.PodCIDR,
"name": node.Metadata.Name,
"role": role,
"status": nodeStatus,
"creation_time": node.Metadata.CreationTimestamp,
"internal_ip": internalIP,
"external_ip": externalIP,
"hostname": hostname,
"pod_cidr": node.Spec.PodCIDR,
"container_runtime": node.Status.NodeInfo.ContainerRuntimeVersion,
"kubelet_version": node.Status.NodeInfo.KubeletVersion,
"os_image": node.Status.NodeInfo.OSImage,
"kernel_version": node.Status.NodeInfo.KernelVersion,
"architecture": node.Status.NodeInfo.Architecture,
"operating_system": node.Status.NodeInfo.OperatingSystem,
"kubelet_version": node.Status.NodeInfo.KubeletVersion,
"os_image": node.Status.NodeInfo.OSImage,
"kernel_version": node.Status.NodeInfo.KernelVersion,
"architecture": node.Status.NodeInfo.Architecture,
"operating_system": node.Status.NodeInfo.OperatingSystem,
// Capacity & Allocatable
"capacity": node.Status.Capacity,
"allocatable": node.Status.Allocatable,
@@ -326,18 +326,18 @@ func (h *KubernetesHandler) GetNodeDetail(c *gin.Context) {
"cpu_usage_m": cpuUsageM,
"mem_usage_mi": memUsageMi,
// Allocation
"pod_count": podCount,
"cpu_request_m": totalCPURequestM,
"mem_request_mi": totalMemRequestMi,
"cpu_alloc_pct": cpuAllocPct,
"mem_alloc_pct": memAllocPct,
"pod_alloc_pct": podAllocPct,
"cpu_capacity": capCPU,
"cpu_allocatable": allocCPU,
"mem_capacity_mb": capMem,
"pod_count": podCount,
"cpu_request_m": totalCPURequestM,
"mem_request_mi": totalMemRequestMi,
"cpu_alloc_pct": cpuAllocPct,
"mem_alloc_pct": memAllocPct,
"pod_alloc_pct": podAllocPct,
"cpu_capacity": capCPU,
"cpu_allocatable": allocCPU,
"mem_capacity_mb": capMem,
"mem_allocatable_mb": allocMem,
"pod_capacity": capPods,
"pod_allocatable": allocPods,
"pod_capacity": capPods,
"pod_allocatable": allocPods,
// Lists
"conditions": conditions,
"taints": taints,
@@ -397,20 +397,29 @@ func parseMemToMi(val string) int64 {
// @Router /kubernetes-clusters/{id}/pods [get]
func (h *KubernetesHandler) GetCapacityAnalysis(c *gin.Context) {
clusterID := h.resolveClusterCode(c.Param("clusterCode"))
if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return }
if clusterID == 0 {
c.JSON(500, model.Response{Code: 500, Message: "cluster not found"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
ns := c.Query("namespace")
deps, err := client.ListDeployments()
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()})
return
}
type ContainerResource struct {
Name string `json:"name"`
CPUReq string `json:"cpu_request"`
CPULim string `json:"cpu_limit"`
MemReq string `json:"mem_request"`
MemLim string `json:"mem_limit"`
Name string `json:"name"`
CPUReq string `json:"cpu_request"`
CPULim string `json:"cpu_limit"`
MemReq string `json:"mem_request"`
MemLim string `json:"mem_limit"`
}
type CapacityRow struct {
Namespace string `json:"namespace"`
@@ -420,7 +429,9 @@ func (h *KubernetesHandler) GetCapacityAnalysis(c *gin.Context) {
}
result := []CapacityRow{}
for _, d := range deps.Items {
if ns != "" && d.Metadata.Namespace != ns { continue }
if ns != "" && d.Metadata.Namespace != ns {
continue
}
containers := []ContainerResource{}
for _, c := range d.Spec.Template.Spec.Containers {
cpuReq := c.Resources.Requests["cpu"]
+139 -48
View File
@@ -198,8 +198,8 @@ func (h *KubernetesHandler) ExecTerminal(c *gin.Context) {
// Dial K8s API server via WebSocket with channel protocol subprotocol
k8sDialer := &websocket.Dialer{
TLSClientConfig: client.TLSConfig,
Subprotocols: []string{"v4.channel.k8s.io", "v3.channel.k8s.io", "v5.channel.k8s.io"},
TLSClientConfig: client.TLSConfig,
Subprotocols: []string{"v4.channel.k8s.io", "v3.channel.k8s.io", "v5.channel.k8s.io"},
HandshakeTimeout: 10 * time.Second,
}
k8sHeader := http.Header{}
@@ -354,30 +354,46 @@ func (h *KubernetesHandler) ExecInPodNS(c *gin.Context) {
// Internal helpers that resolve clusterCode and inject namespace
func (h *KubernetesHandler) listPodsWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
pods, err := client.ListPods()
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()})
return
}
// M2: inject pod metrics (best-effort) // Logan.Li
podMetrics := buildPodMetricsMap(client, ns)
type PodSummary struct {
Namespace string `json:"namespace"`
Name string `json:"name"`
Status string `json:"status"`
NodeName string `json:"node_name"`
IP string `json:"ip"`
RestartCount int `json:"restart_count"`
Image string `json:"image"`
CPUUsageM string `json:"cpu_usage_m,omitempty"`
MemUsageMi string `json:"mem_usage_mi,omitempty"`
Namespace string `json:"namespace"`
Name string `json:"name"`
Status string `json:"status"`
NodeName string `json:"node_name"`
IP string `json:"ip"`
RestartCount int `json:"restart_count"`
Image string `json:"image"`
CPUUsageM string `json:"cpu_usage_m,omitempty"`
MemUsageMi string `json:"mem_usage_mi,omitempty"`
Conditions []k8sclient.PodCondition `json:"conditions,omitempty"`
}
result := []PodSummary{}
for _, p := range pods.Items {
if p.Metadata.Namespace != ns { continue }
image := ""; if len(p.Spec.Containers) > 0 { image = p.Spec.Containers[0].Image }
restarts := 0; if len(p.Status.ContainerStatuses) > 0 { restarts = p.Status.ContainerStatuses[0].RestartCount }
if p.Metadata.Namespace != ns {
continue
}
image := ""
if len(p.Spec.Containers) > 0 {
image = p.Spec.Containers[0].Image
}
restarts := 0
if len(p.Status.ContainerStatuses) > 0 {
restarts = p.Status.ContainerStatuses[0].RestartCount
}
ps := PodSummary{
Namespace: p.Metadata.Namespace,
Name: p.Metadata.Name,
@@ -398,7 +414,9 @@ func (h *KubernetesHandler) listPodsWithNS(c *gin.Context, ns string) {
}
func (h *KubernetesHandler) getPodLogsWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
podName := c.Param("podName")
stream := c.Query("stream") == "true"
// 日志增强参数:container / sinceTime / previous / tailLines(兼容 tail) // Logan.Li
@@ -416,34 +434,61 @@ func (h *KubernetesHandler) getPodLogsWithNS(c *gin.Context, ns string) {
Previous: c.Query("previous") == "true",
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
if stream {
body, err := client.GetPodLogsStreamWithOptions(ns, podName, opts)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "获取日志流失败: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "获取日志流失败: " + err.Error()})
return
}
defer body.Close()
c.Header("Content-Type", "text/plain; charset=utf-8")
c.Header("Cache-Control", "no-cache")
c.Stream(func(w io.Writer) bool {
buf := make([]byte, 4096); n, err := body.Read(buf)
if n > 0 { w.Write(buf[:n]); return true }
buf := make([]byte, 4096)
n, err := body.Read(buf)
if n > 0 {
w.Write(buf[:n])
return true
}
return err == nil
})
return
}
logs, err := client.GetPodLogsWithOptions(ns, podName, opts)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "获取日志失败: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "获取日志失败: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Message: "success", Data: gin.H{"logs": logs, "pod": podName, "namespace": ns}})
}
func (h *KubernetesHandler) execInPodWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
podName := c.Param("podName")
var req struct { Command []string `json:"command"`; Container string `json:"container"` }
if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, model.Response{Code: 400, Message: "参数错误"}); return }
var req struct {
Command []string `json:"command"`
Container string `json:"container"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, model.Response{Code: 400, Message: "参数错误"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
result, err := client.ExecInPod(ns, podName, req.Container, req.Command)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "执行失败: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "执行失败: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Data: result})
}
@@ -454,11 +499,20 @@ func (h *KubernetesHandler) execInPodWithNS(c *gin.Context, ns string) {
// ListDeploymentsAllNS lists all deployments across all namespaces using clusterCode.
func (h *KubernetesHandler) ListPodsAllNS(c *gin.Context) {
clusterID := h.resolveClusterCode(c.Param("clusterCode"))
if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return }
if clusterID == 0 {
c.JSON(500, model.Response{Code: 500, Message: "cluster not found"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
pods, err := client.ListPods()
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()})
return
}
// M2: inject pod metrics (best-effort) // Logan.Li
podMetrics := buildPodMetricsMap(client, "")
type PodSummary struct {
@@ -474,8 +528,14 @@ func (h *KubernetesHandler) ListPodsAllNS(c *gin.Context) {
}
result := []PodSummary{}
for _, p := range pods.Items {
image := ""; if len(p.Spec.Containers) > 0 { image = p.Spec.Containers[0].Image }
restarts := 0; if len(p.Status.ContainerStatuses) > 0 { restarts = p.Status.ContainerStatuses[0].RestartCount }
image := ""
if len(p.Spec.Containers) > 0 {
image = p.Spec.Containers[0].Image
}
restarts := 0
if len(p.Status.ContainerStatuses) > 0 {
restarts = p.Status.ContainerStatuses[0].RestartCount
}
ps := PodSummary{
Namespace: p.Metadata.Namespace,
Name: p.Metadata.Name,
@@ -559,58 +619,80 @@ func parseMemResource(val string) int64 {
// formatCpuFromNano converts K8s metrics CPU (nanocores "80410173n") to millicores "80m"
func formatCpuFromNano(raw string) string {
if raw == "" { return "" }
if raw == "" {
return ""
}
val := raw
val = strings.TrimSuffix(val, "n")
var nano int64
fmt.Sscanf(val, "%d", &nano)
milli := nano / 1000000
if milli < 1 { milli = 1 }
if milli < 1 {
milli = 1
}
return fmt.Sprintf("%dm", milli)
}
// parseCpuNanoToMilli converts K8s metrics CPU (nanocores "100354992n") to millicores (int) // Logan.Li
func parseCpuNanoToMilli(raw string) int {
if raw == "" { return 0 }
if raw == "" {
return 0
}
val := strings.TrimSuffix(raw, "n")
var nano int64
fmt.Sscanf(val, "%d", &nano)
milli := nano / 1000000
if milli < 1 { milli = 1 }
if milli < 1 {
milli = 1
}
return int(milli)
}
// formatMemFromKi converts K8s metrics memory (Ki "2154292Ki") to Mi "2105Mi"
func formatMemFromKi(raw string) string {
if raw == "" { return "" }
if raw == "" {
return ""
}
val := strings.TrimSuffix(raw, "Ki")
var ki int64
fmt.Sscanf(val, "%d", &ki)
mi := ki / 1024
if mi < 1 { mi = 1 }
if mi < 1 {
mi = 1
}
return fmt.Sprintf("%dMi", mi)
}
// parseMemKiToMi converts K8s metrics memory (Ki "2154292Ki") to Mi (int) // Logan.Li
func parseMemKiToMi(raw string) int {
if raw == "" { return 0 }
if raw == "" {
return 0
}
val := strings.TrimSuffix(raw, "Ki")
var ki int64
fmt.Sscanf(val, "%d", &ki)
return int(ki / 1024)
}
// GetResourceYAMLNS returns the YAML of a K8s resource
func (h *KubernetesHandler) GetPodMetrics(c *gin.Context) {
clusterID := h.resolveClusterCode(c.Param("clusterCode"))
if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return }
if clusterID == 0 {
c.JSON(500, model.Response{Code: 500, Message: "cluster not found"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
ns := c.Query("namespace")
metrics, err := client.ListPodMetrics(ns)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "metrics API error: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "metrics API error: " + err.Error()})
return
}
type ContainerMetric struct {
Name string `json:"name"`
@@ -643,13 +725,22 @@ func (h *KubernetesHandler) DeletePodNS(c *gin.Context) {
}
func (h *KubernetesHandler) deletePodWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
podName := c.Param("podName")
if podName == "" { c.JSON(400, model.Response{Code: 400, Message: "缺少 podName"}); return }
if podName == "" {
c.JSON(400, model.Response{Code: 400, Message: "缺少 podName"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
if err := client.DeletePod(ns, podName); err != nil {
c.JSON(500, model.Response{Code: 500, Message: "删除 Pod 失败: " + err.Error()}); return
c.JSON(500, model.Response{Code: 500, Message: "删除 Pod 失败: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Message: fmt.Sprintf("Pod %s 已删除", podName)})
}
+45 -13
View File
@@ -19,20 +19,33 @@ func (h *KubernetesHandler) ListPodFilesNS(c *gin.Context) {
}
func (h *KubernetesHandler) listPodFilesWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
podName := c.Param("podName")
var req struct {
Path string `json:"path"`
Container string `json:"container"`
}
if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, model.Response{Code: 400, Message: "参数错误: " + err.Error()}); return }
if req.Path == "" { req.Path = "/" }
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, model.Response{Code: 400, Message: "参数错误: " + err.Error()})
return
}
if req.Path == "" {
req.Path = "/"
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
// ls -la — BusyBox ignores --time-style, use default "Mon DD HH:MM" format
cmd := []string{"ls", "-la", req.Path}
result, err := client.ExecInPod(ns, podName, req.Container, cmd)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "执行 ls 失败: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "执行 ls 失败: " + err.Error()})
return
}
type FileInfo struct {
Name string `json:"name"`
@@ -45,11 +58,17 @@ func (h *KubernetesHandler) listPodFilesWithNS(c *gin.Context, ns string) {
output := result.Stdout // WebSocket output is already clean text
for _, line := range strings.Split(output, "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "total ") { continue }
if line == "" || strings.HasPrefix(line, "total ") {
continue
}
fields := strings.Fields(line)
if len(fields) < 7 { continue }
if len(fields) < 7 {
continue
}
mode := fields[0]
if len(mode) == 0 || (mode[0] != 'd' && mode[0] != '-' && mode[0] != 'l') { continue }
if len(mode) == 0 || (mode[0] != 'd' && mode[0] != '-' && mode[0] != 'l') {
continue
}
size := fields[4]
// BusyBox ls date format: "Jun 23 02:17" (3 fields: month day time)
// GNU ls --time-style: "2026-06-23T02:17:00" (1 field)
@@ -64,7 +83,9 @@ func (h *KubernetesHandler) listPodFilesWithNS(c *gin.Context, ns string) {
modTime = strings.Join(fields[5:8], " ")
name = strings.Join(fields[8:], " ")
}
if name == "" || name == "." || name == ".." { continue }
if name == "" || name == "." || name == ".." {
continue
}
files = append(files, FileInfo{
Name: name,
Size: size,
@@ -82,16 +103,27 @@ func (h *KubernetesHandler) DownloadPodFileNS(c *gin.Context) {
}
func (h *KubernetesHandler) downloadPodFileWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
podName := c.Param("podName")
filePath := c.Query("path")
container := c.Query("container")
if filePath == "" { c.JSON(400, model.Response{Code: 400, Message: "path 参数不能为空"}); return }
if filePath == "" {
c.JSON(400, model.Response{Code: 400, Message: "path 参数不能为空"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
cmd := []string{"cat", filePath}
result, err := client.ExecInPod(ns, podName, container, cmd)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "读取文件失败: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "读取文件失败: " + err.Error()})
return
}
content := result.Stdout
fileName := path.Base(filePath)
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", fileName))
+84 -45
View File
@@ -223,7 +223,6 @@ func (h *KubernetesHandler) SaveTopology(c *gin.Context) {
c.JSON(http.StatusOK, model.Response{Code: 200, Message: "保存成功"})
}
// SyncCluster 同步集群资源(连接真实K8s API拉取数据)
func (h *KubernetesHandler) ListConfigMaps(c *gin.Context) {
clusterID, _ := strconv.Atoi(c.Param("id"))
@@ -313,11 +312,19 @@ func (h *KubernetesHandler) ListIngressesNS(c *gin.Context) {
}
func (h *KubernetesHandler) listServicesWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
svcs, err := client.ListServices()
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()})
return
}
type SvcPortDetail struct {
Name string `json:"name,omitempty"`
Port int `json:"port"`
@@ -326,17 +333,19 @@ func (h *KubernetesHandler) listServicesWithNS(c *gin.Context, ns string) {
Protocol string `json:"protocol,omitempty"`
}
type SvcSummary struct {
Namespace string `json:"namespace"`
Name string `json:"name"`
Type string `json:"type"`
ClusterIP string `json:"cluster_ip"`
Ports int `json:"ports"`
PortList []SvcPortDetail `json:"portList,omitempty"`
Selector map[string]string `json:"selector,omitempty"`
Namespace string `json:"namespace"`
Name string `json:"name"`
Type string `json:"type"`
ClusterIP string `json:"cluster_ip"`
Ports int `json:"ports"`
PortList []SvcPortDetail `json:"portList,omitempty"`
Selector map[string]string `json:"selector,omitempty"`
}
result := []SvcSummary{}
for _, s := range svcs.Items {
if s.Metadata.Namespace != ns { continue }
if s.Metadata.Namespace != ns {
continue
}
ports := []SvcPortDetail{}
for _, p := range s.Spec.Ports {
ports = append(ports, SvcPortDetail{
@@ -345,28 +354,36 @@ func (h *KubernetesHandler) listServicesWithNS(c *gin.Context, ns string) {
})
}
result = append(result, SvcSummary{
Namespace: s.Metadata.Namespace,
Name: s.Metadata.Name,
Type: s.Spec.Type,
ClusterIP: s.Spec.ClusterIP,
Ports: len(s.Spec.Ports),
PortList: ports,
Selector: s.Spec.Selector,
Namespace: s.Metadata.Namespace,
Name: s.Metadata.Name,
Type: s.Spec.Type,
ClusterIP: s.Spec.ClusterIP,
Ports: len(s.Spec.Ports),
PortList: ports,
Selector: s.Spec.Selector,
})
}
c.JSON(200, model.Response{Code: 200, Data: result})
}
func (h *KubernetesHandler) listIngressesWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
ings, err := client.ListIngresses()
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()})
return
}
type PathDetail struct {
Path string `json:"path"`
PathType string `json:"pathType,omitempty"`
BackendSvc string `json:"backendService,omitempty"`
Path string `json:"path"`
PathType string `json:"pathType,omitempty"`
BackendSvc string `json:"backendService,omitempty"`
BackendPort string `json:"backendPort,omitempty"`
}
type RuleDetail struct {
@@ -374,20 +391,24 @@ func (h *KubernetesHandler) listIngressesWithNS(c *gin.Context, ns string) {
Paths []PathDetail `json:"paths"`
}
type IngSummary struct {
Namespace string `json:"namespace"`
Name string `json:"name"`
Hosts []string `json:"hosts"`
TLS bool `json:"tls"`
IngressClass string `json:"ingressClass,omitempty"`
Rules []RuleDetail `json:"rules,omitempty"`
Namespace string `json:"namespace"`
Name string `json:"name"`
Hosts []string `json:"hosts"`
TLS bool `json:"tls"`
IngressClass string `json:"ingressClass,omitempty"`
Rules []RuleDetail `json:"rules,omitempty"`
}
result := []IngSummary{}
for _, ing := range ings.Items {
if ing.Metadata.Namespace != ns { continue }
if ing.Metadata.Namespace != ns {
continue
}
hosts := []string{}
rules := []RuleDetail{}
for _, rule := range ing.Spec.Rules {
if rule.Host != "" { hosts = append(hosts, rule.Host) }
if rule.Host != "" {
hosts = append(hosts, rule.Host)
}
rd := RuleDetail{Host: rule.Host, Paths: []PathDetail{}}
if rule.HTTP != nil {
for _, p := range rule.HTTP.Paths {
@@ -453,12 +474,21 @@ func (h *KubernetesHandler) ListIngressClasses(c *gin.Context) {
func (h *KubernetesHandler) ListPVCsNS(c *gin.Context) {
clusterID := h.resolveClusterCode(c.Param("clusterCode"))
if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return }
if clusterID == 0 {
c.JSON(500, model.Response{Code: 500, Message: "cluster not found"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
ns := c.Param("namespace")
pvcs, err := client.ListPVCs(ns)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()})
return
}
type PVCSummary struct {
Namespace string `json:"namespace"`
Name string `json:"name"`
@@ -470,14 +500,16 @@ func (h *KubernetesHandler) ListPVCsNS(c *gin.Context) {
for _, p := range pvcs.Items {
size := ""
if p.Status.Capacity != nil {
if s, ok := p.Status.Capacity["storage"]; ok { size = s }
if s, ok := p.Status.Capacity["storage"]; ok {
size = s
}
}
result = append(result, PVCSummary{
Namespace: p.Metadata.Namespace,
Name: p.Metadata.Name,
Phase: p.Status.Phase,
Size: size,
StorageClass: p.Spec.StorageClassName,
Namespace: p.Metadata.Namespace,
Name: p.Metadata.Name,
Phase: p.Status.Phase,
Size: size,
StorageClass: p.Spec.StorageClassName,
})
}
c.JSON(200, model.Response{Code: 200, Data: result})
@@ -486,11 +518,18 @@ func (h *KubernetesHandler) ListPVCsNS(c *gin.Context) {
// DeletePVCNS deletes a PVC (code-based)
func (h *KubernetesHandler) DeletePVCNS(c *gin.Context) {
clusterID := h.resolveClusterCode(c.Param("clusterCode"))
if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return }
if clusterID == 0 {
c.JSON(500, model.Response{Code: 500, Message: "cluster not found"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
if err := client.DeletePVC(c.Param("namespace"), c.Param("name")); err != nil {
c.JSON(500, model.Response{Code: 500, Message: "删除失败: " + err.Error()}); return
c.JSON(500, model.Response{Code: 500, Message: "删除失败: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Message: "已删除"})
}
+357 -98
View File
@@ -208,15 +208,25 @@ func (h *KubernetesHandler) GetDeploymentNS(c *gin.Context) {
ns := c.Param("namespace")
name := c.Param("name")
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
deps, err := client.ListDeployments()
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()})
return
}
for _, d := range deps.Items {
if d.Metadata.Namespace == ns && d.Metadata.Name == name {
image := ""
if len(d.Spec.Template.Spec.Containers) > 0 { image = d.Spec.Template.Spec.Containers[0].Image }
if len(d.Spec.Template.Spec.Containers) > 0 {
image = d.Spec.Template.Spec.Containers[0].Image
}
c.JSON(200, model.Response{Code: 200, Data: map[string]interface{}{
"namespace": d.Metadata.Namespace,
"name": d.Metadata.Name,
@@ -248,11 +258,19 @@ func (h *KubernetesHandler) ResumeDeploymentNS(c *gin.Context) {
}
func (h *KubernetesHandler) listDeploymentsWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
deps, err := client.ListDeployments()
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()})
return
}
type DepSummary struct {
Namespace string `json:"namespace"`
Name string `json:"name"`
@@ -265,8 +283,13 @@ func (h *KubernetesHandler) listDeploymentsWithNS(c *gin.Context, ns string) {
}
result := []DepSummary{}
for _, d := range deps.Items {
if d.Metadata.Namespace != ns { continue }
image := ""; if len(d.Spec.Template.Spec.Containers) > 0 { image = d.Spec.Template.Spec.Containers[0].Image }
if d.Metadata.Namespace != ns {
continue
}
image := ""
if len(d.Spec.Template.Spec.Containers) > 0 {
image = d.Spec.Template.Spec.Containers[0].Image
}
result = append(result, DepSummary{
Namespace: d.Metadata.Namespace,
Name: d.Metadata.Name,
@@ -275,63 +298,131 @@ func (h *KubernetesHandler) listDeploymentsWithNS(c *gin.Context, ns string) {
ReadyReplicas: d.Status.ReadyReplicas,
Image: image,
Paused: d.Spec.Paused,
Selector: func() map[string]string { if d.Spec.Selector != nil { return d.Spec.Selector.MatchLabels }; return nil }(),
Selector: func() map[string]string {
if d.Spec.Selector != nil {
return d.Spec.Selector.MatchLabels
}
return nil
}(),
})
}
c.JSON(200, model.Response{Code: 200, Data: result})
}
func (h *KubernetesHandler) scaleDeploymentWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
var req struct { Replicas int `json:"replicas"` }
if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, model.Response{Code: 400, Message: "参数错误"}); return }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
var req struct {
Replicas int `json:"replicas"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, model.Response{Code: 400, Message: "参数错误"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err := client.ScaleDeployment(ns, c.Param("name"), req.Replicas); err != nil { c.JSON(500, model.Response{Code: 500, Message: "扩缩容失败: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
if err := client.ScaleDeployment(ns, c.Param("name"), req.Replicas); err != nil {
c.JSON(500, model.Response{Code: 500, Message: "扩缩容失败: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Message: fmt.Sprintf("已设置为 %d 副本", req.Replicas)})
}
func (h *KubernetesHandler) restartDeploymentWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err := client.RestartDeployment(ns, c.Param("name")); err != nil { c.JSON(500, model.Response{Code: 500, Message: "重启失败: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
if err := client.RestartDeployment(ns, c.Param("name")); err != nil {
c.JSON(500, model.Response{Code: 500, Message: "重启失败: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Message: "重启指令已下发"})
}
func (h *KubernetesHandler) updateDeploymentImageWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
var req struct { Image string `json:"image"`; ContainerName string `json:"container_name"` }
if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, model.Response{Code: 400, Message: "参数错误"}); return }
if strings.TrimSpace(req.Image) == "" { c.JSON(400, model.Response{Code: 400, Message: "image 不能为空"}); return }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
var req struct {
Image string `json:"image"`
ContainerName string `json:"container_name"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, model.Response{Code: 400, Message: "参数错误"})
return
}
if strings.TrimSpace(req.Image) == "" {
c.JSON(400, model.Response{Code: 400, Message: "image 不能为空"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err := client.UpdateDeploymentImage(ns, c.Param("name"), req.ContainerName, req.Image); err != nil { c.JSON(500, model.Response{Code: 500, Message: "更新镜像失败: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
if err := client.UpdateDeploymentImage(ns, c.Param("name"), req.ContainerName, req.Image); err != nil {
c.JSON(500, model.Response{Code: 500, Message: "更新镜像失败: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Message: fmt.Sprintf("镜像已更新为 %s", req.Image)})
}
func (h *KubernetesHandler) pauseDeploymentWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err := client.PauseDeployment(ns, c.Param("name")); err != nil { c.JSON(500, model.Response{Code: 500, Message: "暂停更新失败: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
if err := client.PauseDeployment(ns, c.Param("name")); err != nil {
c.JSON(500, model.Response{Code: 500, Message: "暂停更新失败: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Message: "已暂停滚动更新"})
}
func (h *KubernetesHandler) resumeDeploymentWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err := client.ResumeDeployment(ns, c.Param("name")); err != nil { c.JSON(500, model.Response{Code: 500, Message: "恢复更新失败: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
if err := client.ResumeDeployment(ns, c.Param("name")); err != nil {
c.JSON(500, model.Response{Code: 500, Message: "恢复更新失败: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Message: "已恢复滚动更新"})
}
func (h *KubernetesHandler) ListDeploymentsAllNS(c *gin.Context) {
clusterID := h.resolveClusterCode(c.Param("clusterCode"))
if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return }
if clusterID == 0 {
c.JSON(500, model.Response{Code: 500, Message: "cluster not found"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
deps, err := client.ListDeployments()
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()})
return
}
type DepSummary struct {
Namespace string `json:"namespace"`
Name string `json:"name"`
@@ -342,7 +433,10 @@ func (h *KubernetesHandler) ListDeploymentsAllNS(c *gin.Context) {
}
result := []DepSummary{}
for _, d := range deps.Items {
image := ""; if len(d.Spec.Template.Spec.Containers) > 0 { image = d.Spec.Template.Spec.Containers[0].Image }
image := ""
if len(d.Spec.Template.Spec.Containers) > 0 {
image = d.Spec.Template.Spec.Containers[0].Image
}
result = append(result, DepSummary{
Namespace: d.Metadata.Namespace,
Name: d.Metadata.Name,
@@ -358,11 +452,20 @@ func (h *KubernetesHandler) ListDeploymentsAllNS(c *gin.Context) {
// ListPodsAllNS lists all pods across all namespaces using clusterCode.
func (h *KubernetesHandler) ListStatefulSetsNS(c *gin.Context) {
clusterID := h.resolveClusterCode(c.Param("clusterCode"))
if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return }
if clusterID == 0 {
c.JSON(500, model.Response{Code: 500, Message: "cluster not found"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
sts, err := client.ListStatefulSets()
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()})
return
}
ns := c.Param("namespace")
type StsSummary struct {
Namespace string `json:"namespace"`
@@ -373,8 +476,13 @@ func (h *KubernetesHandler) ListStatefulSetsNS(c *gin.Context) {
}
result := []StsSummary{}
for _, s := range sts.Items {
if s.Metadata.Namespace != ns { continue }
image := ""; if len(s.Spec.Template.Spec.Containers) > 0 { image = s.Spec.Template.Spec.Containers[0].Image }
if s.Metadata.Namespace != ns {
continue
}
image := ""
if len(s.Spec.Template.Spec.Containers) > 0 {
image = s.Spec.Template.Spec.Containers[0].Image
}
result = append(result, StsSummary{
Namespace: s.Metadata.Namespace,
Name: s.Metadata.Name,
@@ -389,11 +497,20 @@ func (h *KubernetesHandler) ListStatefulSetsNS(c *gin.Context) {
// ListDaemonSetsNS lists DaemonSets in a namespace
func (h *KubernetesHandler) ListDaemonSetsNS(c *gin.Context) {
clusterID := h.resolveClusterCode(c.Param("clusterCode"))
if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return }
if clusterID == 0 {
c.JSON(500, model.Response{Code: 500, Message: "cluster not found"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
ds, err := client.ListDaemonSets()
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()})
return
}
ns := c.Param("namespace")
type DsSummary struct {
Namespace string `json:"namespace"`
@@ -405,8 +522,13 @@ func (h *KubernetesHandler) ListDaemonSetsNS(c *gin.Context) {
}
result := []DsSummary{}
for _, d := range ds.Items {
if d.Metadata.Namespace != ns { continue }
image := ""; if len(d.Spec.Template.Spec.Containers) > 0 { image = d.Spec.Template.Spec.Containers[0].Image }
if d.Metadata.Namespace != ns {
continue
}
image := ""
if len(d.Spec.Template.Spec.Containers) > 0 {
image = d.Spec.Template.Spec.Containers[0].Image
}
result = append(result, DsSummary{
Namespace: d.Metadata.Namespace,
Name: d.Metadata.Name,
@@ -418,18 +540,31 @@ func (h *KubernetesHandler) ListDaemonSetsNS(c *gin.Context) {
}
c.JSON(200, model.Response{Code: 200, Data: result})
}
// ScaleStatefulSetNS scales a StatefulSet (Kuboard code route)
func (h *KubernetesHandler) ScaleStatefulSetNS(c *gin.Context) {
clusterID := h.resolveClusterCode(c.Param("clusterCode"))
if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return }
if clusterID == 0 {
c.JSON(500, model.Response{Code: 500, Message: "cluster not found"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
ns := c.Param("namespace")
name := c.Param("name")
var req struct{ Replicas int `json:"replicas"` }
if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, model.Response{Code: 400, Message: "参数错误"}); return }
var req struct {
Replicas int `json:"replicas"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, model.Response{Code: 400, Message: "参数错误"})
return
}
if err := client.ScaleStatefulSet(ns, name, req.Replicas); err != nil {
c.JSON(500, model.Response{Code: 500, Message: "扩缩容失败: " + err.Error()}); return
c.JSON(500, model.Response{Code: 500, Message: "扩缩容失败: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Message: "StatefulSet 副本数已更新为 " + strconv.Itoa(req.Replicas)})
}
@@ -437,16 +572,30 @@ func (h *KubernetesHandler) ScaleStatefulSetNS(c *gin.Context) {
// ScaleStatefulSet scales a StatefulSet (ID route)
func (h *KubernetesHandler) ScaleStatefulSet(c *gin.Context) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
if clusterID == 0 {
c.JSON(500, model.Response{Code: 500, Message: "cluster not found"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
ns := c.Param("namespace")
name := c.Param("name")
var req struct{ Replicas int `json:"replicas"` }
if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, model.Response{Code: 400, Message: "参数错误"}); return }
var req struct {
Replicas int `json:"replicas"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, model.Response{Code: 400, Message: "参数错误"})
return
}
if err := client.ScaleStatefulSet(ns, name, req.Replicas); err != nil {
c.JSON(500, model.Response{Code: 500, Message: "扩缩容失败: " + err.Error()}); return
c.JSON(500, model.Response{Code: 500, Message: "扩缩容失败: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Message: "StatefulSet 副本数已更新为 " + strconv.Itoa(req.Replicas)})
}
@@ -454,13 +603,20 @@ func (h *KubernetesHandler) ScaleStatefulSet(c *gin.Context) {
// RestartStatefulSetNS restarts a StatefulSet (Kuboard code route)
func (h *KubernetesHandler) RestartStatefulSetNS(c *gin.Context) {
clusterID := h.resolveClusterCode(c.Param("clusterCode"))
if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return }
if clusterID == 0 {
c.JSON(500, model.Response{Code: 500, Message: "cluster not found"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
ns := c.Param("namespace")
name := c.Param("name")
if err := client.RestartStatefulSet(ns, name); err != nil {
c.JSON(500, model.Response{Code: 500, Message: "重启失败: " + err.Error()}); return
c.JSON(500, model.Response{Code: 500, Message: "重启失败: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Message: "StatefulSet 滚动重启已触发"})
}
@@ -468,14 +624,23 @@ func (h *KubernetesHandler) RestartStatefulSetNS(c *gin.Context) {
// RestartStatefulSet restarts a StatefulSet (ID route)
func (h *KubernetesHandler) RestartStatefulSet(c *gin.Context) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
if clusterID == 0 {
c.JSON(500, model.Response{Code: 500, Message: "cluster not found"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
ns := c.Param("namespace")
name := c.Param("name")
if err := client.RestartStatefulSet(ns, name); err != nil {
c.JSON(500, model.Response{Code: 500, Message: "重启失败: " + err.Error()}); return
c.JSON(500, model.Response{Code: 500, Message: "重启失败: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Message: "StatefulSet 滚动重启已触发"})
}
@@ -483,13 +648,20 @@ func (h *KubernetesHandler) RestartStatefulSet(c *gin.Context) {
// RestartDaemonSetNS restarts a DaemonSet (Kuboard code route)
func (h *KubernetesHandler) RestartDaemonSetNS(c *gin.Context) {
clusterID := h.resolveClusterCode(c.Param("clusterCode"))
if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return }
if clusterID == 0 {
c.JSON(500, model.Response{Code: 500, Message: "cluster not found"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
ns := c.Param("namespace")
name := c.Param("name")
if err := client.RestartDaemonSet(ns, name); err != nil {
c.JSON(500, model.Response{Code: 500, Message: "重启失败: " + err.Error()}); return
c.JSON(500, model.Response{Code: 500, Message: "重启失败: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Message: "DaemonSet 滚动重启已触发"})
}
@@ -497,14 +669,23 @@ func (h *KubernetesHandler) RestartDaemonSetNS(c *gin.Context) {
// RestartDaemonSet restarts a DaemonSet (ID route)
func (h *KubernetesHandler) RestartDaemonSet(c *gin.Context) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
if clusterID == 0 {
c.JSON(500, model.Response{Code: 500, Message: "cluster not found"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
ns := c.Param("namespace")
name := c.Param("name")
if err := client.RestartDaemonSet(ns, name); err != nil {
c.JSON(500, model.Response{Code: 500, Message: "重启失败: " + err.Error()}); return
c.JSON(500, model.Response{Code: 500, Message: "重启失败: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Message: "DaemonSet 滚动重启已触发"})
}
@@ -512,26 +693,44 @@ func (h *KubernetesHandler) RestartDaemonSet(c *gin.Context) {
// GetStatefulSetDetailNS returns a single StatefulSet detail (Kuboard code route)
func (h *KubernetesHandler) GetStatefulSetDetailNS(c *gin.Context) {
clusterID := h.resolveClusterCode(c.Param("clusterCode"))
if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return }
if clusterID == 0 {
c.JSON(500, model.Response{Code: 500, Message: "cluster not found"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
ns := c.Param("namespace")
name := c.Param("name")
sts, err := client.GetStatefulSet(ns, name)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Data: sts})
}
// GetDaemonSetDetailNS returns a single DaemonSet detail (Kuboard code route)
func (h *KubernetesHandler) GetDaemonSetDetailNS(c *gin.Context) {
clusterID := h.resolveClusterCode(c.Param("clusterCode"))
if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return }
if clusterID == 0 {
c.JSON(500, model.Response{Code: 500, Message: "cluster not found"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
ns := c.Param("namespace")
name := c.Param("name")
ds, err := client.GetDaemonSet(ns, name)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Data: ds})
}
@@ -545,11 +744,19 @@ func (h *KubernetesHandler) ListReplicaSetsNS(c *gin.Context) {
}
func (h *KubernetesHandler) listReplicaSetsWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
items, err := client.ListReplicaSetsRaw(ns)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()})
return
}
type RSSummary struct {
Namespace string `json:"namespace"`
Name string `json:"name"`
@@ -564,11 +771,16 @@ func (h *KubernetesHandler) listReplicaSetsWithNS(c *gin.Context, ns string) {
result := []RSSummary{}
for _, rs := range items {
image := ""
if len(rs.Spec.Template.Spec.Containers) > 0 { image = rs.Spec.Template.Spec.Containers[0].Image }
if len(rs.Spec.Template.Spec.Containers) > 0 {
image = rs.Spec.Template.Spec.Containers[0].Image
}
revision := rs.Metadata.Annotations["deployment.kubernetes.io/revision"]
owner := ""
for _, o := range rs.Metadata.OwnerReferences {
if o.Kind == "Deployment" { owner = o.Name; break }
if o.Kind == "Deployment" {
owner = o.Name
break
}
}
result = append(result, RSSummary{
Namespace: rs.Metadata.Namespace,
@@ -591,13 +803,24 @@ func (h *KubernetesHandler) ListDeploymentRevisionsNS(c *gin.Context) {
}
func (h *KubernetesHandler) listDeploymentRevisionsWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
deploymentName := c.Param("name")
if deploymentName == "" { c.JSON(400, model.Response{Code: 400, Message: "缺少 deployment name"}); return }
if deploymentName == "" {
c.JSON(400, model.Response{Code: 400, Message: "缺少 deployment name"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
items, err := client.ListReplicaSetsRaw(ns)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()})
return
}
type Revision struct {
Revision string `json:"revision"`
ReplicaSet string `json:"replica_set"`
@@ -610,11 +833,18 @@ func (h *KubernetesHandler) listDeploymentRevisionsWithNS(c *gin.Context, ns str
for _, rs := range items {
isOwner := false
for _, o := range rs.Metadata.OwnerReferences {
if o.Kind == "Deployment" && o.Name == deploymentName { isOwner = true; break }
if o.Kind == "Deployment" && o.Name == deploymentName {
isOwner = true
break
}
}
if !isOwner {
continue
}
if !isOwner { continue }
image := ""
if len(rs.Spec.Template.Spec.Containers) > 0 { image = rs.Spec.Template.Spec.Containers[0].Image }
if len(rs.Spec.Template.Spec.Containers) > 0 {
image = rs.Spec.Template.Spec.Containers[0].Image
}
result = append(result, Revision{
Revision: rs.Metadata.Annotations["deployment.kubernetes.io/revision"],
ReplicaSet: rs.Metadata.Name,
@@ -639,28 +869,44 @@ func (h *KubernetesHandler) RollbackDeploymentNS(c *gin.Context) {
}
func (h *KubernetesHandler) rollbackDeploymentWithNS(c *gin.Context, ns string) {
clusterID, _ := strconv.Atoi(c.Param("id"))
if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) }
if clusterID == 0 {
clusterID = h.resolveClusterCode(c.Param("clusterCode"))
}
deploymentName := c.Param("name")
if deploymentName == "" { c.JSON(400, model.Response{Code: 400, Message: "缺少 deployment name"}); return }
if deploymentName == "" {
c.JSON(400, model.Response{Code: 400, Message: "缺少 deployment name"})
return
}
var req struct {
Revision int `json:"revision"`
ReplicaSet string `json:"replicaSet"`
}
_ = c.ShouldBindJSON(&req) // 允许空 body(但下面会校验)
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
targetRS := req.ReplicaSet
// 通过 revision 定位 ReplicaSet
if targetRS == "" && req.Revision > 0 {
items, err := client.ListReplicaSetsRaw(ns)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "获取 ReplicaSet 列表失败: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "获取 ReplicaSet 列表失败: " + err.Error()})
return
}
for _, rs := range items {
isOwner := false
for _, o := range rs.Metadata.OwnerReferences {
if o.Kind == "Deployment" && o.Name == deploymentName { isOwner = true; break }
if o.Kind == "Deployment" && o.Name == deploymentName {
isOwner = true
break
}
}
if !isOwner {
continue
}
if !isOwner { continue }
if rs.Metadata.Annotations["deployment.kubernetes.io/revision"] == strconv.Itoa(req.Revision) {
targetRS = rs.Metadata.Name
break
@@ -671,18 +917,31 @@ func (h *KubernetesHandler) rollbackDeploymentWithNS(c *gin.Context, ns string)
return
}
}
if targetRS == "" { c.JSON(400, model.Response{Code: 400, Message: "需要 revision 或 replicaSet 参数"}); return }
if targetRS == "" {
c.JSON(400, model.Response{Code: 400, Message: "需要 revision 或 replicaSet 参数"})
return
}
// 取 ReplicaSet 的 template,patch 到 Deployment.spec.template 实现回滚
rsJSON, err := client.GetReplicaSet(ns, targetRS)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "获取 ReplicaSet 失败: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "获取 ReplicaSet 失败: " + err.Error()})
return
}
specMap, ok := rsJSON["spec"].(map[string]interface{})
if !ok { c.JSON(500, model.Response{Code: 500, Message: "ReplicaSet 缺少 spec"}); return }
if !ok {
c.JSON(500, model.Response{Code: 500, Message: "ReplicaSet 缺少 spec"})
return
}
template, ok := specMap["template"].(map[string]interface{})
if !ok { c.JSON(500, model.Response{Code: 500, Message: "ReplicaSet 缺少 template"}); return }
if !ok {
c.JSON(500, model.Response{Code: 500, Message: "ReplicaSet 缺少 template"})
return
}
if err := client.PatchDeploymentSpecTemplate(ns, deploymentName, template); err != nil {
c.JSON(500, model.Response{Code: 500, Message: "回滚失败: " + err.Error()}); return
c.JSON(500, model.Response{Code: 500, Message: "回滚失败: " + err.Error()})
return
}
c.JSON(200, model.Response{
Code: 200,
+64 -18
View File
@@ -12,9 +12,15 @@ import (
func (h *KubernetesHandler) GetResourceYAMLNS(c *gin.Context) {
clusterID := h.resolveClusterCode(c.Param("clusterCode"))
if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return }
if clusterID == 0 {
c.JSON(500, model.Response{Code: 500, Message: "cluster not found"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
ns := c.Param("namespace")
resource := c.Param("resource")
// Fallback: specific routes (statefulsets/:name/yaml, daemonsets/:name/yaml) have no :resource param
@@ -62,10 +68,14 @@ func (h *KubernetesHandler) GetResourceYAMLNS(c *gin.Context) {
case "rolebindings", "rolebinding":
apiPath = fmt.Sprintf("/apis/rbac.authorization.k8s.io/v1/namespaces/%s/rolebindings/%s", ns, name)
default:
c.JSON(400, model.Response{Code: 400, Message: "unsupported resource type: " + resource}); return
c.JSON(400, model.Response{Code: 400, Message: "unsupported resource type: " + resource})
return
}
yamlBytes, err := client.GetResourceYAML(apiPath)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "获取YAML失败: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "获取YAML失败: " + err.Error()})
return
}
c.Header("Content-Type", "application/yaml")
c.String(200, string(yamlBytes))
}
@@ -73,9 +83,15 @@ func (h *KubernetesHandler) GetResourceYAMLNS(c *gin.Context) {
// UpdateResourceYAMLNS applies YAML to update a K8s resource
func (h *KubernetesHandler) UpdateResourceYAMLNS(c *gin.Context) {
clusterID := h.resolveClusterCode(c.Param("clusterCode"))
if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return }
if clusterID == 0 {
c.JSON(500, model.Response{Code: 500, Message: "cluster not found"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
ns := c.Param("namespace")
resource := c.Param("resource")
// Fallback: specific routes (statefulsets/:name/yaml, daemonsets/:name/yaml) have no :resource param
@@ -90,7 +106,10 @@ func (h *KubernetesHandler) UpdateResourceYAMLNS(c *gin.Context) {
}
name := c.Param("name")
yamlData, err := io.ReadAll(c.Request.Body)
if err != nil { c.JSON(400, model.Response{Code: 400, Message: "读取body失败"}); return }
if err != nil {
c.JSON(400, model.Response{Code: 400, Message: "读取body失败"})
return
}
var apiPath string
switch resource {
case "deployments", "deployment":
@@ -124,10 +143,12 @@ func (h *KubernetesHandler) UpdateResourceYAMLNS(c *gin.Context) {
case "rolebindings", "rolebinding":
apiPath = fmt.Sprintf("/apis/rbac.authorization.k8s.io/v1/namespaces/%s/rolebindings/%s", ns, name)
default:
c.JSON(400, model.Response{Code: 400, Message: "unsupported resource type: " + resource}); return
c.JSON(400, model.Response{Code: 400, Message: "unsupported resource type: " + resource})
return
}
if err := client.UpdateResourceYAML(apiPath, yamlData); err != nil {
c.JSON(500, model.Response{Code: 500, Message: "更新失败: " + err.Error()}); return
c.JSON(500, model.Response{Code: 500, Message: "更新失败: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Message: "YAML已应用"})
}
@@ -173,16 +194,26 @@ func resourceAPIPath(ns, resource, name string) (string, error) {
// DeleteResourceYAMLNS deletes a K8s resource (Service/Ingress/ConfigMap etc.)
func (h *KubernetesHandler) DeleteResourceYAMLNS(c *gin.Context) {
clusterID := h.resolveClusterCode(c.Param("clusterCode"))
if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return }
if clusterID == 0 {
c.JSON(500, model.Response{Code: 500, Message: "cluster not found"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
ns := c.Param("namespace")
resource := c.Param("resource")
name := c.Param("name")
apiPath, err := resourceAPIPath(ns, resource, name)
if err != nil { c.JSON(400, model.Response{Code: 400, Message: err.Error()}); return }
if err != nil {
c.JSON(400, model.Response{Code: 400, Message: err.Error()})
return
}
if err := client.DeleteResource(apiPath); err != nil {
c.JSON(500, model.Response{Code: 500, Message: "删除失败: " + err.Error()}); return
c.JSON(500, model.Response{Code: 500, Message: "删除失败: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Message: "资源已删除"})
}
@@ -190,18 +221,33 @@ func (h *KubernetesHandler) DeleteResourceYAMLNS(c *gin.Context) {
// getK8sClient builds a K8s API client from cluster's stored kubeconfig
func (h *KubernetesHandler) ApplyYAML(c *gin.Context) {
clusterID := h.resolveClusterCode(c.Param("clusterCode"))
if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return }
if clusterID == 0 {
c.JSON(500, model.Response{Code: 500, Message: "cluster not found"})
return
}
client, _, err := h.getK8sClient(clusterID)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: err.Error()})
return
}
var req struct {
YAML string `json:"yaml"`
}
if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, model.Response{Code: 400, Message: "参数错误: " + err.Error()}); return }
if req.YAML == "" { c.JSON(400, model.Response{Code: 400, Message: "YAML 内容不能为空"}); return }
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, model.Response{Code: 400, Message: "参数错误: " + err.Error()})
return
}
if req.YAML == "" {
c.JSON(400, model.Response{Code: 400, Message: "YAML 内容不能为空"})
return
}
result, err := client.ApplyYAML(req.YAML)
if err != nil { c.JSON(500, model.Response{Code: 500, Message: "Apply 失败: " + err.Error()}); return }
if err != nil {
c.JSON(500, model.Response{Code: 500, Message: "Apply 失败: " + err.Error()})
return
}
c.JSON(200, model.Response{Code: 200, Message: "资源已应用", Data: result})
}
+1 -1
View File
@@ -151,4 +151,4 @@ func ldapAddADUser(conn *ldap.Conn, userDN, username, displayName, email, passwo
modEnable := ldap.NewModifyRequest(userDN, nil)
modEnable.Replace("userAccountControl", []string{"512"})
return conn.Modify(modEnable)
}
}
+10 -10
View File
@@ -60,17 +60,17 @@ func (h *LLMHandler) GetLLMConfig(c *gin.Context) {
return
}
c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{
"id": cfg.ID,
"provider": cfg.Provider,
"model": cfg.Model,
"api_key": cfg.APIKey,
"endpoint": cfg.Endpoint,
"temperature": cfg.Temperature,
"max_tokens": cfg.MaxTokens,
"system_prompt": cfg.SystemPrompt,
"enabled": cfg.Enabled,
"id": cfg.ID,
"provider": cfg.Provider,
"model": cfg.Model,
"api_key": cfg.APIKey,
"endpoint": cfg.Endpoint,
"temperature": cfg.Temperature,
"max_tokens": cfg.MaxTokens,
"system_prompt": cfg.SystemPrompt,
"enabled": cfg.Enabled,
"reasoning_enabled": cfg.ReasoningEnabled,
"configured": true,
"configured": true,
}})
}
+1 -1
View File
@@ -23,4 +23,4 @@ func buildLLMConfigFromModel(cfg model.LLMConfig) llm.Config {
// buildLLMClientFromConfig 从 model.LLMConfig 构造 LLM 客户端(OpenAI/Anthropic 自动路由) // Logan.Li
func buildLLMClientFromConfig(cfg model.LLMConfig) llm.Client {
return llm.NewClient(buildLLMConfigFromModel(cfg))
}
}
+4 -4
View File
@@ -74,10 +74,10 @@ func (h *LogHandler) CreateSource(c *gin.Context) {
configJSON, _ := json.Marshal(req.Config)
now := time.Now()
item := model.LogSource{
Name: req.Name,
Type: req.Type,
Status: "active",
Config: string(configJSON),
Name: req.Name,
Type: req.Type,
Status: "active",
Config: string(configJSON),
LastSeen: &now,
}
h.db.Create(&item)
+2 -2
View File
@@ -76,7 +76,7 @@ func (h *LogDSHandler) Create(c *gin.Context) {
}
ds := model.LogDataSource{
Name: req.Name, Type: req.Type, URL: strings.TrimRight(req.URL, "/"),
AuthType: normalizeLogDSAuthType(req.AuthType),
AuthType: normalizeLogDSAuthType(req.AuthType),
BasicAuth: req.BasicAuth, BasicAuthUser: req.BasicAuthUser, BasicAuthPass: req.BasicAuthPass,
Token: req.Token, Headers: req.Headers,
SkipTLSVerify: req.SkipTLSVerify, DefaultIndex: req.DefaultIndex,
@@ -439,4 +439,4 @@ func normalizeLogDSAuthType(t string) string {
default:
return "none"
}
}
}
+1 -1
View File
@@ -477,4 +477,4 @@ func formatLokiMetricTimestamp(v interface{}) string {
}
}
return formatLokiTimestamp(fmt.Sprintf("%v", v))
}
}
+1 -1
View File
@@ -198,4 +198,4 @@ func (h *LogScopeRoleHandler) PreviewLogScope(c *gin.Context) {
"matched": matched,
"total": len(matched),
}})
}
}
+16 -16
View File
@@ -134,15 +134,15 @@ func (h *MetricsHandler) TopHosts(c *gin.Context) {
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "5"))
type HostRank struct {
Hostname string `json:"hostname"`
IP string `json:"ip"`
CPUUsage float64 `json:"cpu_usage"`
MemUsage float64 `json:"memory_usage"`
Hostname string `json:"hostname"`
IP string `json:"ip"`
CPUUsage float64 `json:"cpu_usage"`
MemUsage float64 `json:"memory_usage"`
DiskUsage float64 `json:"disk_usage"`
CPUCores int `json:"cpu_cores"`
MemMB int64 `json:"memory_mb"`
DiskGB int64 `json:"disk_gb"`
Status string `json:"status"`
CPUCores int `json:"cpu_cores"`
MemMB int64 `json:"memory_mb"`
DiskGB int64 `json:"disk_gb"`
Status string `json:"status"`
}
var servers []model.Server
@@ -166,15 +166,15 @@ func (h *MetricsHandler) TopHosts(c *gin.Context) {
result := make([]HostRank, len(servers))
for i, s := range servers {
result[i] = HostRank{
Hostname: s.Hostname,
IP: s.IP,
CPUUsage: s.CPUUsage,
MemUsage: s.MemoryUsage,
Hostname: s.Hostname,
IP: s.IP,
CPUUsage: s.CPUUsage,
MemUsage: s.MemoryUsage,
DiskUsage: s.DiskUsage,
CPUCores: s.CPU,
MemMB: s.Memory,
DiskGB: s.Disk,
Status: s.Status,
CPUCores: s.CPU,
MemMB: s.Memory,
DiskGB: s.Disk,
Status: s.Status,
}
}
if result == nil {
+1 -1
View File
@@ -14,7 +14,7 @@ import (
// MetricsUpdate 单个主机的指标更新 // Logan.Li
type MetricsUpdate struct {
Type string `json:"type"` // "metrics_update"
Type string `json:"type"` // "metrics_update"
Hostname string `json:"hostname"`
CPU float64 `json:"cpu_usage"`
Memory float64 `json:"memory_usage"`
+3 -3
View File
@@ -15,8 +15,8 @@ import (
"ezops/model"
"ezops/pkg/systask"
_ "github.com/go-sql-driver/mysql"
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
"gorm.io/gorm"
)
@@ -28,8 +28,8 @@ import (
// MiddlewareConfig 存储在 MonitorTarget.Config JSON 字段中
type MiddlewareConfig struct {
Password string `json:"password,omitempty"`
Username string `json:"username,omitempty"` // MySQL 专用
Database string `json:"database,omitempty"` // MySQL 专用
Username string `json:"username,omitempty"` // MySQL 专用
Database string `json:"database,omitempty"` // MySQL 专用
RedisMode string `json:"redis_mode,omitempty"` // Redis: standalone / cluster
}
@@ -98,4 +98,4 @@ func buildRedisMetrics(info string, dbSize int64, clusterInfo, mode string) map[
}
return result
}
}
@@ -14,12 +14,12 @@ import (
// middlewareSeedResult 种子创建结果 // Logan.Li
type middlewareSeedResult struct {
Created int `json:"created"`
Skipped []string `json:"skipped"`
Failed []string `json:"failed"`
Total int64 `json:"total"`
Message string `json:"message"`
Success bool `json:"success"`
Created int `json:"created"`
Skipped []string `json:"skipped"`
Failed []string `json:"failed"`
Total int64 `json:"total"`
Message string `json:"message"`
Success bool `json:"success"`
}
// SeedDefaultMiddlewareTargets 首次启动时创建平台默认 Redis/MySQL 监控目标 // Logan.Li
@@ -117,4 +117,4 @@ func seedDefaultMiddlewareTargets(db *gorm.DB) middlewareSeedResult {
result.Message = "未创建任何默认目标"
}
return result
}
}
+1 -1
View File
@@ -282,4 +282,4 @@ func (h *AlertHandler) ResolveUnifiedAlert(c *gin.Context) {
return
}
c.JSON(http.StatusOK, model.Response{Code: 200, Message: "已恢复"})
}
}
+116 -60
View File
@@ -6,8 +6,8 @@ import (
"strconv"
"time"
"ezops/model"
"ezops/middleware"
"ezops/model"
ezredis "ezops/pkg/redis"
"ezops/pkg/toolinstaller"
@@ -69,7 +69,7 @@ func NewPipelineHandler(db *gorm.DB, cache ezredis.Cache, ti *toolinstaller.Tool
// PipelineListItem 列表项(含最近一次运行摘要)// Logan.Li
type PipelineListItem struct {
model.Pipeline
LastRunStages string `json:"last_run_stages,omitempty"` // JSON: [{name,status}]
LastRunStages string `json:"last_run_stages,omitempty"` // JSON: [{name,status}]
LastImageTag string `json:"last_image_tag,omitempty"`
LastCommitID string `json:"last_commit_id,omitempty"`
LastRunDuration int `json:"last_duration,omitempty"`
@@ -123,7 +123,7 @@ func (h *PipelineHandler) ListPipelines(c *gin.Context) {
}
// 子查询:每个 pipeline_id 的最新 run id
var latestRuns []model.PipelineRun
h.db.Where("id IN (SELECT MAX(id) FROM ops_pipeline_runs WHERE pipeline_id IN ? AND status IN ('success','failed','running','pending') GROUP BY pipeline_id)", pids).
h.db.Where("id IN (SELECT MAX(id) FROM deploy_pipeline_runs WHERE pipeline_id IN ? AND status IN ('success','failed','running','pending') GROUP BY pipeline_id)", pids).
Find(&latestRuns)
runMap := map[uint]*model.PipelineRun{}
for i := range latestRuns {
@@ -147,8 +147,8 @@ func (h *PipelineHandler) ListPipelines(c *gin.Context) {
}
c.JSON(http.StatusOK, model.Response{
Code: 200,
Data: model.ListResponse{List: items, Total: total},
Code: 200,
Data: model.ListResponse{List: items, Total: total},
})
}
@@ -211,30 +211,28 @@ func (h *PipelineHandler) CreatePipeline(c *gin.Context) {
}
pipeline := model.Pipeline{
Name: req.Name,
Code: req.Code,
JobName: req.JobName,
Description: req.Description,
Type: req.Type,
Source: req.Source,
Branch: req.Branch,
Dockerfile: req.Dockerfile,
Stages: req.Stages,
Variables: req.Variables,
DeployMode: req.DeployMode,
DeployTarget: req.DeployTarget,
ServerIDs: req.ServerIDs,
DeployRemotePath: req.DeployRemotePath,
DeployScript: req.DeployScript,
K8sClusterID: req.K8sClusterID,
K8sNamespace: req.K8sNamespace,
K8sDeployment: req.K8sDeployment,
K8sContainerName: req.K8sContainerName,
RepoID: req.RepoID,
RegistryID: req.RegistryID,
Name: req.Name,
Code: req.Code,
JobName: req.JobName,
Description: req.Description,
Type: req.Type,
Source: req.Source,
Branch: req.Branch,
Dockerfile: req.Dockerfile,
Stages: req.Stages,
Variables: req.Variables,
DeployMode: req.DeployMode,
DeployTarget: req.DeployTarget,
ServerIDs: req.ServerIDs,
DeployRemotePath: req.DeployRemotePath,
DeployScript: req.DeployScript,
K8sClusterID: req.K8sClusterID,
K8sNamespace: req.K8sNamespace,
K8sDeployment: req.K8sDeployment,
K8sContainerName: req.K8sContainerName,
GitCredentialID: req.GitCredentialID,
RegistryCredentialID: req.RegistryCredentialID,
EnvironmentID: req.EnvironmentID,
EnvironmentID: req.EnvironmentID,
// 触发配置
TriggerMode: req.TriggerMode,
WatchBranches: req.WatchBranches,
@@ -246,7 +244,7 @@ func (h *PipelineHandler) CreatePipeline(c *gin.Context) {
// 并发控制
MaxExecutors: req.MaxExecutors,
BuildNodeID: req.BuildNodeID,
Enabled: true,
Enabled: true,
}
if err := h.db.Create(&pipeline).Error; err != nil {
@@ -301,38 +299,96 @@ func (h *PipelineHandler) UpdatePipeline(c *gin.Context) {
}
updates := map[string]interface{}{}
if req.Name != "" { updates["name"] = req.Name }
if req.JobName != "" { updates["job_name"] = req.JobName }
if req.Description != "" { updates["description"] = req.Description }
if req.Type != "" { updates["type"] = req.Type }
if req.Source != "" { updates["source"] = req.Source }
if req.Branch != "" { updates["branch"] = req.Branch }
if req.Dockerfile != "" { updates["dockerfile"] = req.Dockerfile }
if req.Stages != "" { updates["stages"] = req.Stages }
if req.Variables != "" { updates["variables"] = req.Variables }
if req.DeployMode != "" { updates["deploy_mode"] = req.DeployMode }
if req.DeployTarget != "" { updates["deploy_target"] = req.DeployTarget }
if req.ServerIDs != "" { updates["server_ids"] = req.ServerIDs }
if req.DeployRemotePath != "" { updates["deploy_remote_path"] = req.DeployRemotePath }
if req.DeployScript != "" { updates["deploy_script"] = req.DeployScript }
if req.K8sNamespace != "" { updates["k8s_namespace"] = req.K8sNamespace }
if req.K8sDeployment != "" { updates["k8s_deployment"] = req.K8sDeployment }
if req.K8sContainerName != "" { updates["k8s_container_name"] = req.K8sContainerName }
if req.K8sClusterID != nil { updates["k8s_cluster_id"] = req.K8sClusterID }
if req.RepoID != nil { updates["repo_id"] = req.RepoID }
if req.RegistryID != nil { updates["registry_id"] = req.RegistryID }
if req.GitCredentialID != nil { updates["git_credential_id"] = req.GitCredentialID }
if req.RegistryCredentialID != nil { updates["registry_credential_id"] = req.RegistryCredentialID }
if req.EnvironmentID != nil { updates["environment_id"] = req.EnvironmentID }
if req.TriggerMode != "" { updates["trigger_mode"] = req.TriggerMode }
if req.WatchBranches != "" { updates["watch_branches"] = req.WatchBranches }
if req.ExcludeBranch != "" { updates["exclude_branch"] = req.ExcludeBranch }
if req.CronExpr != "" { updates["cron_expr"] = req.CronExpr }
if req.WebhookToken != "" { updates["webhook_token"] = req.WebhookToken }
if req.CachePaths != "" { updates["cache_paths"] = req.CachePaths }
if req.Enabled != nil { updates["enabled"] = req.Enabled }
if req.MaxExecutors > 0 { updates["max_executors"] = req.MaxExecutors }
if req.BuildNodeID != nil { updates["build_node_id"] = req.BuildNodeID }
if req.Name != "" {
updates["name"] = req.Name
}
if req.JobName != "" {
updates["job_name"] = req.JobName
}
if req.Description != "" {
updates["description"] = req.Description
}
if req.Type != "" {
updates["type"] = req.Type
}
if req.Source != "" {
updates["source"] = req.Source
}
if req.Branch != "" {
updates["branch"] = req.Branch
}
if req.Dockerfile != "" {
updates["dockerfile"] = req.Dockerfile
}
if req.Stages != "" {
updates["stages"] = req.Stages
}
if req.Variables != "" {
updates["variables"] = req.Variables
}
if req.DeployMode != "" {
updates["deploy_mode"] = req.DeployMode
}
if req.DeployTarget != "" {
updates["deploy_target"] = req.DeployTarget
}
if req.ServerIDs != "" {
updates["server_ids"] = req.ServerIDs
}
if req.DeployRemotePath != "" {
updates["deploy_remote_path"] = req.DeployRemotePath
}
if req.DeployScript != "" {
updates["deploy_script"] = req.DeployScript
}
if req.K8sNamespace != "" {
updates["k8s_namespace"] = req.K8sNamespace
}
if req.K8sDeployment != "" {
updates["k8s_deployment"] = req.K8sDeployment
}
if req.K8sContainerName != "" {
updates["k8s_container_name"] = req.K8sContainerName
}
if req.K8sClusterID != nil {
updates["k8s_cluster_id"] = req.K8sClusterID
}
if req.GitCredentialID != nil {
updates["git_credential_id"] = req.GitCredentialID
}
if req.RegistryCredentialID != nil {
updates["registry_credential_id"] = req.RegistryCredentialID
}
if req.EnvironmentID != nil {
updates["environment_id"] = req.EnvironmentID
}
if req.TriggerMode != "" {
updates["trigger_mode"] = req.TriggerMode
}
if req.WatchBranches != "" {
updates["watch_branches"] = req.WatchBranches
}
if req.ExcludeBranch != "" {
updates["exclude_branch"] = req.ExcludeBranch
}
if req.CronExpr != "" {
updates["cron_expr"] = req.CronExpr
}
if req.WebhookToken != "" {
updates["webhook_token"] = req.WebhookToken
}
if req.CachePaths != "" {
updates["cache_paths"] = req.CachePaths
}
if req.Enabled != nil {
updates["enabled"] = req.Enabled
}
if req.MaxExecutors > 0 {
updates["max_executors"] = req.MaxExecutors
}
if req.BuildNodeID != nil {
updates["build_node_id"] = req.BuildNodeID
}
if err := h.db.Model(&pipeline).Updates(updates).Error; err != nil {
c.JSON(http.StatusInternalServerError, model.Response{
+14 -13
View File
@@ -162,7 +162,7 @@ func (h *PipelineHandler) executePipeline(pipeline model.Pipeline, run model.Pip
}
runUpdates := map[string]interface{}{
"workspace_path": workspace,
"workspace_path": workspace,
"build_node_name": execCtx.NodeName,
}
if nodeID > 0 {
@@ -545,13 +545,10 @@ func (h *PipelineHandler) runDeploy(workspace string, pipeline model.Pipeline, t
// resolvePipelineImage 解析流水线构建镜像全名(与镜像打包阶段一致) // Logan.Li
func (h *PipelineHandler) resolvePipelineImage(pipeline model.Pipeline, tag string) string {
var registryURL, imageName string
if pipeline.RegistryID != nil {
var reg model.PipelineRegistry
if err := h.db.First(&reg, *pipeline.RegistryID).Error; err == nil {
registryURL = reg.RegistryURL
if reg.Namespace != "" {
imageName = reg.Namespace + "/"
}
if pipeline.RegistryCredentialID != nil {
var credential model.Credential
if err := h.db.Take(&credential, *pipeline.RegistryCredentialID).Error; err == nil {
registryURL = credential.Summary
}
}
appName := pipeline.Code
@@ -838,7 +835,7 @@ func cleanOldWorkspaces(baseDir string, maxAge time.Duration) {
var (
pipelineRunningCount = make(map[uint]int) // pipelineID → 当前运行数
pipelineQueues = make(map[uint][]uint) // pipelineID → 排队 runID 列表
pipelineQueues = make(map[uint][]uint) // pipelineID → 排队 runID 列表
queueMu sync.Mutex
)
@@ -909,9 +906,13 @@ func (h *PipelineHandler) dequeueNext(pipelineID uint) {
// 加载 pipeline + run
var pipeline model.Pipeline
if err := h.db.First(&pipeline, pipelineID).Error; err != nil { return }
if err := h.db.First(&pipeline, pipelineID).Error; err != nil {
return
}
var run model.PipelineRun
if err := h.db.First(&run, nextRunID).Error; err != nil { return }
if err := h.db.First(&run, nextRunID).Error; err != nil {
return
}
nodeID, canNode := h.tryAcquireBuildNode(pipeline)
if !canNode {
@@ -935,8 +936,8 @@ func (h *PipelineHandler) GetQueueStatus(pipelineID uint) map[string]interface{}
running := pipelineRunningCount[pipelineID]
queued := pipelineQueues[pipelineID]
return map[string]interface{}{
"running": running,
"queued": len(queued),
"running": running,
"queued": len(queued),
"queue_ids": queued,
}
}
+1 -1
View File
@@ -260,4 +260,4 @@ func (h *PipelineHandler) hasBuildFileCtx(ctx *PipelineExecCtx, dir string) bool
}
}
return false
}
}
+1 -1
View File
@@ -32,4 +32,4 @@ func loadRDPCredential(crypt *crypto.SecretBox, server model.Server) (model.RDPS
return cred, errors.New("RDP 凭据缺少用户名或密码")
}
return cred, nil
}
}
+2 -2
View File
@@ -84,8 +84,8 @@ func (h *RemoteExecHandler) BatchExec(c *gin.Context) {
// BatchUploadRequest 批量上传请求
type BatchUploadRequest struct {
ServerIDs []uint `json:"server_ids" binding:"required"` // 目标服务器 ID 列表
LocalPath string `json:"local_path" binding:"required"` // AIOps 主机上的文件路径
ServerIDs []uint `json:"server_ids" binding:"required"` // 目标服务器 ID 列表
LocalPath string `json:"local_path" binding:"required"` // AIOps 主机上的文件路径
RemotePath string `json:"remote_path" binding:"required"` // 远程目标路径
}
+31 -19
View File
@@ -94,8 +94,8 @@ func (h *ServerHandler) ListServers(c *gin.Context) {
// 关键词搜索
if query.Keyword != "" {
db = db.Where("hostname LIKE ? OR ip LIKE ? OR public_ip LIKE ?",
"%"+query.Keyword+"%", "%"+query.Keyword+"%", "%"+query.Keyword+"%")
db = db.Where("alias LIKE ? OR cloud_instance_name LIKE ? OR hostname LIKE ? OR ip LIKE ? OR public_ip LIKE ? OR cloud_instance_id LIKE ?",
"%"+query.Keyword+"%", "%"+query.Keyword+"%", "%"+query.Keyword+"%", "%"+query.Keyword+"%", "%"+query.Keyword+"%", "%"+query.Keyword+"%")
}
// 状态过滤
@@ -194,23 +194,26 @@ func (h *ServerHandler) CreateServer(c *gin.Context) {
}
server := model.Server{
Hostname: req.Hostname,
IP: req.IP,
PublicIP: req.PublicIP,
Port: req.Port,
Username: req.Username,
Password: req.Password,
SSHKey: req.SSHKey,
AuthType: req.AuthType,
OS: req.OS,
CPU: req.CPU,
Memory: req.Memory,
Disk: req.Disk,
RegionID: req.RegionID,
CloudID: req.CloudID,
Tags: req.Tags,
Description: req.Description,
Status: "stopped",
Hostname: req.Hostname,
Alias: req.Alias,
CloudInstanceName: req.CloudInstanceName,
CloudInstanceID: req.CloudInstanceID,
IP: req.IP,
PublicIP: req.PublicIP,
Port: req.Port,
Username: req.Username,
Password: req.Password,
SSHKey: req.SSHKey,
AuthType: req.AuthType,
OS: req.OS,
CPU: req.CPU,
Memory: req.Memory,
Disk: req.Disk,
RegionID: req.RegionID,
CloudID: req.CloudID,
Tags: req.Tags,
Description: req.Description,
Status: "stopped",
}
if req.Status != "" {
@@ -295,6 +298,15 @@ func (h *ServerHandler) UpdateServer(c *gin.Context) {
if req.Hostname != "" {
updates["hostname"] = req.Hostname
}
if req.Alias != nil {
updates["alias"] = *req.Alias
}
if req.CloudInstanceName != "" {
updates["cloud_instance_name"] = req.CloudInstanceName
}
if req.CloudInstanceID != "" {
updates["cloud_instance_id"] = req.CloudInstanceID
}
if req.IP != "" {
updates["ip"] = req.IP
}
+1 -1
View File
@@ -67,7 +67,7 @@ func (h *SessionCommandHandler) ListSessionCommands(c *gin.Context) {
// 联表带出会话录制大小,前端可判断能否回放 // Logan.Li
var items []model.SessionCommandItem
listQuery := h.db.Table("sys_session_commands AS sc").
listQuery := h.db.Table("audit_session_commands AS sc").
Select("sc.*, COALESCE(ts.record_size, rs.record_size, 0) AS session_record_size").
Joins("LEFT JOIN sys_terminal_sessions AS ts ON ts.id = sc.session_id AND COALESCE(sc.session_type, 'terminal') = 'terminal'").
Joins("LEFT JOIN sys_rdp_sessions AS rs ON rs.id = sc.session_id AND sc.session_type = 'rdp'")
+2 -2
View File
@@ -35,8 +35,8 @@ func (h *SFTPHandler) sftpClient(serverID uint) (*sftp.Client, *ssh.Client, erro
}
sshConfig := &ssh.ClientConfig{
User: server.Username,
Timeout: 10 * time.Second,
User: server.Username,
Timeout: 10 * time.Second,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
+1 -1
View File
@@ -267,4 +267,4 @@ func (h *SiteHandler) GetSiteStats(c *gin.Context) {
"availability": availability,
"probe_count": totalRecent,
}})
}
}
+18 -18
View File
@@ -12,23 +12,23 @@ import (
// SiteTaskView 前端拨测任务视图(字段与前端对齐)// Logan.Li
type SiteTaskView struct {
ID uint `json:"id"`
Name string `json:"name"`
URL string `json:"url"`
Type string `json:"type"`
FrequencySec int `json:"frequency_sec"`
TimeoutSec int `json:"timeout_sec"`
ExpectedStatusCode int `json:"expected_status_code"`
Enabled bool `json:"enabled"`
LastStatus string `json:"last_status,omitempty"`
LastResponseTimeMs float64 `json:"last_response_time_ms,omitempty"`
LastCheckedAt *string `json:"last_checked_at,omitempty"`
SuccessRate float64 `json:"success_rate"`
AlertStatus string `json:"alert_status"`
Status string `json:"status"`
CreatedAt string `json:"created_at"`
SSLDaysRemaining *int `json:"ssl_days_remaining,omitempty"`
SSLCertExpiry *string `json:"ssl_cert_expiry,omitempty"`
ID uint `json:"id"`
Name string `json:"name"`
URL string `json:"url"`
Type string `json:"type"`
FrequencySec int `json:"frequency_sec"`
TimeoutSec int `json:"timeout_sec"`
ExpectedStatusCode int `json:"expected_status_code"`
Enabled bool `json:"enabled"`
LastStatus string `json:"last_status,omitempty"`
LastResponseTimeMs float64 `json:"last_response_time_ms,omitempty"`
LastCheckedAt *string `json:"last_checked_at,omitempty"`
SuccessRate float64 `json:"success_rate"`
AlertStatus string `json:"alert_status"`
Status string `json:"status"`
CreatedAt string `json:"created_at"`
SSLDaysRemaining *int `json:"ssl_days_remaining,omitempty"`
SSLCertExpiry *string `json:"ssl_cert_expiry,omitempty"`
}
func toSiteTaskView(task model.SiteTask) SiteTaskView {
@@ -220,4 +220,4 @@ func parseCreateTaskRequest(raw map[string]interface{}) model.SiteTask {
task.DNSResolver = strings.TrimSpace(v)
}
return task
}
}
+12 -12
View File
@@ -50,16 +50,16 @@ func (h *SNMPHandler) ListDevices(c *gin.Context) {
// POST /api/v1/snmp/devices
func (h *SNMPHandler) CreateDevice(c *gin.Context) {
var req struct {
Name string `json:"name" binding:"required"`
IP string `json:"ip" binding:"required"`
Port int `json:"port"`
SnmpVersion string `json:"snmp_version"`
Version string `json:"version"`
Community string `json:"community"`
TemplateID uint `json:"template_id"`
DeviceType string `json:"device_type"`
Vendor string `json:"vendor"`
Description string `json:"description"`
Name string `json:"name" binding:"required"`
IP string `json:"ip" binding:"required"`
Port int `json:"port"`
SnmpVersion string `json:"snmp_version"`
Version string `json:"version"`
Community string `json:"community"`
TemplateID uint `json:"template_id"`
DeviceType string `json:"device_type"`
Vendor string `json:"vendor"`
Description string `json:"description"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()})
@@ -172,8 +172,8 @@ func (h *SNMPHandler) GetSNMPStats(c *gin.Context) {
h.db.Model(&model.SNMPDevice{}).Where("status = ?", "online").Count(&online)
c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{
"total": total,
"online": online,
"total": total,
"online": online,
"abnormal": total - online,
}})
}
+1 -1
View File
@@ -198,4 +198,4 @@ func (h *SNMPHandler) ListDeviceMetrics(c *gin.Context) {
func (h *SNMPHandler) StopCollector() {
close(h.stopCh)
h.wg.Wait()
}
}
+2 -2
View File
@@ -260,7 +260,7 @@ func snmpMetricLabel(name, index string) string {
"h3c_fan_speed": "H3C 风扇", "hw_fan_speed": "华为 风扇",
"ruijie_fan_speed": "锐捷 风扇", "dell_fan_speed": "Dell 风扇", "inspur_fan_speed": "浪潮 风扇",
"ent_sensor_value": "实体传感器",
"if_in_octets": "入方向流量", "if_out_octets": "出方向流量",
"if_in_octets": "入方向流量", "if_out_octets": "出方向流量",
}
label := labels[name]
if label == "" {
@@ -270,4 +270,4 @@ func snmpMetricLabel(name, index string) string {
label += " #" + index
}
return label
}
}
+2 -2
View File
@@ -32,7 +32,7 @@ func (h *SystemTaskHandler) ListSystemTasks(c *gin.Context) {
c.JSON(http.StatusOK, model.Response{
Code: 200,
Message: "success",
Data: model.ListResponse{List: list, Total: int64(len(list))},
Data: model.ListResponse{List: list, Total: int64(len(list))},
})
}
@@ -50,4 +50,4 @@ func (h *SystemTaskHandler) RunSystemTask(c *gin.Context) {
Message: "执行完成",
Data: item,
})
}
}
+5 -5
View File
@@ -105,11 +105,11 @@ func (h *ToolConfigHandler) UpdateTool(c *gin.Context) {
}
var req struct {
DisplayName *string `json:"display_name"`
Description *string `json:"description"`
DisplayName *string `json:"display_name"`
Description *string `json:"description"`
InstallMethod *model.ToolInstallMethod `json:"install_method"`
Enabled *bool `json:"enabled"`
SortOrder *int `json:"sort_order"`
Enabled *bool `json:"enabled"`
SortOrder *int `json:"sort_order"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()})
@@ -356,4 +356,4 @@ func getPresetVersions(toolName string) []map[string]string {
default:
return nil
}
}
}
+21 -21
View File
@@ -34,37 +34,37 @@ type jaegerServicesResp struct {
}
type jaegerTraceResp struct {
Data []jaegerTrace `json:"data"`
Total int `json:"total"`
Data []jaegerTrace `json:"data"`
Total int `json:"total"`
}
type jaegerTrace struct {
TraceID string `json:"traceID"`
Spans []jaegerSpan `json:"spans"`
TraceID string `json:"traceID"`
Spans []jaegerSpan `json:"spans"`
Processes map[string]jaegerProc `json:"processes"`
}
type jaegerSpan struct {
TraceID string `json:"traceID"`
SpanID string `json:"spanID"`
OperationName string `json:"operationName"`
References []jaegerRef `json:"references"`
StartTime int64 `json:"startTime"` // microseconds
Duration int64 `json:"duration"` // microseconds
Tags []jaegerTag `json:"tags"`
ProcessID string `json:"processID"`
Logs []jaegerLog `json:"logs"`
TraceID string `json:"traceID"`
SpanID string `json:"spanID"`
OperationName string `json:"operationName"`
References []jaegerRef `json:"references"`
StartTime int64 `json:"startTime"` // microseconds
Duration int64 `json:"duration"` // microseconds
Tags []jaegerTag `json:"tags"`
ProcessID string `json:"processID"`
Logs []jaegerLog `json:"logs"`
}
type jaegerRef struct {
RefType string `json:"refType"`
TraceID string `json:"traceID"`
SpanID string `json:"spanID"`
RefType string `json:"refType"`
TraceID string `json:"traceID"`
SpanID string `json:"spanID"`
}
type jaegerProc struct {
ServiceName string `json:"serviceName"`
Tags []jaegerTag `json:"tags"`
ServiceName string `json:"serviceName"`
Tags []jaegerTag `json:"tags"`
}
type jaegerTag struct {
@@ -74,8 +74,8 @@ type jaegerTag struct {
}
type jaegerLog struct {
Timestamp int64 `json:"timestamp"`
Fields []jaegerTag `json:"fields"`
Timestamp int64 `json:"timestamp"`
Fields []jaegerTag `json:"fields"`
}
// ---- 前端期望的格式 ----
@@ -115,7 +115,7 @@ type serviceMetric struct {
ServiceName string `json:"serviceName"`
RequestCount int `json:"requestCount"`
ErrorRate float64 `json:"errorRate"`
AvgDuration float64 `json:"avgDuration"` // ms
AvgDuration float64 `json:"avgDuration"` // ms
P95Duration float64 `json:"p95Duration"`
P99Duration float64 `json:"p99Duration"`
}
+25 -14
View File
@@ -4,8 +4,8 @@ import (
"net/http"
"time"
"ezops/middleware"
"ezops/config"
"ezops/middleware"
"ezops/model"
"github.com/gin-gonic/gin"
@@ -62,20 +62,31 @@ func parseUserAgent(ua string) (browser, os string) {
}
// Browser
switch {
case containsAny(ua, "Edg/"): browser = "Edge"
case containsAny(ua, "Chrome"): browser = "Chrome"
case containsAny(ua, "Safari") && !containsAny(ua, "Chrome"): browser = "Safari"
case containsAny(ua, "Firefox"): browser = "Firefox"
case containsAny(ua, "curl"): browser = "curl"
case containsAny(ua, "Python"): browser = "Python"
case containsAny(ua, "Edg/"):
browser = "Edge"
case containsAny(ua, "Chrome"):
browser = "Chrome"
case containsAny(ua, "Safari") && !containsAny(ua, "Chrome"):
browser = "Safari"
case containsAny(ua, "Firefox"):
browser = "Firefox"
case containsAny(ua, "curl"):
browser = "curl"
case containsAny(ua, "Python"):
browser = "Python"
}
// OS
switch {
case containsAny(ua, "Windows"): os = "Windows"
case containsAny(ua, "Mac OS"): os = "macOS"
case containsAny(ua, "Linux") || containsAny(ua, "X11"): os = "Linux"
case containsAny(ua, "Android"): os = "Android"
case containsAny(ua, "iPhone") || containsAny(ua, "iPad"): os = "iOS"
case containsAny(ua, "Windows"):
os = "Windows"
case containsAny(ua, "Mac OS"):
os = "macOS"
case containsAny(ua, "Linux") || containsAny(ua, "X11"):
os = "Linux"
case containsAny(ua, "Android"):
os = "Android"
case containsAny(ua, "iPhone") || containsAny(ua, "iPad"):
os = "iOS"
}
return
}
@@ -363,7 +374,7 @@ func collectUserPermissionCodes(db *gorm.DB, userID uint, isAdmin bool) []string
if isAdmin {
return []string{"*"}
}
// raw SQL: user → iam_user_roles → iam_roles → role_permissions → iam_permissions
// raw SQL: user → iam_user_roles → iam_roles → iam_role_permissions → iam_permissions
// 逐层 JOIN,任一层缺失自然返回空
type permRow struct {
Code string
@@ -373,7 +384,7 @@ func collectUserPermissionCodes(db *gorm.DB, userID uint, isAdmin bool) []string
SELECT DISTINCT p.code
FROM iam_user_roles ur
JOIN iam_roles r ON r.id = ur.role_id AND r.status = 1
JOIN role_permissions rp ON rp.role_id = r.id
JOIN iam_role_permissions rp ON rp.role_id = r.id
JOIN iam_permissions p ON p.id = rp.permission_id AND p.status = 1
WHERE ur.user_id = ?
`, userID).Scan(&rows).Error
+1
View File
@@ -396,6 +396,7 @@ func (h *UserHandler) ListRoles(c *gin.Context) {
Code: 200, Data: model.ListResponse{List: roles, Total: int64(len(roles))},
})
}
// GET /api/v1/admin/users/import-template
func (h *UserHandler) ImportTemplate(c *gin.Context) {
// UTF-8 BOM for Excel compatibility
+4 -2
View File
@@ -273,7 +273,9 @@ func (h *UserHandler) UpdateApiAccessKey(c *gin.Context) {
// ExtendApiAccessKey 延长有效期(兼容旧接口)// Logan.Li
func (h *UserHandler) ExtendApiAccessKey(c *gin.Context) {
userID := middleware.GetUserID(c)
var req struct{ DurationMonths int `json:"duration_months"` }
var req struct {
DurationMonths int `json:"duration_months"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误"})
return
@@ -311,4 +313,4 @@ func (h *UserHandler) RevokeApiAccessKey(c *gin.Context) {
return
}
c.JSON(http.StatusOK, model.Response{Code: 200, Message: "访问密钥已删除"})
}
}
+4 -4
View File
@@ -60,10 +60,10 @@ func newAsciicastRecorder() *asciicastRecorder {
func (r *asciicastRecorder) writeHeader() {
h, _ := json.Marshal(map[string]interface{}{
"version": 2,
"width": 80,
"height": 24,
"timestamp": r.startTime.Unix(),
"version": 2,
"width": 80,
"height": 24,
"timestamp": r.startTime.Unix(),
"aiops_input_recorded": false,
"env": map[string]string{
"SHELL": "/bin/bash",
+3 -3
View File
@@ -9,8 +9,8 @@ import (
"time"
"ezops/middleware"
"ezops/pkg/wshub"
ezredis "ezops/pkg/redis"
"ezops/pkg/wshub"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
@@ -125,7 +125,7 @@ func (h *WSPipelineLogHandler) GetLogHistory(c *gin.Context) {
// 先查 Redis(执行中)
logKey := fmt.Sprintf("pipeline:run:%d:logs", uint(runID))
ctx := c.Request.Context()
raw, _ := h.cache.Get(ctx, logKey)
if raw != "" && !strings.HasPrefix(raw, "[") {
raw = "[]"
@@ -137,7 +137,7 @@ func (h *WSPipelineLogHandler) GetLogHistory(c *gin.Context) {
// 查 DB(已完成)
var logs string
h.db.Table("ops_pipeline_runs").Where("id = ?", uint(runID)).Select("logs").Scan(&logs)
h.db.Table("deploy_pipeline_runs").Where("id = ?", uint(runID)).Select("logs").Scan(&logs)
if logs == "" {
logs = "[]"
}
+36 -12
View File
@@ -113,24 +113,48 @@ func (h *ZabbixDSHandler) Update(c *gin.Context) {
}
updates := map[string]interface{}{}
if req.Name != nil { updates["name"] = *req.Name }
if req.URL != nil { updates["url"] = *req.URL }
if req.Username != nil { updates["username"] = *req.Username }
if req.Password != nil && *req.Password != "" { updates["password"] = *req.Password }
if req.TrendsAfter != nil { updates["trends_after"] = *req.TrendsAfter }
if req.TrendsRange != nil { updates["trends_range"] = *req.TrendsRange }
if req.TrendsCacheTTL != nil { updates["trends_cache_ttl"] = *req.TrendsCacheTTL }
if req.TrendsTimeout != nil { updates["trends_timeout"] = *req.TrendsTimeout }
if req.DirectDB != nil { updates["direct_db"] = *req.DirectDB }
if req.DisableAcknowledges != nil { updates["disable_acknowledges"] = *req.DisableAcknowledges }
if req.DisableDataAlignment != nil { updates["disable_data_alignment"] = *req.DisableDataAlignment }
if req.Name != nil {
updates["name"] = *req.Name
}
if req.URL != nil {
updates["url"] = *req.URL
}
if req.Username != nil {
updates["username"] = *req.Username
}
if req.Password != nil && *req.Password != "" {
updates["password"] = *req.Password
}
if req.TrendsAfter != nil {
updates["trends_after"] = *req.TrendsAfter
}
if req.TrendsRange != nil {
updates["trends_range"] = *req.TrendsRange
}
if req.TrendsCacheTTL != nil {
updates["trends_cache_ttl"] = *req.TrendsCacheTTL
}
if req.TrendsTimeout != nil {
updates["trends_timeout"] = *req.TrendsTimeout
}
if req.DirectDB != nil {
updates["direct_db"] = *req.DirectDB
}
if req.DisableAcknowledges != nil {
updates["disable_acknowledges"] = *req.DisableAcknowledges
}
if req.DisableDataAlignment != nil {
updates["disable_data_alignment"] = *req.DisableDataAlignment
}
if req.IsDefault != nil {
updates["is_default"] = *req.IsDefault
if *req.IsDefault {
h.db.Model(&model.ZabbixDataSource{}).Where("is_default = ? AND id != ?", true, id).Update("is_default", false)
}
}
if req.Status != nil { updates["status"] = *req.Status }
if req.Status != nil {
updates["status"] = *req.Status
}
if len(updates) > 0 {
if err := h.db.Model(&ds).Updates(updates).Error; err != nil {
+16 -16
View File
@@ -28,7 +28,7 @@ type ZabbixHostSummary struct {
Hostname string `json:"hostname"`
Name string `json:"name"`
IP string `json:"ip"`
Available string `json:"available"` // 0=未知 1=可用 2=不可用
Available string `json:"available"` // 0=未知 1=可用 2=不可用
CPUUsage float64 `json:"cpu_usage"`
MemoryUsage float64 `json:"memory_usage"`
DiskUsage float64 `json:"disk_usage"`
@@ -71,7 +71,7 @@ func (h *ZabbixProxyHandler) Connect(c *gin.Context) {
// 获取主机列表(含接口和组信息)
hosts, err := client.GetHosts(ctx, &zabbix.GetHostsParams{
Status: 0, // 只获取被监控的主机
Status: 0, // 只获取被监控的主机
SelectInterfaces: []string{"interfaceid", "hostid", "main", "type", "useip", "ip", "dns", "port"},
SelectGroups: []string{"groupid", "name"},
Output: []string{"hostid", "host", "name", "status", "available", "description"},
@@ -85,17 +85,17 @@ func (h *ZabbixProxyHandler) Connect(c *gin.Context) {
// 为每台主机查询监控项
var summaries []ZabbixHostSummary
itemKeys := []string{
"system.cpu.util[,idle]", // CPU 空闲率
"system.cpu.util", // CPU 使用率(备用)
"vm.memory.size[total]", // 总内存 bytes
"vm.memory.size[available]", // 可用内存 bytes
"vfs.fs.size[/,total]", // 总磁盘 bytes
"vfs.fs.size[/,used]", // 已用磁盘 bytes
"system.cpu.load[all,avg5]", // 5分钟负载
"net.if.in[ens18]", // 网络流入
"net.if.out[ens18]", // 网络流出
"system.cpu.num", // CPU 数量
"system.uptime", // 运行时间
"system.cpu.util[,idle]", // CPU 空闲率
"system.cpu.util", // CPU 使用率(备用)
"vm.memory.size[total]", // 总内存 bytes
"vm.memory.size[available]", // 可用内存 bytes
"vfs.fs.size[/,total]", // 总磁盘 bytes
"vfs.fs.size[/,used]", // 已用磁盘 bytes
"system.cpu.load[all,avg5]", // 5分钟负载
"net.if.in[ens18]", // 网络流入
"net.if.out[ens18]", // 网络流出
"system.cpu.num", // CPU 数量
"system.uptime", // 运行时间
}
for _, host := range hosts {
@@ -185,9 +185,9 @@ func (h *ZabbixProxyHandler) Connect(c *gin.Context) {
Code: 200,
Message: "success",
Data: gin.H{
"version": version,
"hosts": summaries,
"total": len(summaries),
"version": version,
"hosts": summaries,
"total": len(summaries),
},
})
}