server.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. package httpserver
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net"
  8. "net/http"
  9. "os"
  10. "strings"
  11. "sync"
  12. "time"
  13. "networktool/internal/auth"
  14. "networktool/internal/config"
  15. "networktool/internal/deviceinfo"
  16. "networktool/internal/logger"
  17. "networktool/internal/model"
  18. applyexecsvc "networktool/internal/network/applyexec"
  19. configreadersvc "networktool/internal/network/configreader"
  20. interfacesvc "networktool/internal/network/interfaces"
  21. netplansvc "networktool/internal/network/netplan"
  22. validatorsvc "networktool/internal/network/validator"
  23. "networktool/internal/systemaction"
  24. "networktool/internal/tasks"
  25. )
  26. type Server struct {
  27. cfg config.Config
  28. log *logger.Logger
  29. deviceSvc *deviceinfo.Service
  30. interfaceSvc *interfacesvc.Service
  31. configSvc *configreadersvc.Service
  32. validatorSvc *validatorsvc.Service
  33. netplanSvc *netplansvc.Service
  34. applySvc *applyexecsvc.Service
  35. taskSvc *tasks.Service
  36. systemSvc *systemaction.Service
  37. confirmMu sync.Mutex
  38. applyControls map[string]applyControl
  39. }
  40. type applyControl struct {
  41. confirm chan struct{}
  42. cancel chan struct{}
  43. }
  44. const applyConfirmationTimeout = 20 * time.Second
  45. 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, taskSvc *tasks.Service, systemSvc *systemaction.Service) *Server {
  46. return &Server{cfg: cfg, log: log, deviceSvc: deviceSvc, interfaceSvc: interfaceSvc, configSvc: configSvc, validatorSvc: validatorSvc, netplanSvc: netplanSvc, applySvc: applySvc, taskSvc: taskSvc, systemSvc: systemSvc, applyControls: make(map[string]applyControl)}
  47. }
  48. func (s *Server) Run(ctx context.Context) error {
  49. mux := http.NewServeMux()
  50. mux.Handle("/api/health", auth.Middleware(s.cfg, http.HandlerFunc(s.handleHealth)))
  51. mux.Handle("/api/device/info", auth.Middleware(s.cfg, http.HandlerFunc(s.handleDeviceInfo)))
  52. mux.Handle("/api/network/interfaces", auth.Middleware(s.cfg, http.HandlerFunc(s.handleInterfaces)))
  53. mux.Handle("/api/network/config", auth.Middleware(s.cfg, http.HandlerFunc(s.handleConfig)))
  54. mux.Handle("/api/network/validate", auth.Middleware(s.cfg, http.HandlerFunc(s.handleValidate)))
  55. mux.Handle("/api/network/validate-all", auth.Middleware(s.cfg, http.HandlerFunc(s.handleValidateAll)))
  56. mux.Handle("/api/network/apply", auth.Middleware(s.cfg, http.HandlerFunc(s.handleApply)))
  57. mux.Handle("/api/network/apply-all", auth.Middleware(s.cfg, http.HandlerFunc(s.handleApplyAll)))
  58. mux.Handle("/api/network/apply/confirm", auth.Middleware(s.cfg, http.HandlerFunc(s.handleApplyConfirm)))
  59. mux.Handle("/api/network/apply/cancel", auth.Middleware(s.cfg, http.HandlerFunc(s.handleApplyCancel)))
  60. mux.Handle("/api/network/rollback", auth.Middleware(s.cfg, http.HandlerFunc(s.handleRollback)))
  61. mux.Handle("/api/system/reboot", auth.Middleware(s.cfg, http.HandlerFunc(s.handleReboot)))
  62. mux.Handle("/api/system/shutdown", auth.Middleware(s.cfg, http.HandlerFunc(s.handleShutdown)))
  63. mux.Handle("/api/tasks/", auth.Middleware(s.cfg, http.HandlerFunc(s.handleTaskGet)))
  64. handler := s.withAccessLog(mux)
  65. server := &http.Server{
  66. Addr: fmt.Sprintf("%s:%d", s.cfg.HTTPHost, s.cfg.HTTPPort),
  67. Handler: handler,
  68. ReadHeaderTimeout: 5 * time.Second,
  69. }
  70. go func() {
  71. <-ctx.Done()
  72. shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  73. defer cancel()
  74. _ = server.Shutdown(shutdownCtx)
  75. }()
  76. s.log.Info("http server listening", "addr", server.Addr)
  77. err := server.ListenAndServe()
  78. if err == http.ErrServerClosed {
  79. return nil
  80. }
  81. return err
  82. }
  83. func (s *Server) handleApplyConfirm(w http.ResponseWriter, r *http.Request) {
  84. if r.Method != http.MethodPost {
  85. writeJSON(w, http.StatusMethodNotAllowed, model.APIResponse{Code: 2002, Message: "资源不存在", Data: nil})
  86. return
  87. }
  88. var input model.ConfirmApplyRequest
  89. if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
  90. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 2001, Message: "参数错误", Data: map[string][]string{"errors": []string{"请求体格式不正确。"}}})
  91. return
  92. }
  93. if input.TaskID == "" {
  94. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 2001, Message: "参数错误", Data: map[string][]string{"errors": []string{"缺少 task_id。"}}})
  95. return
  96. }
  97. if !s.confirmApply(input.TaskID) {
  98. writeJSON(w, http.StatusNotFound, model.APIResponse{Code: 2002, Message: "资源不存在", Data: nil})
  99. return
  100. }
  101. writeJSON(w, http.StatusOK, model.APIResponse{Code: 0, Message: "已确认保留配置", Data: map[string]any{"task_id": input.TaskID, "confirmed": true}})
  102. }
  103. func (s *Server) handleApplyCancel(w http.ResponseWriter, r *http.Request) {
  104. if r.Method != http.MethodPost {
  105. writeJSON(w, http.StatusMethodNotAllowed, model.APIResponse{Code: 2002, Message: "资源不存在", Data: nil})
  106. return
  107. }
  108. var input model.ConfirmApplyRequest
  109. if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
  110. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 2001, Message: "参数错误", Data: map[string][]string{"errors": []string{"请求体格式不正确。"}}})
  111. return
  112. }
  113. if input.TaskID == "" {
  114. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 2001, Message: "参数错误", Data: map[string][]string{"errors": []string{"缺少 task_id。"}}})
  115. return
  116. }
  117. if !s.cancelApply(input.TaskID) {
  118. writeJSON(w, http.StatusNotFound, model.APIResponse{Code: 2002, Message: "资源不存在", Data: nil})
  119. return
  120. }
  121. writeJSON(w, http.StatusOK, model.APIResponse{Code: 0, Message: "已取消保留配置,正在回滚", Data: map[string]any{"task_id": input.TaskID, "cancelled": true}})
  122. }
  123. func (s *Server) withAccessLog(next http.Handler) http.Handler {
  124. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  125. started := time.Now()
  126. rw := &statusRecorder{ResponseWriter: w, statusCode: http.StatusOK}
  127. next.ServeHTTP(rw, r)
  128. s.log.Info(
  129. "http request completed",
  130. "method", r.Method,
  131. "path", r.URL.Path,
  132. "query", r.URL.RawQuery,
  133. "remote", r.RemoteAddr,
  134. "status", rw.statusCode,
  135. "duration_ms", time.Since(started).Milliseconds(),
  136. )
  137. })
  138. }
  139. type statusRecorder struct {
  140. http.ResponseWriter
  141. statusCode int
  142. }
  143. func (r *statusRecorder) WriteHeader(statusCode int) {
  144. r.statusCode = statusCode
  145. r.ResponseWriter.WriteHeader(statusCode)
  146. }
  147. func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) {
  148. writeJSON(w, http.StatusOK, model.APIResponse{Code: 0, Message: "成功", Data: map[string]any{"status": "运行中", "server_version": s.cfg.ServerVersion}})
  149. }
  150. func (s *Server) handleDeviceInfo(w http.ResponseWriter, _ *http.Request) {
  151. writeJSON(w, http.StatusOK, model.APIResponse{Code: 0, Message: "成功", Data: s.deviceSvc.Get()})
  152. }
  153. func (s *Server) handleInterfaces(w http.ResponseWriter, _ *http.Request) {
  154. data, err := s.interfaceSvc.List()
  155. if err != nil {
  156. writeJSON(w, http.StatusInternalServerError, model.APIResponse{Code: 4001, Message: "系统执行失败", Data: map[string]string{"error": err.Error()}})
  157. return
  158. }
  159. writeJSON(w, http.StatusOK, model.APIResponse{Code: 0, Message: "成功", Data: data})
  160. }
  161. func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) {
  162. interfaceName := r.URL.Query().Get("interface")
  163. if interfaceName == "" {
  164. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 2001, Message: "参数错误", Data: map[string][]string{"errors": []string{"缺少 interface 参数。"}}})
  165. return
  166. }
  167. if !s.interfaceExists(interfaceName) {
  168. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 2001, Message: "参数错误", Data: map[string][]string{"errors": []string{"目标接口不存在。"}}})
  169. return
  170. }
  171. data, err := s.configSvc.Read(interfaceName)
  172. if err != nil {
  173. writeJSON(w, http.StatusInternalServerError, model.APIResponse{Code: 4001, Message: "系统执行失败", Data: map[string]string{"error": err.Error()}})
  174. return
  175. }
  176. writeJSON(w, http.StatusOK, model.APIResponse{Code: 0, Message: "成功", Data: data})
  177. }
  178. func (s *Server) handleValidate(w http.ResponseWriter, r *http.Request) {
  179. if r.Method != http.MethodPost {
  180. writeJSON(w, http.StatusMethodNotAllowed, model.APIResponse{Code: 2002, Message: "资源不存在", Data: nil})
  181. return
  182. }
  183. body, err := io.ReadAll(r.Body)
  184. if err != nil {
  185. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 2001, Message: "参数错误", Data: map[string][]string{"errors": []string{"请求体读取失败。"}}})
  186. return
  187. }
  188. var input model.InterfaceConfig
  189. if err := json.Unmarshal(body, &input); err != nil {
  190. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 2001, Message: "参数错误", Data: map[string][]string{"errors": []string{"请求体格式不正确。"}}})
  191. return
  192. }
  193. if input.Interface != "" && !s.interfaceExists(input.Interface) {
  194. result := model.ValidateResponse{Valid: false, Errors: []string{"目标接口不存在。"}, Warnings: []string{}}
  195. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 3001, Message: "配置校验失败", Data: result})
  196. return
  197. }
  198. result := s.validatorSvc.Validate(input)
  199. s.addManagementAddressWarning(&result, input)
  200. if !result.Valid {
  201. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 3001, Message: "配置校验失败", Data: result})
  202. return
  203. }
  204. writeJSON(w, http.StatusOK, model.APIResponse{Code: 0, Message: "校验通过", Data: result})
  205. }
  206. func (s *Server) handleValidateAll(w http.ResponseWriter, r *http.Request) {
  207. if r.Method != http.MethodPost {
  208. writeJSON(w, http.StatusMethodNotAllowed, model.APIResponse{Code: 2002, Message: "资源不存在", Data: nil})
  209. return
  210. }
  211. var input model.InterfaceConfigsRequest
  212. if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
  213. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 2001, Message: "参数错误", Data: map[string][]string{"errors": []string{"请求体格式不正确。"}}})
  214. return
  215. }
  216. result := s.validateConfigs(input.Configs)
  217. if !result.Valid {
  218. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 3001, Message: "配置校验失败", Data: result})
  219. return
  220. }
  221. writeJSON(w, http.StatusOK, model.APIResponse{Code: 0, Message: "校验通过", Data: result})
  222. }
  223. func (s *Server) handleApply(w http.ResponseWriter, r *http.Request) {
  224. if r.Method != http.MethodPost {
  225. writeJSON(w, http.StatusMethodNotAllowed, model.APIResponse{Code: 2002, Message: "资源不存在", Data: nil})
  226. return
  227. }
  228. if !hasRootPrivileges() {
  229. writeJSON(w, http.StatusForbidden, model.APIResponse{Code: 4001, Message: "系统执行失败", Data: map[string][]string{"errors": []string{"Server 未以 root 身份运行,无法写入 netplan 或执行 netplan apply。"}}})
  230. return
  231. }
  232. var input model.InterfaceConfig
  233. if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
  234. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 2001, Message: "参数错误", Data: map[string][]string{"errors": []string{"请求体格式不正确。"}}})
  235. return
  236. }
  237. if !s.interfaceExists(input.Interface) {
  238. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 3001, Message: "配置校验失败", Data: model.ValidateResponse{Valid: false, Errors: []string{"目标接口不存在。"}}})
  239. return
  240. }
  241. result := s.validatorSvc.Validate(input)
  242. if !result.Valid {
  243. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 3001, Message: "配置校验失败", Data: result})
  244. return
  245. }
  246. management := s.currentManagementInterface()
  247. if management == "" {
  248. writeJSON(w, http.StatusInternalServerError, model.APIResponse{Code: 4001, Message: "系统执行失败", Data: map[string][]string{"errors": []string{"未能识别管理接口。"}}})
  249. return
  250. }
  251. task := s.taskSvc.Create()
  252. go s.runApplyTask(task.TaskID, input, management)
  253. writeJSON(w, http.StatusOK, model.APIResponse{Code: 0, Message: "配置任务已提交", Data: map[string]any{"interface": input.Interface, "task_id": task.TaskID}})
  254. }
  255. func (s *Server) handleApplyAll(w http.ResponseWriter, r *http.Request) {
  256. if r.Method != http.MethodPost {
  257. writeJSON(w, http.StatusMethodNotAllowed, model.APIResponse{Code: 2002, Message: "资源不存在", Data: nil})
  258. return
  259. }
  260. if !hasRootPrivileges() {
  261. writeJSON(w, http.StatusForbidden, model.APIResponse{Code: 4001, Message: "系统执行失败", Data: map[string][]string{"errors": []string{"Server 未以 root 身份运行,无法写入 netplan 或执行 netplan apply。"}}})
  262. return
  263. }
  264. var input model.InterfaceConfigsRequest
  265. if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
  266. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 2001, Message: "参数错误", Data: map[string][]string{"errors": []string{"请求体格式不正确。"}}})
  267. return
  268. }
  269. result := s.validateConfigs(input.Configs)
  270. if !result.Valid {
  271. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 3001, Message: "配置校验失败", Data: result})
  272. return
  273. }
  274. management := s.currentManagementInterface()
  275. if management == "" {
  276. writeJSON(w, http.StatusInternalServerError, model.APIResponse{Code: 4001, Message: "系统执行失败", Data: map[string][]string{"errors": []string{"未能识别管理接口。"}}})
  277. return
  278. }
  279. task := s.taskSvc.Create()
  280. go s.runApplyAllTask(task.TaskID, input.Configs, management)
  281. writeJSON(w, http.StatusOK, model.APIResponse{Code: 0, Message: "配置任务已提交", Data: map[string]any{"task_id": task.TaskID}})
  282. }
  283. func (s *Server) handleRollback(w http.ResponseWriter, r *http.Request) {
  284. if r.Method != http.MethodPost {
  285. writeJSON(w, http.StatusMethodNotAllowed, model.APIResponse{Code: 2002, Message: "资源不存在", Data: nil})
  286. return
  287. }
  288. if !hasRootPrivileges() {
  289. writeJSON(w, http.StatusForbidden, model.APIResponse{Code: 4001, Message: "系统执行失败", Data: map[string][]string{"errors": []string{"Server 未以 root 身份运行,无法恢复 netplan 或执行 netplan apply。"}}})
  290. return
  291. }
  292. var input model.RollbackRequest
  293. if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
  294. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 2001, Message: "参数错误", Data: map[string][]string{"errors": []string{"请求体格式不正确。"}}})
  295. return
  296. }
  297. filePath, err := s.netplanSvc.FindSingleFile()
  298. if err != nil {
  299. writeJSON(w, http.StatusInternalServerError, model.APIResponse{Code: 4001, Message: "系统执行失败", Data: map[string]string{"error": err.Error()}})
  300. return
  301. }
  302. backupPath := filePath + ".networktool.bak"
  303. if err := s.netplanSvc.Restore(filePath, backupPath); err != nil {
  304. writeJSON(w, http.StatusInternalServerError, model.APIResponse{Code: 3004, Message: "回滚失败", Data: map[string]string{"error": err.Error()}})
  305. return
  306. }
  307. if err := s.applySvc.Apply(); err != nil {
  308. writeJSON(w, http.StatusInternalServerError, model.APIResponse{Code: 3004, Message: "回滚失败", Data: map[string]string{"error": err.Error()}})
  309. return
  310. }
  311. writeJSON(w, http.StatusOK, model.APIResponse{Code: 0, Message: "回滚成功", Data: map[string]any{"interface": input.Interface, "rolled_back": true}})
  312. }
  313. func (s *Server) handleTaskGet(w http.ResponseWriter, r *http.Request) {
  314. taskID := strings.TrimPrefix(r.URL.Path, "/api/tasks/")
  315. if taskID == "" {
  316. writeJSON(w, http.StatusBadRequest, model.APIResponse{Code: 2001, Message: "参数错误", Data: map[string][]string{"errors": []string{"缺少 task_id。"}}})
  317. return
  318. }
  319. item, ok := s.taskSvc.Get(taskID)
  320. if !ok {
  321. writeJSON(w, http.StatusNotFound, model.APIResponse{Code: 2002, Message: "资源不存在", Data: nil})
  322. return
  323. }
  324. writeJSON(w, http.StatusOK, model.APIResponse{Code: 0, Message: "成功", Data: item})
  325. }
  326. func (s *Server) handleReboot(w http.ResponseWriter, r *http.Request) {
  327. s.handleSystemAction(w, r, "reboot")
  328. }
  329. func (s *Server) handleShutdown(w http.ResponseWriter, r *http.Request) {
  330. s.handleSystemAction(w, r, "shutdown")
  331. }
  332. func (s *Server) handleSystemAction(w http.ResponseWriter, r *http.Request, action string) {
  333. if r.Method != http.MethodPost {
  334. writeJSON(w, http.StatusMethodNotAllowed, model.APIResponse{Code: 2002, Message: "资源不存在", Data: nil})
  335. return
  336. }
  337. if !hasRootPrivileges() {
  338. writeJSON(w, http.StatusForbidden, model.APIResponse{Code: 4001, Message: "系统执行失败", Data: map[string][]string{"errors": []string{"Server 未以 root 身份运行,无法执行重启或关机。"}}})
  339. return
  340. }
  341. task := s.taskSvc.Create()
  342. go s.runSystemTask(task.TaskID, action)
  343. message := "系统任务已提交"
  344. if action == "reboot" {
  345. message = "重启任务已提交"
  346. } else if action == "shutdown" {
  347. message = "关机任务已提交"
  348. }
  349. writeJSON(w, http.StatusOK, model.APIResponse{Code: 0, Message: message, Data: map[string]any{"action": action, "task_id": task.TaskID}})
  350. }
  351. func (s *Server) runApplyTask(taskID string, input model.InterfaceConfig, managementInterface string) {
  352. s.taskSvc.Update(taskID, "running", "validating", "正在校验配置。", false)
  353. result := s.validatorSvc.Validate(input)
  354. if !result.Valid {
  355. s.taskSvc.Update(taskID, "failed", "validating", "配置校验失败。", false)
  356. return
  357. }
  358. filePath, err := s.netplanSvc.FindSingleFile()
  359. if err != nil {
  360. s.taskSvc.Update(taskID, "failed", "writing_netplan", err.Error(), false)
  361. return
  362. }
  363. s.taskSvc.Update(taskID, "running", "writing_netplan", "正在写入 netplan 配置。", false)
  364. backupPath, err := s.netplanSvc.Backup(filePath)
  365. if err != nil {
  366. s.taskSvc.Update(taskID, "failed", "writing_netplan", err.Error(), false)
  367. return
  368. }
  369. s.log.Info("preparing to write netplan", "task_id", taskID, "file", filePath, "target_interface", input.Interface, "addresses", formatAddresses(input), "routes", formatRoutes(input), "dns", strings.Join(input.DNS, ","))
  370. if err := s.netplanSvc.Write(filePath, input.Interface, input, managementInterface, s.cfg.MaintenanceCIDR); err != nil {
  371. s.taskSvc.Update(taskID, "failed", "writing_netplan", err.Error(), false)
  372. return
  373. }
  374. if writtenData, err := os.ReadFile(filePath); err != nil {
  375. s.log.Error("failed to read netplan after write", "task_id", taskID, "file", filePath, "error", err.Error())
  376. } else {
  377. s.log.Info("netplan written", "task_id", taskID, "file", filePath, "content", string(writtenData))
  378. }
  379. control := s.registerApplyControl(taskID)
  380. defer s.unregisterApplyControl(taskID)
  381. s.taskSvc.Update(taskID, "running", "applying", "正在应用 netplan 配置。", false)
  382. if err := s.applySvc.Apply(); err != nil {
  383. s.log.Error("netplan apply failed, restoring netplan file", "task_id", taskID, "file", filePath, "error", err.Error())
  384. _ = s.netplanSvc.Restore(filePath, backupPath)
  385. _ = s.applySvc.Apply()
  386. s.logNetplanFile(taskID, filePath, "netplan restored after apply failure")
  387. s.taskSvc.Update(taskID, "rolled_back", "rolling_back", fmt.Sprintf("应用 netplan 失败,已自动回滚:%v", err), true)
  388. return
  389. }
  390. s.taskSvc.Update(taskID, "running", "confirming", fmt.Sprintf("配置已应用,请在 %d 秒内确认保留;未确认将自动回滚。", int(applyConfirmationTimeout.Seconds())), false)
  391. select {
  392. case <-control.confirm:
  393. _ = os.Remove(backupPath)
  394. s.taskSvc.Update(taskID, "success", "completed", "配置已应用并由客户端确认保留。", false)
  395. return
  396. case <-control.cancel:
  397. s.rollbackAppliedConfig(taskID, filePath, backupPath, "用户取消保留配置")
  398. return
  399. case <-time.After(applyConfirmationTimeout):
  400. s.rollbackAppliedConfig(taskID, filePath, backupPath, "客户端未在限定时间内确认保留配置")
  401. return
  402. }
  403. }
  404. func (s *Server) runApplyAllTask(taskID string, inputs []model.InterfaceConfig, managementInterface string) {
  405. s.taskSvc.Update(taskID, "running", "validating", "正在校验配置。", false)
  406. result := s.validateConfigs(inputs)
  407. if !result.Valid {
  408. s.taskSvc.Update(taskID, "failed", "validating", "配置校验失败。", false)
  409. return
  410. }
  411. filePath, err := s.netplanSvc.FindSingleFile()
  412. if err != nil {
  413. s.taskSvc.Update(taskID, "failed", "writing_netplan", err.Error(), false)
  414. return
  415. }
  416. s.taskSvc.Update(taskID, "running", "writing_netplan", "正在写入 netplan 配置。", false)
  417. backupPath, err := s.netplanSvc.Backup(filePath)
  418. if err != nil {
  419. s.taskSvc.Update(taskID, "failed", "writing_netplan", err.Error(), false)
  420. return
  421. }
  422. if err := s.netplanSvc.WriteMany(filePath, inputs, managementInterface, s.cfg.MaintenanceCIDR); err != nil {
  423. s.taskSvc.Update(taskID, "failed", "writing_netplan", err.Error(), false)
  424. return
  425. }
  426. if writtenData, err := os.ReadFile(filePath); err != nil {
  427. s.log.Error("failed to read netplan after write", "task_id", taskID, "file", filePath, "error", err.Error())
  428. } else {
  429. s.log.Info("netplan written", "task_id", taskID, "file", filePath, "content", string(writtenData))
  430. }
  431. control := s.registerApplyControl(taskID)
  432. defer s.unregisterApplyControl(taskID)
  433. s.taskSvc.Update(taskID, "running", "applying", "正在应用 netplan 配置。", false)
  434. if err := s.applySvc.Apply(); err != nil {
  435. s.log.Error("netplan apply failed, restoring netplan file", "task_id", taskID, "file", filePath, "error", err.Error())
  436. _ = s.netplanSvc.Restore(filePath, backupPath)
  437. _ = s.applySvc.Apply()
  438. s.logNetplanFile(taskID, filePath, "netplan restored after apply failure")
  439. s.taskSvc.Update(taskID, "rolled_back", "rolling_back", fmt.Sprintf("应用 netplan 失败,已自动回滚:%v", err), true)
  440. return
  441. }
  442. s.taskSvc.Update(taskID, "running", "confirming", fmt.Sprintf("配置已应用,请在 %d 秒内确认保留;未确认将自动回滚。", int(applyConfirmationTimeout.Seconds())), false)
  443. select {
  444. case <-control.confirm:
  445. _ = os.Remove(backupPath)
  446. s.taskSvc.Update(taskID, "success", "completed", "配置已应用并由客户端确认保留。", false)
  447. return
  448. case <-control.cancel:
  449. s.rollbackAppliedConfig(taskID, filePath, backupPath, "用户取消保留配置")
  450. return
  451. case <-time.After(applyConfirmationTimeout):
  452. s.rollbackAppliedConfig(taskID, filePath, backupPath, "客户端未在限定时间内确认保留配置")
  453. return
  454. }
  455. }
  456. func (s *Server) validateConfigs(inputs []model.InterfaceConfig) model.ValidateResponse {
  457. result := model.ValidateResponse{Valid: true, Warnings: []string{}, Errors: []string{}}
  458. if len(inputs) == 0 {
  459. result.Valid = false
  460. result.Errors = append(result.Errors, "接口配置不能为空。")
  461. return result
  462. }
  463. seen := make(map[string]struct{})
  464. defaultRouteInterfaces := make([]string, 0, 1)
  465. managementInterface := s.currentManagementInterface()
  466. for _, input := range inputs {
  467. name := strings.TrimSpace(input.Interface)
  468. if name == "" {
  469. result.Valid = false
  470. result.Errors = append(result.Errors, "目标接口不能为空。")
  471. continue
  472. }
  473. if _, ok := seen[name]; ok {
  474. result.Valid = false
  475. result.Errors = append(result.Errors, fmt.Sprintf("接口重复:%s", name))
  476. continue
  477. }
  478. seen[name] = struct{}{}
  479. if !s.interfaceExists(name) {
  480. result.Valid = false
  481. result.Errors = append(result.Errors, fmt.Sprintf("目标接口不存在:%s", name))
  482. continue
  483. }
  484. if hasDefaultRouteConfig(input) {
  485. defaultRouteInterfaces = append(defaultRouteInterfaces, name)
  486. }
  487. item := s.validatorSvc.Validate(input)
  488. if name == managementInterface {
  489. addManagementAddressWarning(&item, input)
  490. }
  491. if !item.Valid {
  492. result.Valid = false
  493. }
  494. for _, err := range item.Errors {
  495. result.Errors = append(result.Errors, fmt.Sprintf("%s:%s", name, err))
  496. }
  497. for _, warning := range item.Warnings {
  498. result.Warnings = append(result.Warnings, fmt.Sprintf("%s:%s", name, warning))
  499. }
  500. }
  501. if len(defaultRouteInterfaces) > 1 {
  502. result.Valid = false
  503. result.Errors = append(result.Errors, fmt.Sprintf("只能有一个网口配置默认网关,当前检测到多个默认网关:%s。", strings.Join(defaultRouteInterfaces, "、")))
  504. }
  505. return result
  506. }
  507. func hasDefaultRouteConfig(input model.InterfaceConfig) bool {
  508. if input.Dhcp4 {
  509. return false
  510. }
  511. for _, route := range input.Routes {
  512. if strings.TrimSpace(route.To) == "default" && strings.TrimSpace(route.Via) != "" {
  513. return true
  514. }
  515. }
  516. return false
  517. }
  518. func (s *Server) addManagementAddressWarning(result *model.ValidateResponse, input model.InterfaceConfig) {
  519. managementInterface := s.currentManagementInterface()
  520. if managementInterface == "" || strings.TrimSpace(input.Interface) != managementInterface {
  521. return
  522. }
  523. addManagementAddressWarning(result, input)
  524. }
  525. func addManagementAddressWarning(result *model.ValidateResponse, input model.InterfaceConfig) {
  526. if hasLinkLocalAddress(input) {
  527. return
  528. }
  529. result.Warnings = append(result.Warnings, "直连接口未配置 169.254 链路本地地址,可能导致客户端无法通过维护链路发现或连接设备。")
  530. }
  531. func hasLinkLocalAddress(input model.InterfaceConfig) bool {
  532. addresses := input.Addresses
  533. if len(addresses) == 0 && strings.TrimSpace(input.IP) != "" {
  534. addresses = []model.InterfaceAddressConfig{{IP: strings.TrimSpace(input.IP), Prefix: input.Prefix}}
  535. }
  536. for _, address := range addresses {
  537. ip := net.ParseIP(strings.TrimSpace(address.IP))
  538. if ip == nil {
  539. continue
  540. }
  541. ipv4 := ip.To4()
  542. if ipv4 != nil && ipv4[0] == 169 && ipv4[1] == 254 {
  543. return true
  544. }
  545. }
  546. return false
  547. }
  548. func (s *Server) rollbackAppliedConfig(taskID string, filePath string, backupPath string, reason string) {
  549. s.log.Warn("apply confirmation failed, restoring netplan file", "task_id", taskID, "file", filePath, "reason", reason)
  550. _ = s.netplanSvc.Restore(filePath, backupPath)
  551. _ = s.applySvc.Apply()
  552. s.logNetplanFile(taskID, filePath, "netplan restored after confirmation failure")
  553. s.taskSvc.Update(taskID, "rolled_back", "rolling_back", fmt.Sprintf("%s,已自动回滚。", reason), true)
  554. }
  555. func (s *Server) registerApplyControl(taskID string) applyControl {
  556. control := applyControl{confirm: make(chan struct{}, 1), cancel: make(chan struct{}, 1)}
  557. s.confirmMu.Lock()
  558. s.applyControls[taskID] = control
  559. s.confirmMu.Unlock()
  560. return control
  561. }
  562. func (s *Server) unregisterApplyControl(taskID string) {
  563. s.confirmMu.Lock()
  564. delete(s.applyControls, taskID)
  565. s.confirmMu.Unlock()
  566. }
  567. func (s *Server) confirmApply(taskID string) bool {
  568. s.confirmMu.Lock()
  569. control, ok := s.applyControls[taskID]
  570. s.confirmMu.Unlock()
  571. if !ok {
  572. return false
  573. }
  574. select {
  575. case control.confirm <- struct{}{}:
  576. default:
  577. }
  578. return true
  579. }
  580. func (s *Server) cancelApply(taskID string) bool {
  581. s.confirmMu.Lock()
  582. control, ok := s.applyControls[taskID]
  583. s.confirmMu.Unlock()
  584. if !ok {
  585. return false
  586. }
  587. select {
  588. case control.cancel <- struct{}{}:
  589. default:
  590. }
  591. return true
  592. }
  593. func (s *Server) logNetplanFile(taskID string, filePath string, message string) {
  594. data, err := os.ReadFile(filePath)
  595. if err != nil {
  596. s.log.Error("failed to read netplan file for logging", "task_id", taskID, "file", filePath, "error", err.Error())
  597. return
  598. }
  599. s.log.Info(message, "task_id", taskID, "file", filePath, "content", string(data))
  600. }
  601. func (s *Server) runSystemTask(taskID string, action string) {
  602. detail := "正在发送系统指令。"
  603. if action == "reboot" {
  604. detail = "正在发送重启指令。"
  605. } else if action == "shutdown" {
  606. detail = "正在发送关机指令。"
  607. }
  608. s.taskSvc.Update(taskID, "running", "executing", detail, false)
  609. var err error
  610. switch action {
  611. case "reboot":
  612. err = s.systemSvc.Reboot()
  613. case "shutdown":
  614. err = s.systemSvc.Shutdown()
  615. default:
  616. err = fmt.Errorf("unsupported system action: %s", action)
  617. }
  618. if err != nil {
  619. s.log.Error("system action failed", "action", action, "error", err.Error())
  620. s.taskSvc.Update(taskID, "failed", "executing", err.Error(), false)
  621. return
  622. }
  623. completedDetail := "系统指令已发送。"
  624. if action == "reboot" {
  625. completedDetail = "系统重启指令已发送。"
  626. } else if action == "shutdown" {
  627. completedDetail = "系统关机指令已发送。"
  628. }
  629. s.taskSvc.Update(taskID, "success", "completed", completedDetail, false)
  630. }
  631. func (s *Server) interfaceExists(name string) bool {
  632. data, err := s.interfaceSvc.List()
  633. if err != nil {
  634. return false
  635. }
  636. for _, item := range data.Interfaces {
  637. if item.SystemName == name {
  638. return true
  639. }
  640. }
  641. return false
  642. }
  643. func (s *Server) currentManagementInterface() string {
  644. data, err := s.interfaceSvc.List()
  645. if err != nil {
  646. return ""
  647. }
  648. return data.ManagementInterface
  649. }
  650. func writeJSON(w http.ResponseWriter, status int, payload model.APIResponse) {
  651. w.Header().Set("Content-Type", "application/json")
  652. w.WriteHeader(status)
  653. _ = json.NewEncoder(w).Encode(payload)
  654. }
  655. func hasRootPrivileges() bool {
  656. return os.Geteuid() == 0
  657. }
  658. func formatAddresses(input model.InterfaceConfig) string {
  659. addresses := input.Addresses
  660. if len(addresses) == 0 && strings.TrimSpace(input.IP) != "" {
  661. addresses = []model.InterfaceAddressConfig{{IP: input.IP, Prefix: input.Prefix}}
  662. }
  663. items := make([]string, 0, len(addresses))
  664. for _, address := range addresses {
  665. items = append(items, fmt.Sprintf("%s/%d", strings.TrimSpace(address.IP), address.Prefix))
  666. }
  667. return strings.Join(items, ",")
  668. }
  669. func formatRoutes(input model.InterfaceConfig) string {
  670. routes := input.Routes
  671. if len(routes) == 0 && strings.TrimSpace(input.Gateway) != "" {
  672. routes = []model.InterfaceRouteConfig{{To: "default", Via: input.Gateway}}
  673. }
  674. items := make([]string, 0, len(routes))
  675. for _, route := range routes {
  676. items = append(items, fmt.Sprintf("%s via %s", strings.TrimSpace(route.To), strings.TrimSpace(route.Via)))
  677. }
  678. return strings.Join(items, ",")
  679. }