deleteservicelogic.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  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. // 任一目录卸载失败(外挂不可达/返回错误)都中止删除,失败原因原样返回给前端,
  42. // 避免服务记录删了、挂载还挂在外挂机上成为无人管理的孤儿挂载。
  43. unmountErr := l.notifyFuseUnmount(svc)
  44. if unmountErr != "" {
  45. return nil, fmt.Errorf("删除已中止,请先解决挂载卸载问题后重试: %s", unmountErr)
  46. }
  47. err = l.svcCtx.DB.Transact(func(session sqlx.Session) error {
  48. dirModel := l.svcCtx.DirectoryModel.WithSession(session)
  49. svcModel := l.svcCtx.ServiceModel.WithSession(session)
  50. if err := dirModel.DeleteByServiceId(l.ctx, req.Id); err != nil {
  51. return fmt.Errorf("delete t_directory of service %d: %w", req.Id, err)
  52. }
  53. if err := svcModel.Delete(l.ctx, req.Id); err != nil {
  54. return fmt.Errorf("delete t_service %d: %w", req.Id, err)
  55. }
  56. return nil
  57. })
  58. if err != nil {
  59. l.Errorf("delete service tx failed: %v", err)
  60. return nil, err
  61. }
  62. return &types.DeleteResp{Ok: true}, nil
  63. }
  64. // notifyFuseUnmount 删库前回调外挂程序(svc.Ip:svc.Port)的 GET /api/fuseUnMount 接口,
  65. func (l *DeleteServiceLogic) notifyFuseUnmount(svc *model.TService) string {
  66. // MountStatus 是 sql.NullString 类型,.String 取其中的字符串值
  67. if svc.MountStatus.String != "mounted" {
  68. return "" // 未挂载/挂载失败,库里明确没有活动挂载,无需通知外挂
  69. }
  70. ip, port := svc.Ip.String, svc.Port // port 已是 int64
  71. if ip == "" || port == 0 {
  72. return "外挂服务 IP/端口为空,无法联动卸载,目录可能仍处于挂载状态"
  73. }
  74. dirs, err := l.svcCtx.DirectoryModel.FindDirsByServiceId(l.ctx, svc.Id)
  75. if err != nil {
  76. return fmt.Sprintf("查询保护目录失败,无法联动卸载: %v", err)
  77. }
  78. if len(dirs) == 0 {
  79. return "" // 没配保护目录,无需卸载
  80. }
  81. baseURL := fmt.Sprintf("http://%s:%d/api/fuseUnMount", ip, port) // %d:port 是 int64
  82. var msgs []string
  83. for _, mount := range dirs {
  84. // path.Clean(非 filepath!):该路径发给远程 Linux 外挂程序,必须保持 / 分隔符
  85. cleanMount := path.Clean(mount)
  86. reqURL, uerr := url.Parse(baseURL)
  87. if uerr != nil {
  88. msgs = append(msgs, fmt.Sprintf("解析 URL 失败: %v", uerr))
  89. continue
  90. }
  91. // q.Encode() 自动做 URL 编码(/ → %2F),外挂侧 Query().Get 自动解码还原
  92. q := reqURL.Query()
  93. q.Set("mount", cleanMount)
  94. reqURL.RawQuery = q.Encode()
  95. l.Infof("fuse unmount forward: GET %s", reqURL.String()) // 打出转发 URL 便于排查
  96. // DoSimple 记录 type=2 接口日志,父 Span 指向本次入站请求(GET 用 url 描述请求原文)
  97. if _, callErr := audit.DoSimple(l.svcCtx.SpanRecorder, l.ctx, "FuseUnMount", reqURL.String(),
  98. audit.BuildRemoteGetRequest(http.MethodGet, reqURL.String()),
  99. func() (map[string]interface{}, int64, error) {
  100. // doFuseRequest 注入 X-TOKEN(按 iden 换算的 apiSecret);client.Get 快捷方式带不了自定义头,裸发会被外挂 401 拒绝
  101. resp, rerr := doFuseRequest(l.ctx, l.svcCtx, fuseMountClient, svc.Iden.String, http.MethodGet, reqURL.String(), nil, "") // 复用挂载逻辑里的 HTTP 客户端(同包变量)
  102. if rerr != nil {
  103. return nil, 0, fmt.Errorf("卸载目录 %s 失败(外挂程序未启动?): %w", cleanMount, rerr)
  104. }
  105. raw, _ := io.ReadAll(resp.Body) // 读到 EOF 保证 TCP 连接复用 Keep-Alive
  106. resp.Body.Close()
  107. status := int64(resp.StatusCode)
  108. if status >= http.StatusBadRequest {
  109. return nil, status, fmt.Errorf("卸载目录 %s 失败,外挂程序返回 HTTP %d: %s", cleanMount, status, string(raw))
  110. }
  111. return map[string]interface{}{"status": status, "body": string(raw)}, status, nil
  112. }); callErr != nil {
  113. msgs = append(msgs, callErr.Error())
  114. continue
  115. }
  116. l.Infof("fuse unmount ok: %s", cleanMount)
  117. }
  118. if len(msgs) == 0 {
  119. return ""
  120. }
  121. return "卸载挂载失败: " + strings.Join(msgs, "; ")
  122. }