112 wiersze
2.8 KiB
Go
112 wiersze
2.8 KiB
Go
package main
|
|
|
|
import (
|
|
"flag"
|
|
"log"
|
|
"os"
|
|
|
|
"github.com/ansible-deploy/internal/handlers"
|
|
"github.com/ansible-deploy/internal/services"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
var (
|
|
configPath string
|
|
port string
|
|
)
|
|
|
|
func init() {
|
|
flag.StringVar(&configPath, "config", "config/config.yaml", "配置文件路径")
|
|
flag.StringVar(&port, "port", "8080", "服务端口")
|
|
}
|
|
|
|
func main() {
|
|
flag.Parse()
|
|
|
|
// 加载配置
|
|
cfg, err := services.LoadConfig(configPath)
|
|
if err != nil {
|
|
log.Printf("配置加载失败: %v,使用默认配置", err)
|
|
cfg = services.DefaultConfig()
|
|
}
|
|
|
|
// 初始化Ansible服务
|
|
ansibleService := services.NewAnsibleService(cfg)
|
|
|
|
// 初始化处理器
|
|
h := handlers.NewAnsibleHandler(ansibleService)
|
|
|
|
// 初始化Web服务
|
|
r := gin.Default()
|
|
|
|
// CORS配置
|
|
r.Use(func(c *gin.Context) {
|
|
c.Header("Access-Control-Allow-Origin", "*")
|
|
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
|
c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
|
if c.Request.Method == "OPTIONS" {
|
|
c.AbortWithStatus(204)
|
|
return
|
|
}
|
|
c.Next()
|
|
})
|
|
|
|
// 静态文件
|
|
r.Static("/static", "./web/dist")
|
|
r.Static("/assets", "./web/dist/assets")
|
|
|
|
// API路由
|
|
api := r.Group("/api")
|
|
{
|
|
// 主机管理
|
|
api.GET("/hosts", h.ListHosts)
|
|
api.POST("/hosts", h.AddHost)
|
|
api.DELETE("/hosts/:id", h.DeleteHost)
|
|
api.PUT("/hosts/:id", h.UpdateHost)
|
|
api.POST("/hosts/test/:id", h.TestConnection)
|
|
|
|
// 主机组管理
|
|
api.GET("/groups", h.ListGroups)
|
|
api.POST("/groups", h.CreateGroup)
|
|
api.DELETE("/groups/:name", h.DeleteGroup)
|
|
api.PUT("/groups/:name", h.UpdateGroup)
|
|
|
|
// Playbook管理
|
|
api.GET("/playbooks", h.ListPlaybooks)
|
|
api.POST("/playbooks", h.CreatePlaybook)
|
|
api.GET("/playbooks/:name/content", h.GetPlaybookContent)
|
|
api.PUT("/playbooks/:name", h.UpdatePlaybook)
|
|
api.DELETE("/playbooks/:name", h.DeletePlaybook)
|
|
api.POST("/playbooks/execute", h.ExecutePlaybook)
|
|
api.GET("/playbooks/:name", h.GetPlaybook)
|
|
|
|
// 命令执行
|
|
api.POST("/command/execute", h.ExecuteCommand)
|
|
api.POST("/command/batch", h.BatchExecute)
|
|
|
|
// 任务执行
|
|
api.GET("/tasks", h.ListTasks)
|
|
api.GET("/tasks/:id", h.GetTask)
|
|
api.GET("/tasks/:id/stream", h.StreamTaskOutput)
|
|
api.DELETE("/tasks/:id", h.CancelTask)
|
|
}
|
|
|
|
// 前端路由 - 禁止缓存确保始终返回最新版本
|
|
r.GET("/", func(c *gin.Context) {
|
|
c.Header("Cache-Control", "no-cache, no-store, must-revalidate")
|
|
c.Header("Pragma", "no-cache")
|
|
c.Header("Expires", "0")
|
|
c.File("./web/dist/index.html")
|
|
})
|
|
|
|
// 创建必要目录
|
|
os.MkdirAll(cfg.InventoryDir, 0755)
|
|
os.MkdirAll(cfg.PlaybookDir, 0755)
|
|
os.MkdirAll(cfg.LogDir, 0755)
|
|
|
|
log.Printf("Ansible部署工具启动,监听端口: %s", port)
|
|
if err := r.Run(":" + port); err != nil {
|
|
log.Fatalf("服务启动失败: %v", err)
|
|
}
|
|
}
|