deleteservicelogic.go 4.9 KB

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