webforwarding.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. package repository
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. v1 "github.com/go-nunu/nunu-layout-advanced/api/v1"
  8. "github.com/go-nunu/nunu-layout-advanced/internal/model"
  9. "github.com/qiniu/qmgo"
  10. "go.mongodb.org/mongo-driver/bson"
  11. "go.mongodb.org/mongo-driver/bson/primitive"
  12. "go.mongodb.org/mongo-driver/mongo"
  13. "gorm.io/gorm"
  14. "time"
  15. )
  16. type WebForwardingRepository interface {
  17. GetWebForwarding(ctx context.Context, id int64) (*model.WebForwarding, error)
  18. AddWebForwarding(ctx context.Context, req *model.WebForwarding) (int, error)
  19. EditWebForwarding(ctx context.Context, req *model.WebForwarding) error
  20. DeleteWebForwarding(ctx context.Context, id int64) error
  21. GetWebForwardingPortCountByHostId(ctx context.Context, hostId int) (int64, error)
  22. GetWebForwardingDomainCountByHostId(ctx context.Context, hostId int) (int64, []string, error)
  23. GetWebForwardingWafWebAllIds(ctx context.Context, hostId int) ([]int, error)
  24. AddWebForwardingIps(ctx context.Context, req model.WebForwardingRule) (primitive.ObjectID, error)
  25. EditWebForwardingIps(ctx context.Context, req model.WebForwardingRule) error
  26. GetWebForwardingIpsByID(ctx context.Context, webId int) (*model.WebForwardingRule, error)
  27. DeleteWebForwardingIpsById(ctx context.Context, webId int) error
  28. // 获取域名数量
  29. GetDomainCount(ctx context.Context, hostId int, domain string) (int, error)
  30. // 获取IP数量等于1的IP
  31. GetIpCountByIp(ctx context.Context, ips []string) ([]v1.IpCountResult, error)
  32. GetSslCertId (ctx context.Context, sslPocyID int64) ([]v1.SslCertsJSON, error)
  33. // 获取CDN的web配置的id
  34. GetWebConfigId(ctx context.Context, id int64) (int64, error)
  35. // 获取域名
  36. GetDomainByHostIdPort(ctx context.Context, hostId int64, port string) ([]v1.Domain, error)
  37. // 获取CDN的web配置的id
  38. GetWebId(ctx context.Context, serverId int64) (int64, error)
  39. GetWebAll(ctx context.Context, hostIds []int) ([]int, error)
  40. }
  41. func NewWebForwardingRepository(
  42. repository *Repository,
  43. ) WebForwardingRepository {
  44. return &webForwardingRepository{
  45. Repository: repository,
  46. }
  47. }
  48. type webForwardingRepository struct {
  49. *Repository
  50. }
  51. func (r *webForwardingRepository) GetWebForwarding(ctx context.Context, id int64) (*model.WebForwarding, error) {
  52. var webForwarding model.WebForwarding
  53. if err := r.db.WithContext(ctx).Where("id = ?", id).First(&webForwarding).Error; err != nil {
  54. return nil, err
  55. }
  56. return &webForwarding, nil
  57. }
  58. func (r *webForwardingRepository) AddWebForwarding(ctx context.Context, req *model.WebForwarding) (int, error) {
  59. if err := r.db.WithContext(ctx).Create(req).Error; err != nil {
  60. return 0, err
  61. }
  62. return req.Id, nil
  63. }
  64. func (r *webForwardingRepository) EditWebForwarding(ctx context.Context, req *model.WebForwarding) error {
  65. forceUpdateFields := map[string]interface{}{
  66. "domain": req.Domain,
  67. "is_https": req.IsHttps,
  68. "proxy" : req.Proxy,
  69. "cc" : req.Cc,
  70. }
  71. // 核心逻辑:
  72. // 1. Model(req): 定位要更新的记录。
  73. // 2. Updates(req): 先用 struct 更新。GORM 会自动忽略 req 中的零值字段。
  74. // - 如果 req.Domain 是 "abc",它会被更新。
  75. // - 如果 req.Domain 是 "",它会被忽略。
  76. // - 如果 req.TargetURL 是 "xyz",它会被更新。
  77. // - 如果 req.TargetURL 是 "",它会被忽略。
  78. // 3. Updates(forceUpdateFields): 接着用 map 更新。这会无视零值,强制更新 map 中指定的字段。
  79. // - 它会用 req.Domain 的值(无论是 "abc" 还是 "")覆盖上一步的结果。
  80. //
  81. // 最终效果:
  82. // - Domain 字段总能被正确更新(无论新值是不是 "")。
  83. // - 其他字段遵循 GORM 的默认行为(非零值才更新)。
  84. // - 这一切都在一个 UPDATE 语句中完成。
  85. db := r.db.WithContext(ctx).Model(req).Updates(req).Updates(forceUpdateFields)
  86. if db.Error != nil {
  87. return db.Error
  88. }
  89. return nil
  90. }
  91. func (r *webForwardingRepository) DeleteWebForwarding(ctx context.Context, id int64) error {
  92. if err := r.db.WithContext(ctx).Where("id = ?", id).Delete(&model.WebForwarding{}).Error; err != nil {
  93. return err
  94. }
  95. return nil
  96. }
  97. func (r *webForwardingRepository) GetWebForwardingPortCountByHostId(ctx context.Context, hostId int) (int64, error) {
  98. var count int64
  99. if err := r.db.Model(&model.WebForwarding{}).WithContext(ctx).Where("host_id = ?", hostId).Count(&count).Error; err != nil {
  100. return 0, err
  101. }
  102. return count, nil
  103. }
  104. func (r *webForwardingRepository) GetWebForwardingDomainCountByHostId(ctx context.Context, hostId int) (int64, []string, error) {
  105. var distinctDomains []string
  106. err := r.db.Model(&model.WebForwarding{}).WithContext(ctx).
  107. Distinct(). // 确保我们只获取唯一的 domain 值
  108. Where("host_id = ? AND domain IS NOT NULL AND domain != ''", hostId). // 额外添加 domain != '' 以排除空字符串
  109. Pluck("domain", &distinctDomains).Error
  110. if err != nil {
  111. return 0, nil, err
  112. }
  113. count := int64(len(distinctDomains))
  114. return count, distinctDomains, nil
  115. }
  116. func (r *webForwardingRepository) GetWebForwardingWafWebAllIds(ctx context.Context, hostId int) ([]int, error) {
  117. var ids []int
  118. if err := r.db.Model(&model.WebForwarding{}).WithContext(ctx).Where("host_id = ?", hostId).Select("id").Find(&ids).Error; err != nil {
  119. return nil, err
  120. }
  121. return ids, nil
  122. }
  123. // mongodb 插入
  124. func (r *webForwardingRepository) AddWebForwardingIps(ctx context.Context, req model.WebForwardingRule) (primitive.ObjectID, error) {
  125. collection := r.mongoDB.Collection("web_forwarding_rules")
  126. req.CreatedAt = time.Now()
  127. result, err := collection.InsertOne(ctx, req)
  128. if err != nil {
  129. return primitive.NilObjectID, fmt.Errorf("插入MongoDB失败: %w", err)
  130. }
  131. // 返回插入文档的ID
  132. return result.InsertedID.(primitive.ObjectID), nil
  133. }
  134. func (r *webForwardingRepository) EditWebForwardingIps(ctx context.Context, req model.WebForwardingRule) error {
  135. collection := r.mongoDB.Collection("web_forwarding_rules")
  136. updateData := bson.M{}
  137. if req.Uid != 0 {
  138. updateData["uid"] = req.Uid
  139. }
  140. if req.HostId != 0 {
  141. updateData["host_id"] = req.HostId
  142. }
  143. if req.WebId != 0 {
  144. updateData["web_id"] = req.WebId
  145. }
  146. if len(req.BackendList) > 0 {
  147. updateData["backend_list"] = req.BackendList
  148. }
  149. updateData["cdn_origin_ids"] = req.CdnOriginIds
  150. // 始终更新更新时间
  151. updateData["updated_at"] = time.Now()
  152. // 如果没有任何字段需要更新,则直接返回
  153. if len(updateData) == 0 {
  154. return nil
  155. }
  156. // 执行更新
  157. update := bson.M{"$set": updateData}
  158. err := collection.UpdateOne(ctx, bson.M{"web_id": req.WebId}, update)
  159. if err != nil {
  160. return fmt.Errorf("更新MongoDB文档失败: %w", err)
  161. }
  162. return nil
  163. }
  164. func (r *webForwardingRepository) GetWebForwardingIpsByID(ctx context.Context, webId int) (*model.WebForwardingRule, error) {
  165. // 获取集合
  166. collection := r.mongoDB.Collection("web_forwarding_rules")
  167. // 创建一个结构体来存储查询到的文档
  168. var rule model.WebForwardingRule
  169. // 使用 FindByID 方法来查找文档
  170. // FindByID 是 QMgo 封装的一个方便的方法,它内部会构建查询 _id = id
  171. err := collection.Find(ctx, qmgo.M{"web_id": webId}).One(&rule) // QMgo 的 FindOne 返回一个 QueryBuilder,接着调用 .One() 来执行查询并解码到 rule
  172. if err != nil {
  173. if errors.Is(err, mongo.ErrNoDocuments) {
  174. return nil, nil
  175. }
  176. // 其他错误
  177. return nil, fmt.Errorf("查询MongoDB失败: %w", err)
  178. }
  179. // 返回找到的文档
  180. return &rule, nil
  181. }
  182. func (r *webForwardingRepository) DeleteWebForwardingIpsById(ctx context.Context, webId int) error {
  183. collection := r.mongoDB.Collection("web_forwarding_rules")
  184. err := collection.Remove(ctx, bson.M{"web_id": webId})
  185. if err != nil {
  186. if errors.Is(err, mongo.ErrNoDocuments) {
  187. return fmt.Errorf("记录不存在")
  188. }
  189. return fmt.Errorf("删除MongoDB文档失败: %w", err)
  190. }
  191. return nil
  192. }
  193. // 获取域名数量
  194. func (r *webForwardingRepository) GetDomainCount(ctx context.Context, hostId int, domain string) (int, error) {
  195. var count int64
  196. if err := r.db.Model(&model.WebForwarding{}).WithContext(ctx).Where("host_id = ? AND domain = ?", hostId, domain).Count(&count).Error; err != nil {
  197. return 0, err
  198. }
  199. return int(count), nil
  200. }
  201. // 获取IP数量等于1的IP
  202. func (r *webForwardingRepository) GetIpCountByIp(ctx context.Context, ips []string) ([]v1.IpCountResult, error) {
  203. if len(ips) == 0 {
  204. return []v1.IpCountResult{}, nil
  205. }
  206. pipeline := []bson.M{
  207. // 第 1 步: $unwind - 展开 backend_list 数组
  208. // 将包含多个 backend 对象的文档拆分成多条,每条只包含一个 backend 对象。
  209. {
  210. "$unwind": "$backend_list",
  211. },
  212. // 第 2 步: $addFields - 添加一个新字段用于存放解析出的 IP
  213. // 我们需要从 "ip:port" 格式的 addr 字段中把 ip 提取出来。
  214. // 使用 $split 操作符按 ":" 分割字符串,然后用 $arrayElemAt 取第一个元素。
  215. {
  216. "$addFields": bson.M{
  217. "extracted_ip": bson.M{
  218. "$arrayElemAt": []interface{}{
  219. bson.M{"$split": []string{"$backend_list.addr", ":"}},
  220. 0,
  221. },
  222. },
  223. },
  224. },
  225. // 第 3 步: $match - 匹配我们关心的 IP
  226. // 在上一步创建的 extracted_ip 字段上进行匹配。
  227. {
  228. "$match": bson.M{
  229. "extracted_ip": bson.M{"$in": ips},
  230. },
  231. },
  232. // 第 4 步: $group - 按解析出的 IP 地址进行分组和计数
  233. {
  234. "$group": bson.M{
  235. "_id": "$extracted_ip", // 使用我们新创建的 extracted_ip 字段作为分组依据
  236. "count": bson.M{"$sum": 1},
  237. },
  238. },
  239. // 第 5 步: $project - 格式化最终输出
  240. // 这个阶段和之前一样,只是为了让输出结果更清晰,并匹配 Go 结构体。
  241. {
  242. "$project": bson.M{
  243. "_id": 0,
  244. "ip": "$_id",
  245. "count": 1,
  246. },
  247. },
  248. }
  249. var results []v1.IpCountResult
  250. // 使用 qmgo 执行聚合查询
  251. err := r.mongoDB.Collection("web_forwarding_rules").Aggregate(ctx, pipeline).All(&results)
  252. if err != nil {
  253. // 加上错误包装,方便调试
  254. return nil, fmt.Errorf("聚合查询 web_forwarding_rules 失败: %w", err)
  255. }
  256. return results, nil
  257. }
  258. func (r *webForwardingRepository) GetSslCertId (ctx context.Context, sslPolicyID int64) ([]v1.SslCertsJSON, error) {
  259. var certsJSON string
  260. // 2. 查询数据库,只获取 `certs` 字段的字符串内容
  261. // 使用 Scopes 来确保没有不必要的 ORDER BY 子句,或者直接用 Raw/Scan
  262. // 但在这里,用 .First(&certsJSON) 通常是安全的,因为目标是简单类型 string
  263. err := r.DBWithName(ctx, "cdn").WithContext(ctx).
  264. Table("cloud_ssl_policies").
  265. Select("certs").
  266. Where("id = ?", sslPolicyID).
  267. Row(). // 获取 sql.Row
  268. Scan(&certsJSON) // 将结果扫描到字符串变量中
  269. // 如果查询出错,或者没有找到记录 (sql.ErrNoRows)
  270. if err != nil {
  271. if err == gorm.ErrRecordNotFound {
  272. // 如果记录不存在是正常情况,可以返回一个空切片和nil错误
  273. return []v1.SslCertsJSON{}, nil
  274. }
  275. return nil, err
  276. }
  277. // 如果certs字段在数据库中可能是NULL或者空字符串,需要处理
  278. if certsJSON == "" {
  279. return []v1.SslCertsJSON{}, nil
  280. }
  281. // 3. 将JSON字符串反序列化到Go结构体切片中
  282. var res []v1.SslCertsJSON
  283. err = json.Unmarshal([]byte(certsJSON), &res)
  284. if err != nil {
  285. // 这里是真正的JSON格式转换错误
  286. return nil, err
  287. }
  288. return res, nil
  289. }
  290. // 获取CDN的web配置的id
  291. func (r *webForwardingRepository) GetWebConfigId(ctx context.Context, id int64) (int64, error) {
  292. var webConfigId int64
  293. if err := r.DBWithName(ctx,"cdn").Table("cloud_servers").Where("id = ?", id).Select("webId").Scan(&webConfigId).Error; err != nil {
  294. return 0, err
  295. }
  296. return webConfigId, nil
  297. }
  298. func (r *webForwardingRepository) GetDomainByHostIdPort(ctx context.Context, hostId int64, port string) ([]v1.Domain, error) {
  299. var domains []v1.Domain
  300. if err := r.db.WithContext(ctx).Model(&model.WebForwarding{}).Where("host_id = ? AND port = ?", hostId, port).Select("domain,id,is_https").Scan(&domains).Error; err != nil {
  301. return nil, err
  302. }
  303. return domains, nil
  304. }
  305. // 获取CDN的web配置的id
  306. func (r *webForwardingRepository) GetWebId(ctx context.Context, serverId int64) (int64, error) {
  307. var webId int64
  308. if err := r.DBWithName(ctx,"cdn").Table("cloud_servers").Where("id = ?", serverId).Select("webId").Scan(&webId).Error; err != nil {
  309. return 0, err
  310. }
  311. return webId, nil
  312. }
  313. func (r *webForwardingRepository) GetWebAll(ctx context.Context, hostIds []int) ([]int, error) {
  314. var res []int
  315. if err := r.db.Model(&model.WebForwarding{}).WithContext(ctx).Where("host_id IN ?", hostIds).Select("cdn_web_id").Scan(&res).Error; err != nil {
  316. return nil, err
  317. }
  318. return res, nil
  319. }