deleteservicelogic.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. // udeServer: DeleteService 走事务 —— 同一事务内先删该服务下的 t_directory,
  2. // 再删 t_service。任一步失败全部回滚,不会残留孤儿目录数据。
  3. package logic
  4. import (
  5. "context"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "net/url"
  10. "path"
  11. "strings"
  12. "udeServer/internal/audit"
  13. "udeServer/internal/model"
  14. "udeServer/internal/svc"
  15. "udeServer/internal/types"
  16. "github.com/zeromicro/go-zero/core/logx"
  17. "github.com/zeromicro/go-zero/core/stores/sqlx"
  18. )
  19. type DeleteServiceLogic struct {
  20. logx.Logger
  21. ctx context.Context
  22. svcCtx *svc.ServiceContext
  23. }
  24. func NewDeleteServiceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteServiceLogic {
  25. return &DeleteServiceLogic{
  26. Logger: logx.WithContext(ctx),
  27. ctx: ctx,
  28. svcCtx: svcCtx,
  29. }
  30. }
  31. func (l *DeleteServiceLogic) DeleteService(req *types.ServiceIdReq) (*types.DeleteResp, error) {
  32. if err := checkId(req.Id); err != nil {
  33. return nil, err
  34. }
  35. // 先查出服务实体:删库前要拿 ip/port 去通知外挂程序卸载,删了就查不到了
  36. svc, err := findService(l.ctx, l.svcCtx.ServiceModel, req.Id)
  37. if err != nil {
  38. return nil, err
  39. }
  40. // P1 联动卸载:先卸载后删库。卸载失败软处理(不阻塞删除,外挂机器可能已下线),
  41. // 聚合成 unmountWarning 由前端弹黄色警告。
  42. unmountWarning := l.notifyFuseUnmount(svc)
  43. err = l.svcCtx.DB.Transact(func(session sqlx.Session) error {
  44. dirModel := l.svcCtx.DirectoryModel.WithSession(session)
  45. svcModel := l.svcCtx.ServiceModel.WithSession(session)
  46. if err := dirModel.DeleteByServiceId(l.ctx, req.Id); err != nil {
  47. return fmt.Errorf("delete t_directory of service %d: %w", req.Id, err)
  48. }
  49. if err := svcModel.Delete(l.ctx, req.Id); err != nil {
  50. return fmt.Errorf("delete t_service %d: %w", req.Id, err)
  51. }
  52. return nil
  53. })
  54. if err != nil {
  55. l.Errorf("delete service tx failed: %v", err)
  56. return nil, err
  57. }
  58. resp := &types.DeleteResp{Ok: true}
  59. if unmountWarning != "" {
  60. resp.UnmountWarning = unmountWarning
  61. }
  62. return resp, nil
  63. }
  64. // notifyFuseUnmount 删库前回调外挂程序(svc.Ip:svc.Port)的 GET /api/fuseUnMount 接口,
  65. // 逐目录卸载该服务全部 FUSE 挂载。
  66. // 前置判断:只有挂载状态 mount_status=mounted 的服务才真正调外挂卸载接口;
  67. // unmounted/failed 视为无活动挂载,直接跳过不发请求——避免删除"本来就没挂载"
  68. // 的服务时还要去外挂机器白跑一趟、机器不可达时弹一堆无意义的卸载失败警告。
  69. // 软处理:单个目录失败只记录并聚合,绝不阻塞删除流程(外挂机器可能已关机,
  70. // 服务记录必须还能删)。返回空串 = 全部卸载成功或无需卸载。
  71. func (l *DeleteServiceLogic) notifyFuseUnmount(svc *model.TService) string {
  72. // MountStatus 是 sql.NullString 类型,.String 取其中的字符串值
  73. if svc.MountStatus.String != "mounted" {
  74. return "" // 未挂载/挂载失败,库里明确没有活动挂载,无需通知外挂
  75. }
  76. ip, port := svc.Ip.String, svc.Port // port 已是 int64
  77. if ip == "" || port == 0 {
  78. return "外挂服务 IP/端口为空,无法联动卸载,目录可能仍处于挂载状态"
  79. }
  80. dirs, err := l.svcCtx.DirectoryModel.FindDirsByServiceId(l.ctx, svc.Id)
  81. if err != nil {
  82. return fmt.Sprintf("查询保护目录失败,无法联动卸载: %v", err)
  83. }
  84. if len(dirs) == 0 {
  85. return "" // 没配保护目录,无需卸载
  86. }
  87. baseURL := fmt.Sprintf("http://%s:%d/api/fuseUnMount", ip, port) // %d:port 是 int64
  88. var msgs []string
  89. for _, mount := range dirs {
  90. // path.Clean(非 filepath!):该路径发给远程 Linux 外挂程序,必须保持 / 分隔符
  91. cleanMount := path.Clean(mount)
  92. reqURL, uerr := url.Parse(baseURL)
  93. if uerr != nil {
  94. msgs = append(msgs, fmt.Sprintf("解析 URL 失败: %v", uerr))
  95. continue
  96. }
  97. // q.Encode() 自动做 URL 编码(/ → %2F),外挂侧 Query().Get 自动解码还原
  98. q := reqURL.Query()
  99. q.Set("mount", cleanMount)
  100. reqURL.RawQuery = q.Encode()
  101. l.Infof("fuse unmount forward: GET %s", reqURL.String()) // 打出转发 URL 便于排查
  102. // DoSimple 记录 type=2 接口日志,父 Span 指向本次入站请求(GET 用 url 描述请求原文)
  103. if _, callErr := audit.DoSimple(l.svcCtx.SpanRecorder, l.ctx, "FuseUnMount", reqURL.String(),
  104. audit.BuildRemoteGetRequest(http.MethodGet, reqURL.String()),
  105. func() (map[string]interface{}, int64, error) {
  106. // doFuseRequest 注入 X-TOKEN=svc.Iden(接入标识);client.Get 快捷方式带不了自定义头,裸发会被外挂 401 拒绝
  107. resp, rerr := doFuseRequest(fuseMountClient, svc.Iden.String, http.MethodGet, reqURL.String(), nil, "") // 复用挂载逻辑里的 HTTP 客户端(同包变量)
  108. if rerr != nil {
  109. return nil, 0, fmt.Errorf("卸载目录 %s 失败(外挂程序未启动?): %w", cleanMount, rerr)
  110. }
  111. raw, _ := io.ReadAll(resp.Body) // 读到 EOF 保证 TCP 连接复用 Keep-Alive
  112. resp.Body.Close()
  113. status := int64(resp.StatusCode)
  114. if status >= http.StatusBadRequest {
  115. return nil, status, fmt.Errorf("卸载目录 %s 失败,外挂程序返回 HTTP %d: %s", cleanMount, status, string(raw))
  116. }
  117. return map[string]interface{}{"status": status, "body": string(raw)}, status, nil
  118. }); callErr != nil {
  119. msgs = append(msgs, callErr.Error())
  120. continue
  121. }
  122. l.Infof("fuse unmount ok: %s", cleanMount)
  123. }
  124. if len(msgs) == 0 {
  125. return ""
  126. }
  127. return "服务已删除,但卸载挂载失败: " + strings.Join(msgs, "; ")
  128. }