tcpforwarding.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. package repository
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. v1 "github.com/go-nunu/nunu-layout-advanced/api/v1"
  7. "github.com/go-nunu/nunu-layout-advanced/internal/model"
  8. "go.mongodb.org/mongo-driver/bson"
  9. "go.mongodb.org/mongo-driver/bson/primitive"
  10. "go.mongodb.org/mongo-driver/mongo"
  11. "time"
  12. )
  13. type TcpforwardingRepository interface {
  14. GetTcpforwarding(ctx context.Context, id int64) (*model.Tcpforwarding, error)
  15. AddTcpforwarding(ctx context.Context, req *model.Tcpforwarding) (int, error)
  16. EditTcpforwarding(ctx context.Context, req *model.Tcpforwarding) error
  17. DeleteTcpforwarding(ctx context.Context, id int64) error
  18. GetTcpforwardingWafTcpIdById(ctx context.Context, id int) (int, error)
  19. GetTcpForwardingPortCountByHostId(ctx context.Context, hostId int) (int64, error)
  20. GetTcpForwardingAllIdsByID(ctx context.Context, hostId int) ([]int, error)
  21. AddTcpforwardingIps(ctx context.Context,req model.TcpForwardingRule) (primitive.ObjectID, error)
  22. EditTcpforwardingIps(ctx context.Context, req model.TcpForwardingRule) error
  23. GetTcpForwardingIpsByID(ctx context.Context, tcpId int) (*model.TcpForwardingRule, error)
  24. DeleteTcpForwardingIpsById(ctx context.Context, tcpId int) error
  25. // 获取IP数量等于1的IP
  26. GetIpCountByIp(ctx context.Context,ips []string) ([]v1.IpCountResult, error)
  27. // 获取端口数量
  28. GetPortCount(ctx context.Context,hostId int64, port string) (int64, error)
  29. // 获取所有数据
  30. GetTcpAll(ctx context.Context, hostIds []int) ([]int, error)
  31. }
  32. func NewTcpforwardingRepository(
  33. repository *Repository,
  34. ) TcpforwardingRepository {
  35. return &tcpforwardingRepository{
  36. Repository: repository,
  37. }
  38. }
  39. type tcpforwardingRepository struct {
  40. *Repository
  41. }
  42. func (r *tcpforwardingRepository) GetTcpforwarding(ctx context.Context, id int64) (*model.Tcpforwarding, error) {
  43. var tcpforwarding model.Tcpforwarding
  44. if err := r.db.Where("id = ?", id).First(&tcpforwarding).Error; err != nil {
  45. return nil, err
  46. }
  47. return &tcpforwarding, nil
  48. }
  49. func (r *tcpforwardingRepository) AddTcpforwarding(ctx context.Context, req *model.Tcpforwarding) (int, error) {
  50. if err := r.db.Create(req).Error; err != nil {
  51. return 0, err
  52. }
  53. return req.Id, nil
  54. }
  55. func (r *tcpforwardingRepository) EditTcpforwarding(ctx context.Context, req *model.Tcpforwarding) error {
  56. data := map[string]interface{}{
  57. "proxy" : req.Proxy,
  58. }
  59. if err := r.db.Updates(req).Updates(data).Error; err != nil {
  60. return err
  61. }
  62. return nil
  63. }
  64. func (r *tcpforwardingRepository) DeleteTcpforwarding(ctx context.Context, id int64) error {
  65. if err := r.db.Where("id = ?", id).Delete(&model.Tcpforwarding{}).Error; err != nil {
  66. return err
  67. }
  68. return nil
  69. }
  70. func (r *tcpforwardingRepository) GetTcpforwardingWafTcpIdById(ctx context.Context, id int) (int, error) {
  71. var WafTcpId int
  72. if err := r.db.Model(&model.Tcpforwarding{}).Where("id = ?", id).Select("waf_tcp_id").Find(&WafTcpId).Error; err != nil {
  73. return 0, err
  74. }
  75. return WafTcpId, nil
  76. }
  77. func (r *tcpforwardingRepository) GetTcpForwardingPortCountByHostId(ctx context.Context, hostId int) (int64, error) {
  78. var count int64
  79. if err := r.db.Model(&model.Tcpforwarding{}).Where("host_id = ?", hostId).Count(&count).Error; err != nil {
  80. return 0, err
  81. }
  82. return count, nil
  83. }
  84. func (r *tcpforwardingRepository) GetTcpForwardingAllIdsByID(ctx context.Context, hostId int) ([]int, error) {
  85. var res []int
  86. if err := r.db.WithContext(ctx).Model(&model.Tcpforwarding{}).Where("host_id = ?", hostId).Select("id").Find(&res).Error; err != nil {
  87. return nil, err
  88. }
  89. return res, nil
  90. }
  91. //mongodb 插入
  92. func (r *tcpforwardingRepository) AddTcpforwardingIps(ctx context.Context,req model.TcpForwardingRule) (primitive.ObjectID, error) {
  93. collection := r.mongoDB.Collection("tcp_forwarding_rules")
  94. req.CreatedAt = time.Now()
  95. result, err := collection.InsertOne(ctx, req)
  96. if err != nil {
  97. return primitive.NilObjectID, fmt.Errorf("插入MongoDB失败: %w", err)
  98. }
  99. // 返回插入文档的ID
  100. return result.InsertedID.(primitive.ObjectID), nil
  101. }
  102. func (r *tcpforwardingRepository) EditTcpforwardingIps(ctx context.Context, req model.TcpForwardingRule) error {
  103. collection := r.mongoDB.Collection("tcp_forwarding_rules")
  104. updateData := bson.M{}
  105. if req.Uid != 0 {
  106. updateData["uid"] = req.Uid
  107. }
  108. if req.HostId != 0 {
  109. updateData["host_id"] = req.HostId
  110. }
  111. if req.TcpId != 0 {
  112. updateData["tcp_id"] = req.TcpId
  113. }
  114. if len(req.BackendList) > 0 {
  115. updateData["backend_list"] = req.BackendList
  116. }
  117. updateData["cdn_origin_ids"] = req.CdnOriginIds
  118. // 始终更新更新时间
  119. updateData["updated_at"] = time.Now()
  120. // 如果没有任何字段需要更新,则直接返回
  121. if len(updateData) == 0 {
  122. return nil
  123. }
  124. // 执行更新
  125. update := bson.M{"$set": updateData}
  126. err := collection.UpdateOne(ctx, bson.M{"tcp_id": req.TcpId}, update)
  127. if err != nil {
  128. if errors.Is(err, mongo.ErrNoDocuments) {
  129. return fmt.Errorf("记录不存在")
  130. }
  131. return fmt.Errorf("更新MongoDB文档失败: %w", err)
  132. }
  133. return nil
  134. }
  135. func (r *tcpforwardingRepository) GetTcpForwardingIpsByID(ctx context.Context, tcpId int) (*model.TcpForwardingRule, error) {
  136. collection := r.mongoDB.Collection("tcp_forwarding_rules")
  137. var res model.TcpForwardingRule
  138. err := collection.Find(ctx, bson.M{"tcp_id": tcpId}).One(&res)
  139. if err != nil {
  140. if errors.Is(err, mongo.ErrNoDocuments) {
  141. return nil, nil
  142. }
  143. return nil, fmt.Errorf("查询MongoDB失败: %w", err)
  144. }
  145. return &res, nil
  146. }
  147. func (r *tcpforwardingRepository) DeleteTcpForwardingIpsById(ctx context.Context, tcpId int) error {
  148. collection := r.mongoDB.Collection("tcp_forwarding_rules")
  149. err := collection.Remove(ctx, bson.M{"tcp_id": tcpId})
  150. if err != nil {
  151. if errors.Is(err, mongo.ErrNoDocuments) {
  152. return fmt.Errorf("记录不存在")
  153. }
  154. return fmt.Errorf("删除MongoDB文档失败: %w", err)
  155. }
  156. return nil
  157. }
  158. // 获取IP数量等于1的IP
  159. func (r *tcpforwardingRepository) GetIpCountByIp(ctx context.Context, ips []string) ([]v1.IpCountResult, error) {
  160. if len(ips) == 0 {
  161. return []v1.IpCountResult{}, nil
  162. }
  163. pipeline := []bson.M{
  164. // 1. 展开 backend_list 数组。此时 backend_list 字段会变成 "ip:port" 字符串。
  165. {
  166. "$unwind": "$backend_list",
  167. },
  168. // 2. 添加新字段 extracted_ip,存放从 "ip:port" 中解析出的 IP。
  169. {
  170. "$addFields": bson.M{
  171. "extracted_ip": bson.M{
  172. "$arrayElemAt": []interface{}{
  173. // 直接在 backend_list 字符串上分割
  174. bson.M{"$split": []string{"$backend_list", ":"}},
  175. 0,
  176. },
  177. },
  178. },
  179. },
  180. // 3. 匹配我们关心的 IP
  181. {
  182. "$match": bson.M{
  183. "extracted_ip": bson.M{"$in": ips},
  184. },
  185. },
  186. // 4. 按解析出的 IP 地址进行分组和计数
  187. {
  188. "$group": bson.M{
  189. "_id": "$extracted_ip",
  190. "count": bson.M{"$sum": 1},
  191. },
  192. },
  193. // 5. 格式化最终输出
  194. {
  195. "$project": bson.M{
  196. "_id": 0,
  197. "ip": "$_id",
  198. "count": 1,
  199. },
  200. },
  201. }
  202. var results []v1.IpCountResult
  203. err := r.mongoDB.Collection("tcp_forwarding_rules").Aggregate(ctx, pipeline).All(&results)
  204. if err != nil {
  205. return nil, fmt.Errorf("聚合查询 tcp_forwarding_rules 失败: %w", err)
  206. }
  207. return results, nil
  208. }
  209. func (r *tcpforwardingRepository) GetPortCount(ctx context.Context,hostId int64, port string) (int64, error) {
  210. var count int64
  211. if err := r.db.WithContext(ctx).Model(&model.Tcpforwarding{}).Where("host_id = ? AND port = ?", hostId, port).Count(&count).Error; err != nil {
  212. return 0, err
  213. }
  214. return count, nil
  215. }
  216. func (r *tcpforwardingRepository) GetTcpAll(ctx context.Context, hostIds []int) ([]int, error) {
  217. var res []int
  218. if err := r.db.WithContext(ctx).Model(&model.Tcpforwarding{}).Where("host_id IN ?", hostIds).Select("cdn_web_id").Scan(&res).Error; err != nil {
  219. return nil, err
  220. }
  221. return res, nil
  222. }