tcpforwarding.go 7.7 KB

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