udpforwarding.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. package waf
  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. "github.com/go-nunu/nunu-layout-advanced/internal/repository"
  9. "go.mongodb.org/mongo-driver/bson"
  10. "go.mongodb.org/mongo-driver/bson/primitive"
  11. "go.mongodb.org/mongo-driver/mongo"
  12. "time"
  13. )
  14. type UdpForWardingRepository interface {
  15. GetUdpForWarding(ctx context.Context, id int64) (*model.UdpForWarding, error)
  16. AddUdpForwarding(ctx context.Context, req *model.UdpForWarding) (int, error)
  17. EditUdpForwarding(ctx context.Context, req *model.UdpForWarding) error
  18. DeleteUdpForwarding(ctx context.Context, id int64) error
  19. GetUdpForwardingWafUdpIdById(ctx context.Context, id int) (int, error)
  20. GetUdpForwardingPortCountByHostId(ctx context.Context, hostId int) (int64, error)
  21. GetUdpForwardingWafUdpAllIds(ctx context.Context, hostId int) ([]int, error)
  22. AddUdpForwardingIps(ctx context.Context, req model.UdpForwardingRule) (primitive.ObjectID, error)
  23. EditUdpForwardingIps(ctx context.Context, req model.UdpForwardingRule) error
  24. GetUdpForwardingIpsByID(ctx context.Context, udpId int) (*model.UdpForwardingRule, error)
  25. DeleteUdpForwardingIpsById(ctx context.Context, udpId int) error
  26. // 获取ip数量等于1的ip
  27. GetIpCountByIp(ctx context.Context, ips []string) ([]v1.IpCountResult, error)
  28. // 获取端口数量
  29. GetPortCount(ctx context.Context, hostId int64, port string) (int64, error)
  30. GetUdpAll(ctx context.Context, hostIds []int) ([]int, error)
  31. }
  32. func NewUdpForWardingRepository(
  33. repository *repository.Repository,
  34. ) UdpForWardingRepository {
  35. return &udpForWardingRepository{
  36. Repository: repository,
  37. }
  38. }
  39. type udpForWardingRepository struct {
  40. *repository.Repository
  41. }
  42. func (r *udpForWardingRepository) GetUdpForWarding(ctx context.Context, id int64) (*model.UdpForWarding, error) {
  43. var udpForWarding model.UdpForWarding
  44. if err := r.Db.Where("id = ?", id).First(&udpForWarding).Error; err != nil {
  45. return nil, err
  46. }
  47. return &udpForWarding, nil
  48. }
  49. func (r *udpForWardingRepository) AddUdpForwarding(ctx context.Context, req *model.UdpForWarding) (int, error) {
  50. if err := r.Db.WithContext(ctx).Create(req).Error; err != nil {
  51. return 0, err
  52. }
  53. return req.Id, nil
  54. }
  55. func (r *udpForWardingRepository) EditUdpForwarding(ctx context.Context, req *model.UdpForWarding) 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 *udpForWardingRepository) DeleteUdpForwarding(ctx context.Context, id int64) error {
  65. if err := r.Db.Where("id = ?", id).Delete(&model.UdpForWarding{}).Error; err != nil {
  66. return err
  67. }
  68. return nil
  69. }
  70. func (r *udpForWardingRepository) GetUdpForwardingWafUdpIdById(ctx context.Context, id int) (int, error) {
  71. var WafUdpId int
  72. if err := r.Db.Model(&model.UdpForWarding{}).Where("id = ?", id).Select("waf_udp_id").Find(&WafUdpId).Error; err != nil {
  73. return 0, err
  74. }
  75. return WafUdpId, nil
  76. }
  77. func (r *udpForWardingRepository) GetUdpForwardingPortCountByHostId(ctx context.Context, hostId int) (int64, error) {
  78. var count int64
  79. if err := r.Db.Model(&model.UdpForWarding{}).Where("host_id = ?", hostId).Count(&count).Error; err != nil {
  80. return 0, err
  81. }
  82. return count, nil
  83. }
  84. func (r *udpForWardingRepository) GetUdpForwardingWafUdpAllIds(ctx context.Context, hostId int) ([]int, error) {
  85. var res []int
  86. if err:= r.Db.WithContext(ctx).Model(&model.UdpForWarding{}).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 *udpForWardingRepository) AddUdpForwardingIps(ctx context.Context, req model.UdpForwardingRule) (primitive.ObjectID, error) {
  93. collection := r.MongoDB.Collection("udp_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 *udpForWardingRepository) EditUdpForwardingIps(ctx context.Context, req model.UdpForwardingRule) error {
  103. collection := r.MongoDB.Collection("udp_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.UdpId != 0 {
  112. updateData["udp_id"] = req.UdpId
  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{"udp_id": req.UdpId}, update)
  127. if err != nil {
  128. return fmt.Errorf("更新MongoDB文档失败: %w", err)
  129. }
  130. return nil
  131. }
  132. func (r *udpForWardingRepository) GetUdpForwardingIpsByID(ctx context.Context, udpId int) (*model.UdpForwardingRule, error) {
  133. collection := r.MongoDB.Collection("udp_forwarding_rules")
  134. var result model.UdpForwardingRule
  135. err := collection.Find(ctx, bson.M{"udp_id": udpId}).One(&result)
  136. if err != nil {
  137. if errors.Is(err, mongo.ErrNoDocuments) {
  138. return nil, nil
  139. }
  140. return nil, fmt.Errorf("从MongoDB中获取文档失败: %w", err)
  141. }
  142. return &result, nil
  143. }
  144. func (r *udpForWardingRepository) DeleteUdpForwardingIpsById(ctx context.Context, udpId int) error {
  145. collection := r.MongoDB.Collection("udp_forwarding_rules")
  146. err := collection.Remove(ctx, bson.M{"udp_id": udpId})
  147. if err != nil {
  148. if errors.Is(err, mongo.ErrNoDocuments) {
  149. return fmt.Errorf("记录不存在")
  150. }
  151. return fmt.Errorf("删除MongoDB文档失败: %w", err)
  152. }
  153. return nil
  154. }
  155. // 获取IP数量等于1的IP
  156. func (r *udpForWardingRepository) GetIpCountByIp(ctx context.Context, ips []string) ([]v1.IpCountResult, error) {
  157. if len(ips) == 0 {
  158. return []v1.IpCountResult{}, nil
  159. }
  160. // 管道逻辑与 TCP 版本完全相同
  161. pipeline := []bson.M{
  162. {
  163. "$unwind": "$backend_list",
  164. },
  165. {
  166. "$addFields": bson.M{
  167. "extracted_ip": bson.M{
  168. "$arrayElemAt": []interface{}{
  169. bson.M{"$split": []string{"$backend_list", ":"}},
  170. 0,
  171. },
  172. },
  173. },
  174. },
  175. {
  176. "$match": bson.M{
  177. "extracted_ip": bson.M{"$in": ips},
  178. },
  179. },
  180. {
  181. "$group": bson.M{
  182. "_id": "$extracted_ip",
  183. "count": bson.M{"$sum": 1},
  184. },
  185. },
  186. {
  187. "$project": bson.M{
  188. "_id": 0,
  189. "ip": "$_id",
  190. "count": 1,
  191. },
  192. },
  193. }
  194. var results []v1.IpCountResult
  195. err := r.MongoDB.Collection("udp_forwarding_rules").Aggregate(ctx, pipeline).All(&results)
  196. if err != nil {
  197. return nil, fmt.Errorf("聚合查询 udp_forwarding_rules 失败: %w", err)
  198. }
  199. return results, nil
  200. }
  201. func (r *udpForWardingRepository) GetPortCount(ctx context.Context, hostId int64, port string) (int64, error) {
  202. var count int64
  203. if err := r.Db.WithContext(ctx).Model(&model.UdpForWarding{}).Where("host_id = ? AND port = ?", hostId, port).Count(&count).Error; err != nil {
  204. return 0, err
  205. }
  206. return count, nil
  207. }
  208. func (r *udpForWardingRepository) GetUdpAll(ctx context.Context, hostIds []int) ([]int, error) {
  209. var res []int
  210. if err:= r.Db.WithContext(ctx).Model(&model.UdpForWarding{}).Where("host_id IN ?", hostIds).Select("cdn_web_id").Scan(&res).Error; err != nil {
  211. return nil, err
  212. }
  213. return res, nil
  214. }