feat: Ansible Playbook 全栈 CRUD + 真实执行 — 替换mock为后端持久化

后端:
- models/automation.go: Playbook 模型新增 Category/Tags 字段; 新增 CreatePlaybookRequest
- handlers/automation.go: 新增 runPlaybookLocal(写临时YML+ansible-playbook --connection=local执行)
  + randomCode(crypto/rand生成唯一code) + List/Get/Create/Update/Delete/Execute Playbook 完整CRUD
  Execute 创建TaskExecution(task_type=playbook)记录,采集stdout/stderr/退出码/耗时
- routes/routes.go: 注册 /playbooks 路由组(7个端点)

前端:
- services/api.ts: ansibleApi 从mock改为真实 /playbooks 后端调用
- AnsibleManager.tsx 完全重写:
  - Playbook管理: 真实数据卡片列表(id/name/category/tags/run_count/timeout) + 搜索/分类筛选
  - 新建/编辑对话框复用(编辑模式预填数据) — 新增编辑入口(原无编辑功能)
  - 查看内容: 终端风格YAML查看器 + 快捷编辑按钮
  - 执行: ConfirmProvider确认 + ansible-playbook本地执行 + toast结果反馈
  - 执行记录tab: 真实TaskExecution记录(任务名/状态/开始时间/耗时/日志查看)
  - 统计卡片: 总数/执行中/今日成功/今日失败(基于真实执行记录)
  - 移除原inventory占位tab(无后端支持,避免非功能按钮)
  - tags JSON数组与前端string[]互转映射
This commit is contained in:
attacker committed 2026-06-14 23:14:16 +08:00
1 parent 2807e4895b
commit ae6af93360
5 files changed
+769 -416

No files matched your search

