server.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. package httpserver
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "strings"
  9. "time"
  10. "quickip/internal/auth"
  11. "quickip/internal/config"
  12. "quickip/internal/deviceinfo"
  13. "quickip/internal/logger"
  14. "quickip/internal/model"
  15. applyexecsvc "quickip/internal/network/applyexec"
  16. configreadersvc "quickip/internal/network/configreader"
  17. interfacesvc "quickip/internal/network/interfaces"
  18. netplansvc "quickip/internal/network/netplan"
  19. validatorsvc "quickip/internal/network/validator"
  20. verifysvc "quickip/internal/network/verify"
  21. "quickip/internal/tasks"
  22. )
  23. type Server struct {
  24. cfg config.Config
  25. log *logger.Logger
  26. deviceSvc *deviceinfo.Service
  27. interfaceSvc *interfacesvc.Service
  28. configSvc *configreadersvc.Service
  29. validatorSvc *validatorsvc.Service
  30. netplanSvc *netplansvc.Service
  31. applySvc *applyexecsvc.Service
  32. verifySvc *verifysvc.Service
  33. taskSvc *tasks.Service
  34. }
  35. func New(cfg config.Config, log *logger.Logger, deviceSvc *deviceinfo.Service, interfaceSvc *interfacesvc.Service, configSvc *configreadersvc.Service, validatorSvc *validatorsvc.Service, netplanSvc *netplansvc.Service, applySvc *applyexecsvc.Service, verifySvc *verifysvc.Service, taskSvc *tasks.Service) *Server {
  36. return &Server{cfg: cfg, log: log, deviceSvc: deviceSvc, interfaceSvc: interfaceSvc, configSvc: configSvc, validatorSvc: validatorSvc, netplanSvc: netplanSvc, applySvc: applySvc, verifySvc: verifySvc, taskSvc: taskSvc}
  37. }
  38. func (s *Server) Run(ctx context.Context) error {
  39. mux := http.NewServeMux()
  40. mux.Handle("/api/health", auth.Middleware(s.cfg, http.HandlerFunc(s.handleHealth)))
  41. mux.Handle("/api/device/info", auth.Middleware(s.cfg, http.HandlerFunc(s.handleDeviceInfo)))
  42. mux.Handle("/api/network/interfaces", auth.Middleware(s.cfg, http.HandlerFunc(s.handleInterfaces)))
  43. mux.Handle("/api/network/config", auth.Middleware(s.cfg, http.HandlerFunc(s.handleConfig)))
  44. mux.Handle("/api/network/validate", auth.Middleware(s.cfg, http.HandlerFunc(s.handleValidate)))
  45. mux.Handle("/api/network/apply", auth.Middleware(s.cfg, http.HandlerFunc(s.handleApply)))
  46. mux.Handle("/api/network/rollback", auth.Middleware(s.cfg, http.HandlerFunc(s.handleRollback)))
  47. mux.Handle("/api/tasks/", auth.Middleware(s.cfg, http.HandlerFunc(s.handleTaskGet)))
  48. handler := s.withAccessLog(mux)
  49. server := &http.Server{
  50. Addr: fmt.Sprintf("%s:%d", s.cfg.HTTPHost, s.cfg.HTTPPort),
  51. Handler: handler,
  52. ReadHeaderTimeout: 5 * time.Second,
  53. }
  54. go func() {
  55. <-ctx.Done()
  56. shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  57. defer cancel()
  58. _ = server.Shutdown(shutdownCtx)
  59. }()
  60. s.log.Info("http server listening", "addr", server.Addr)
  61. err := server.ListenAndServe()
  62. if err == http.ErrServerClosed {
  63. return nil
  64. }
  65. return err
  66. }
  67. func (s *Server) withAccessLog(next http.Handler) http.Handler {
  68. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  69. started := time.Now()
  70. rw := &statusRecorder{ResponseWriter: w, statusCode: http.StatusOK}
  71. next.ServeHTTP(rw, r)
  72. s.log.Info(
  73. "http request completed",
  74. "method", r.Method,
  75. "path", r.URL.Path,
  76. "query", r.URL.RawQuery,
  77. "remote", r.RemoteAddr,
  78. "status", rw.statusCode,
  79. "duration_ms", time.Since(started).Milliseconds(),
  80. )
  81. })
  82. }
  83. type statusRecorder struct {
  84. http.ResponseWriter
  85. statusCode int
  86. }
  87. func (r *statusRecorder) WriteHeader(statusCode int) {
  88. r.statusCode = statusCode
  89. r.ResponseWriter.WriteHeader(statusCode)
  90. }
  91. func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) {
  92. writeJSON(w, http.StatusOK, model.APIResponse{Code: 0, Message: "成功", Data: map[string]any{"status": "运行中", "agent_version": s.cfg.AgentVersion}})
  93. }
  94. func (s *Server) handleDeviceInfo(w http.ResponseWriter, _ *http.Request) {
  95. writeJSON(w, http.StatusOK, model.APIResponse{Code: 0, Message: "成功", Data: s.deviceSvc.Get()})
  96. }
  97. func (s *Server) handleInterfaces(w http.ResponseWriter, _ *http.Request) {
  98. data, err := s.interfaceSvc.List()
  99. if err != nil {
  100. writeJSON(w, http.StatusInternalServerError, model.APIResponse{Code: 4001, Message: "系统执行失败", Data: map[string]string{"error": err.Error()}})
  101. return
  102. }
  103. writeJSON(w, http.StatusOK, model.APIResponse{Code: 0, Message: "成功", Data: data})
  104. }
  105. func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) {
  106. interfaceName := r.URL.Query().Get("interface")
  107. if interfaceName == "" {
  108. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 2001, Message: "参数错误", Data: map[string][]string{"errors": []string{"缺少 interface 参数。"}}})
  109. return
  110. }
  111. if !s.interfaceExists(interfaceName) {
  112. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 2001, Message: "参数错误", Data: map[string][]string{"errors": []string{"目标接口不存在。"}}})
  113. return
  114. }
  115. data, err := s.configSvc.Read(interfaceName)
  116. if err != nil {
  117. writeJSON(w, http.StatusInternalServerError, model.APIResponse{Code: 4001, Message: "系统执行失败", Data: map[string]string{"error": err.Error()}})
  118. return
  119. }
  120. writeJSON(w, http.StatusOK, model.APIResponse{Code: 0, Message: "成功", Data: data})
  121. }
  122. func (s *Server) handleValidate(w http.ResponseWriter, r *http.Request) {
  123. if r.Method != http.MethodPost {
  124. writeJSON(w, http.StatusMethodNotAllowed, model.APIResponse{Code: 2002, Message: "资源不存在", Data: nil})
  125. return
  126. }
  127. body, err := io.ReadAll(r.Body)
  128. if err != nil {
  129. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 2001, Message: "参数错误", Data: map[string][]string{"errors": []string{"请求体读取失败。"}}})
  130. return
  131. }
  132. var input model.InterfaceConfig
  133. if err := json.Unmarshal(body, &input); err != nil {
  134. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 2001, Message: "参数错误", Data: map[string][]string{"errors": []string{"请求体格式不正确。"}}})
  135. return
  136. }
  137. if input.Interface != "" && !s.interfaceExists(input.Interface) {
  138. result := model.ValidateResponse{Valid: false, Errors: []string{"目标接口不存在。"}, Warnings: []string{}}
  139. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 3001, Message: "配置校验失败", Data: result})
  140. return
  141. }
  142. result := s.validatorSvc.Validate(input)
  143. if !result.Valid {
  144. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 3001, Message: "配置校验失败", Data: result})
  145. return
  146. }
  147. writeJSON(w, http.StatusOK, model.APIResponse{Code: 0, Message: "校验通过", Data: result})
  148. }
  149. func (s *Server) handleApply(w http.ResponseWriter, r *http.Request) {
  150. if r.Method != http.MethodPost {
  151. writeJSON(w, http.StatusMethodNotAllowed, model.APIResponse{Code: 2002, Message: "资源不存在", Data: nil})
  152. return
  153. }
  154. var input model.InterfaceConfig
  155. if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
  156. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 2001, Message: "参数错误", Data: map[string][]string{"errors": []string{"请求体格式不正确。"}}})
  157. return
  158. }
  159. if !s.interfaceExists(input.Interface) {
  160. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 3001, Message: "配置校验失败", Data: model.ValidateResponse{Valid: false, Errors: []string{"目标接口不存在。"}}})
  161. return
  162. }
  163. result := s.validatorSvc.Validate(input)
  164. if !result.Valid {
  165. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 3001, Message: "配置校验失败", Data: result})
  166. return
  167. }
  168. management := s.currentManagementInterface()
  169. if management == "" {
  170. writeJSON(w, http.StatusInternalServerError, model.APIResponse{Code: 4001, Message: "系统执行失败", Data: map[string][]string{"errors": []string{"未能识别管理接口。"}}})
  171. return
  172. }
  173. task := s.taskSvc.Create()
  174. go s.runApplyTask(task.TaskID, input, management)
  175. writeJSON(w, http.StatusOK, model.APIResponse{Code: 0, Message: "配置任务已提交", Data: map[string]any{"interface": input.Interface, "task_id": task.TaskID}})
  176. }
  177. func (s *Server) handleRollback(w http.ResponseWriter, r *http.Request) {
  178. if r.Method != http.MethodPost {
  179. writeJSON(w, http.StatusMethodNotAllowed, model.APIResponse{Code: 2002, Message: "资源不存在", Data: nil})
  180. return
  181. }
  182. var input model.RollbackRequest
  183. if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
  184. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 2001, Message: "参数错误", Data: map[string][]string{"errors": {"请求体格式不正确。"}}})
  185. return
  186. }
  187. filePath, err := s.netplanSvc.FindSingleFile()
  188. if err != nil {
  189. writeJSON(w, http.StatusInternalServerError, model.APIResponse{Code: 4001, Message: "系统执行失败", Data: map[string]string{"error": err.Error()}})
  190. return
  191. }
  192. backupPath := filePath + ".quickip.bak"
  193. if err := s.netplanSvc.Restore(filePath, backupPath); err != nil {
  194. writeJSON(w, http.StatusInternalServerError, model.APIResponse{Code: 3004, Message: "回滚失败", Data: map[string]string{"error": err.Error()}})
  195. return
  196. }
  197. if err := s.applySvc.Apply(); err != nil {
  198. writeJSON(w, http.StatusInternalServerError, model.APIResponse{Code: 3004, Message: "回滚失败", Data: map[string]string{"error": err.Error()}})
  199. return
  200. }
  201. writeJSON(w, http.StatusOK, model.APIResponse{Code: 0, Message: "回滚成功", Data: map[string]any{"interface": input.Interface, "rolled_back": true}})
  202. }
  203. func (s *Server) handleTaskGet(w http.ResponseWriter, r *http.Request) {
  204. taskID := strings.TrimPrefix(r.URL.Path, "/api/tasks/")
  205. if taskID == "" {
  206. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 2001, Message: "参数错误", Data: map[string][]string{"errors": []string{"缺少 task_id。"}}})
  207. return
  208. }
  209. item, ok := s.taskSvc.Get(taskID)
  210. if !ok {
  211. writeJSON(w, http.StatusNotFound, model.APIResponse{Code: 2002, Message: "资源不存在", Data: nil})
  212. return
  213. }
  214. writeJSON(w, http.StatusOK, model.APIResponse{Code: 0, Message: "成功", Data: item})
  215. }
  216. func (s *Server) runApplyTask(taskID string, input model.InterfaceConfig, managementInterface string) {
  217. s.taskSvc.Update(taskID, "running", "validating", "正在校验配置。", false)
  218. result := s.validatorSvc.Validate(input)
  219. if !result.Valid {
  220. s.taskSvc.Update(taskID, "failed", "validating", "配置校验失败。", false)
  221. return
  222. }
  223. filePath, err := s.netplanSvc.FindSingleFile()
  224. if err != nil {
  225. s.taskSvc.Update(taskID, "failed", "writing_netplan", err.Error(), false)
  226. return
  227. }
  228. s.taskSvc.Update(taskID, "running", "writing_netplan", "正在写入 netplan 配置。", false)
  229. backupPath, err := s.netplanSvc.Backup(filePath)
  230. if err != nil {
  231. s.taskSvc.Update(taskID, "failed", "writing_netplan", err.Error(), false)
  232. return
  233. }
  234. if err := s.netplanSvc.Write(filePath, input.Interface, input, managementInterface, s.cfg.MaintenanceCIDR); err != nil {
  235. s.taskSvc.Update(taskID, "failed", "writing_netplan", err.Error(), false)
  236. return
  237. }
  238. s.taskSvc.Update(taskID, "running", "applying", "正在应用 netplan 配置。", false)
  239. if err := s.applySvc.Apply(); err != nil {
  240. _ = s.netplanSvc.Restore(filePath, backupPath)
  241. _ = s.applySvc.Apply()
  242. s.taskSvc.Update(taskID, "rolled_back", "rolling_back", "配置失败,已自动回滚。", true)
  243. return
  244. }
  245. s.taskSvc.Update(taskID, "running", "verifying", "正在验证配置结果。", false)
  246. if err := s.verifySvc.Verify(input); err != nil {
  247. _ = s.netplanSvc.Restore(filePath, backupPath)
  248. _ = s.applySvc.Apply()
  249. s.taskSvc.Update(taskID, "rolled_back", "rolling_back", "配置失败,已自动回滚。", true)
  250. return
  251. }
  252. s.taskSvc.Update(taskID, "success", "completed", "目标接口配置已成功应用。", false)
  253. }
  254. func (s *Server) interfaceExists(name string) bool {
  255. data, err := s.interfaceSvc.List()
  256. if err != nil {
  257. return false
  258. }
  259. for _, item := range data.Interfaces {
  260. if item.SystemName == name {
  261. return true
  262. }
  263. }
  264. return false
  265. }
  266. func (s *Server) currentManagementInterface() string {
  267. data, err := s.interfaceSvc.List()
  268. if err != nil {
  269. return ""
  270. }
  271. return data.ManagementInterface
  272. }
  273. func writeJSON(w http.ResponseWriter, status int, payload model.APIResponse) {
  274. w.Header().Set("Content-Type", "application/json")
  275. w.WriteHeader(status)
  276. _ = json.NewEncoder(w).Encode(payload)
  277. }