+354
View File
@@ -3,8 +3,11 @@ package handlers
import ( import (
"bytes" "bytes"
"context" "context"
"crypto/rand"
"encoding/hex"
"fmt" "fmt"
"net/http" "net/http"
"os"
"os/exec" "os/exec"
"strconv" "strconv"
"time" "time"
@@ -15,6 +18,15 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
// randomCode returns a short unique code for records that require a unique
// string identifier (e.g. playbooks). It combines a unix timestamp with 4
// random hex bytes to guarantee uniqueness even under rapid sequential inserts.
func randomCode(prefix string) string {
b := make([]byte, 4)
_, _ = rand.Read(b)
return fmt.Sprintf("%s-%d-%s", prefix, time.Now().Unix(), hex.EncodeToString(b))
}
// runLocal executes a script or shell command locally on the AIOps host and // runLocal executes a script or shell command locally on the AIOps host and
// returns the combined stdout+stderr output, the process exit code (0 = success) // returns the combined stdout+stderr output, the process exit code (0 = success)
// and the wall-clock duration in milliseconds. A timeout prevents runaway jobs. // and the wall-clock duration in milliseconds. A timeout prevents runaway jobs.
@@ -711,3 +723,345 @@ func (h *AutomationHandler) ListExecutions(c *gin.Context) {
}, },
}) })
} }
// runPlaybookLocal executes an Ansible playbook YAML locally on the AIOps host.
// It writes the content to a temporary file and invokes `ansible-playbook`
// against localhost with a local connection. If the ansible-playbook binary is
// missing the exec error is captured in the output. Returns combined
// stdout+stderr, the exit code (-1 on failure) and duration in milliseconds.
func runPlaybookLocal(content, inventory string, timeoutSec int) (output string, exitCode int, durationMs int) {
start := time.Now()
timeout := time.Duration(timeoutSec) * time.Second
if timeout <= 0 {
timeout = 600 * time.Second
}
// Write the playbook YAML to a temporary file.
tmpFile, err := os.CreateTemp("", "ezops-playbook-*.yml")
if err != nil {
return fmt.Sprintf("创建临时文件失败: %v", err), -1, 0
}
defer os.Remove(tmpFile.Name())
if _, err := tmpFile.WriteString(content); err != nil {
tmpFile.Close()
return fmt.Sprintf("写入临时文件失败: %v", err), -1, 0
}
tmpFile.Close()
// Write an optional inventory file.
inventoryArg := "localhost,"
if inventory != "" {
invFile, err := os.CreateTemp("", "ezops-inventory-*.ini")
if err == nil {
if _, werr := invFile.WriteString(inventory); werr == nil {
inventoryArg = invFile.Name()
defer os.Remove(invFile.Name())
}
invFile.Close()
}
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
args := []string{"-i", inventoryArg}
if inventoryArg == "localhost," {
args = append(args, "--connection=local")
}
args = append(args, tmpFile.Name())
cmd := exec.CommandContext(ctx, "ansible-playbook", args...)
var out bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &out
runErr := cmd.Run()
durationMs = int(time.Since(start).Milliseconds())
output = out.String()
if ctx.Err() == context.DeadlineExceeded {
output += fmt.Sprintf("\n[超时] 执行超过 %d 秒被终止", timeoutSec)
return output, -1, durationMs
}
if runErr != nil {
if exitError, ok := runErr.(*exec.ExitError); ok {
exitCode = exitError.ExitCode()
} else {
// Binary not found or other exec error (e.g. ansible-playbook not
// installed). Provide a clear hint instead of an empty output.
exitCode = -1
if output == "" {
output = fmt.Sprintf("无法执行 ansible-playbook:%v\n(请确认 AIOps 主机已安装 ansible:yum install -y ansible / pip install ansible)", runErr)
}
}
return output, exitCode, durationMs
}
return output, 0, durationMs
}
// ListPlaybooks 获取Playbook列表
// @Summary 获取Playbook列表
// @Description 获取所有Ansible Playbook列表
// @Tags 自动化运维
// @Produce json
// @Security Bearer
// @Param page query int false "页码"
// @Param page_size query int false "每页数量"
// @Success 200 {object} models.Response{data=models.ListResponse}
// @Router /playbooks [get]
func (h *AutomationHandler) ListPlaybooks(c *gin.Context) {
var query models.PageQuery
c.ShouldBindQuery(&query)
var total int64
h.db.Model(&models.Playbook{}).Count(&total)
var playbooks []models.Playbook
h.db.Order("created_at DESC").Offset(query.GetOffset()).Limit(query.GetLimit()).Find(&playbooks)
c.JSON(http.StatusOK, models.Response{
Code: 200,
Message: "success",
Data: models.ListResponse{
List: playbooks,
Total: total,
},
})
}
// GetPlaybook 获取Playbook详情
// @Summary 获取Playbook详情
// @Description 获取指定Playbook的详细信息
// @Tags 自动化运维
// @Produce json
// @Security Bearer
// @Param id path int true "Playbook ID"
// @Success 200 {object} models.Response{data=models.Playbook}
// @Router /playbooks/{id} [get]
func (h *AutomationHandler) GetPlaybook(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
var playbook models.Playbook
if err := h.db.First(&playbook, id).Error; err != nil {
c.JSON(http.StatusNotFound, models.Response{
Code: 404,
Message: "Playbook不存在",
})
return
}
c.JSON(http.StatusOK, models.Response{
Code: 200,
Message: "success",
Data: playbook,
})
}
// CreatePlaybook 创建Playbook
// @Summary 创建Playbook
// @Description 创建新的Ansible Playbook
// @Tags 自动化运维
// @Accept json
// @Produce json
// @Security Bearer
// @Param request body models.CreatePlaybookRequest true "创建请求"
// @Success 200 {object} models.Response{data=models.Playbook}
// @Router /playbooks [post]
func (h *AutomationHandler) CreatePlaybook(c *gin.Context) {
var req models.CreatePlaybookRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, models.Response{
Code: 400,
Message: "请求参数错误: " + err.Error(),
})
return
}
playbook := models.Playbook{
Name: req.Name,
Code: randomCode("pb"),
Description: req.Description,
Content: req.Content,
Category: req.Category,
Tags: req.Tags,
Variables: req.Variables,
Inventory: req.Inventory,
Timeout: req.Timeout,
}
if playbook.Category == "" {
playbook.Category = "deployment"
}
if playbook.Timeout == 0 {
playbook.Timeout = 600
}
if err := h.db.Create(&playbook).Error; err != nil {
c.JSON(http.StatusInternalServerError, models.Response{
Code: 500,
Message: "创建失败: " + err.Error(),
})
return
}
c.JSON(http.StatusOK, models.Response{
Code: 200,
Message: "创建成功",
Data: playbook,
})
}
// UpdatePlaybook 更新Playbook
// @Summary 更新Playbook
// @Description 更新指定Playbook
// @Tags 自动化运维
// @Accept json
// @Produce json
// @Security Bearer
// @Param id path int true "Playbook ID"
// @Param request body models.CreatePlaybookRequest true "更新请求"
// @Success 200 {object} models.Response{data=models.Playbook}
// @Router /playbooks/{id} [put]
func (h *AutomationHandler) UpdatePlaybook(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
var req models.CreatePlaybookRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, models.Response{
Code: 400,
Message: "请求参数错误: " + err.Error(),
})
return
}
var playbook models.Playbook
if err := h.db.First(&playbook, id).Error; err != nil {
c.JSON(http.StatusNotFound, models.Response{
Code: 404,
Message: "Playbook不存在",
})
return
}
updates := map[string]interface{}{
"name": req.Name,
"description": req.Description,
"content": req.Content,
"category": req.Category,
"tags": req.Tags,
"variables": req.Variables,
"inventory": req.Inventory,
"timeout": req.Timeout,
}
if err := h.db.Model(&playbook).Updates(updates).Error; err != nil {
c.JSON(http.StatusInternalServerError, models.Response{
Code: 500,
Message: "更新失败",
})
return
}
h.db.First(&playbook, id)
c.JSON(http.StatusOK, models.Response{
Code: 200,
Message: "更新成功",
Data: playbook,
})
}
// DeletePlaybook 删除Playbook
// @Summary 删除Playbook
// @Description 删除指定Playbook
// @Tags 自动化运维
// @Produce json
// @Security Bearer
// @Param id path int true "Playbook ID"
// @Success 200 {object} models.Response
// @Router /playbooks/{id} [delete]
func (h *AutomationHandler) DeletePlaybook(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
if err := h.db.Delete(&models.Playbook{}, id).Error; err != nil {
c.JSON(http.StatusInternalServerError, models.Response{
Code: 500,
Message: "删除失败",
})
return
}
c.JSON(http.StatusOK, models.Response{
Code: 200,
Message: "删除成功",
})
}
// ExecutePlaybook 执行Playbook
// @Summary 执行Playbook
// @Description 在AIOps主机上本地执行Ansible Playbook
// @Tags 自动化运维
// @Accept json
// @Produce json
// @Security Bearer
// @Param id path int true "Playbook ID"
// @Success 200 {object} models.Response{data=models.TaskExecution}
// @Router /playbooks/{id}/execute [post]
func (h *AutomationHandler) ExecutePlaybook(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
var playbook models.Playbook
if err := h.db.First(&playbook, id).Error; err != nil {
c.JSON(http.StatusNotFound, models.Response{
Code: 404,
Message: "Playbook不存在",
})
return
}
now := time.Now()
execution := models.TaskExecution{
TaskType: "playbook",
TaskID: uint(id),
TaskName: playbook.Name,
Status: "running",
StartedAt: &now,
}
if err := h.db.Create(&execution).Error; err != nil {
c.JSON(http.StatusInternalServerError, models.Response{
Code: 500,
Message: "创建执行记录失败",
})
return
}
// Execute the playbook locally on the AIOps host.
output, exitCode, duration := runPlaybookLocal(playbook.Content, playbook.Inventory, playbook.Timeout)
finishedAt := time.Now()
status := "success"
if exitCode != 0 {
status = "failed"
}
h.db.Model(&execution).Updates(map[string]interface{}{
"status": status,
"output": output,
"duration": duration,
"finished_at": finishedAt,
})
h.db.Model(&playbook).UpdateColumn("run_count", playbook.RunCount+1)
execution.Output = output
execution.Status = status
execution.Duration = duration
execution.FinishedAt = &finishedAt
msg := "执行成功"
if status == "failed" {
msg = "执行失败"
}
c.JSON(http.StatusOK, models.Response{
Code: 200,
Message: msg,
Data: execution,
})
}
+10
View File
@@ -261,6 +261,16 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config) {
scripts.POST("/:id/execute", automationHandler.ExecuteScript) scripts.POST("/:id/execute", automationHandler.ExecuteScript)
} }
playbooks := authorized.Group("/playbooks")
{
playbooks.GET("", automationHandler.ListPlaybooks)
playbooks.POST("", automationHandler.CreatePlaybook)
playbooks.GET("/:id", automationHandler.GetPlaybook)
playbooks.PUT("/:id", automationHandler.UpdatePlaybook)
playbooks.DELETE("/:id", automationHandler.DeletePlaybook)
playbooks.POST("/:id/execute", automationHandler.ExecutePlaybook)
}
// 任务执行记录(脚本/定时任务执行历史) // 任务执行记录(脚本/定时任务执行历史)
authorized.GET("/task-executions", automationHandler.ListExecutions) authorized.GET("/task-executions", automationHandler.ListExecutions)
+14
View File
@@ -93,6 +93,8 @@ type Playbook struct {
Code string `gorm:"size:64;uniqueIndex;not null" json:"code"` Code string `gorm:"size:64;uniqueIndex;not null" json:"code"`
Description string `gorm:"size:500" json:"description"` Description string `gorm:"size:500" json:"description"`
Content string `gorm:"type:text;not null" json:"content"` Content string `gorm:"type:text;not null" json:"content"`
Category string `gorm:"size:64" json:"category"`
Tags string `gorm:"type:text" json:"tags"` // JSON 数组字符串,如 ["deploy","docker"]
Variables string `gorm:"type:text" json:"variables"` Variables string `gorm:"type:text" json:"variables"`
Inventory string `gorm:"type:text" json:"inventory"` Inventory string `gorm:"type:text" json:"inventory"`
Timeout int `gorm:"default:600" json:"timeout"` Timeout int `gorm:"default:600" json:"timeout"`
@@ -109,6 +111,18 @@ func (Playbook) TableName() string {
return "playbooks" return "playbooks"
} }
// CreatePlaybookRequest 创建Playbook请求
type CreatePlaybookRequest struct {
Name string `json:"name" binding:"required"`
Description string `json:"description"`
Content string `json:"content" binding:"required"`
Category string `json:"category"`
Tags string `json:"tags"` // JSON 数组字符串
Variables string `json:"variables"`
Inventory string `json:"inventory"`
Timeout int `json:"timeout"`
}
// CreateCronJobRequest 创建定时任务请求 // CreateCronJobRequest 创建定时任务请求
type CreateCronJobRequest struct { type CreateCronJobRequest struct {
Name string `json:"name" binding:"required"` Name string `json:"name" binding:"required"`
File diff suppressed because it is too large. Load diff
+19 -7
View File
@@ -531,14 +531,26 @@ export const sqlAuditApi = {
toggleRule: async (ruleId: string, enabled: boolean) => ({ success: true }), toggleRule: async (ruleId: string, enabled: boolean) => ({ success: true }),
}; };
// Ansible API(无后端) // Ansible Playbook API(后端 /playbooks)
export const ansibleApi = { export const ansibleApi = {
getPlaybooks: async () => ({ data: mockData.ansiblePlaybooks as any }), getPlaybooks: async (params?: { page?: number; page_size?: number }) => {
getJobs: async () => ({ data: mockData.ansibleJobs as any }), return http.get<ListResponse>('/playbooks', params);
getInventories: async () => ({ data: mockData.ansibleInventories as any }), },
createPlaybook: async (data: any) => ({ success: true, data: { id: Date.now().toString() } }), getPlaybook: async (id: number | string) => {
deletePlaybook: async (id: string) => ({ success: true }), return http.get(`/playbooks/${id}`);
executePlaybook: async (id: string, config: any) => ({ success: true, data: { jobId: Date.now().toString() } }), },
createPlaybook: async (data: any) => {
return http.post('/playbooks', data);
},
updatePlaybook: async (id: number | string, data: any) => {
return http.put(`/playbooks/${id}`, data);
},
deletePlaybook: async (id: number | string) => {
return http.delete(`/playbooks/${id}`);
},
executePlaybook: async (id: number | string) => {
return http.post(`/playbooks/${id}/execute`);
},
}; };
// Logs API(无后端) // Logs API(无后端)