webforwarding.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/davecgh/go-spew/spew"
  7. v1 "github.com/go-nunu/nunu-layout-advanced/api/v1"
  8. "github.com/go-nunu/nunu-layout-advanced/internal/model"
  9. "github.com/go-nunu/nunu-layout-advanced/internal/repository"
  10. "github.com/go-nunu/nunu-layout-advanced/pkg/rabbitmq"
  11. amqp "github.com/rabbitmq/amqp091-go"
  12. "go.uber.org/zap"
  13. "golang.org/x/sync/errgroup"
  14. "sort"
  15. "strconv"
  16. "strings"
  17. )
  18. type WebForwardingService interface {
  19. GetWebForwarding(ctx context.Context, req v1.GetForwardingRequest) (v1.WebForwardingDataRequest, error)
  20. GetWebForwardingWafWebAllIps(ctx context.Context, req v1.GetForwardingRequest) ([]v1.WebForwardingDataRequest, error)
  21. AddWebForwarding(ctx context.Context, req *v1.WebForwardingRequest) error
  22. EditWebForwarding(ctx context.Context, req *v1.WebForwardingRequest) error
  23. DeleteWebForwarding(ctx context.Context, Ids []int) error
  24. }
  25. func NewWebForwardingService(
  26. service *Service,
  27. required RequiredService,
  28. webForwardingRepository repository.WebForwardingRepository,
  29. crawler CrawlerService,
  30. parser ParserService,
  31. wafformatter WafFormatterService,
  32. aoDun AoDunService,
  33. mq *rabbitmq.RabbitMQ,
  34. gatewayGroupIpRep repository.GateWayGroupIpRepository,
  35. ) WebForwardingService {
  36. return &webForwardingService{
  37. Service: service,
  38. webForwardingRepository: webForwardingRepository,
  39. required: required,
  40. parser: parser,
  41. crawler: crawler,
  42. wafformatter: wafformatter,
  43. aoDun: aoDun,
  44. mq: mq,
  45. gatewayGroupIpRep: gatewayGroupIpRep,
  46. }
  47. }
  48. type webForwardingService struct {
  49. *Service
  50. webForwardingRepository repository.WebForwardingRepository
  51. required RequiredService
  52. parser ParserService
  53. crawler CrawlerService
  54. wafformatter WafFormatterService
  55. aoDun AoDunService
  56. mq *rabbitmq.RabbitMQ
  57. gatewayGroupIpRep repository.GateWayGroupIpRepository
  58. }
  59. func (s *webForwardingService) require(ctx context.Context,req v1.GlobalRequire) (v1.GlobalRequire, error) {
  60. var err error
  61. var res v1.GlobalRequire
  62. g, gCtx := errgroup.WithContext(ctx)
  63. g.Go(func() error {
  64. result, e := s.wafformatter.require(gCtx, req, "web")
  65. if e != nil {
  66. return e
  67. }
  68. res = result
  69. return nil
  70. })
  71. g.Go(func() error {
  72. e := s.wafformatter.validateWafDomainCount(gCtx, req)
  73. if e != nil {
  74. return e
  75. }
  76. return nil
  77. })
  78. if err = g.Wait(); err != nil {
  79. return v1.GlobalRequire{}, err
  80. }
  81. return res, nil
  82. }
  83. func (s *webForwardingService) GetWebForwarding(ctx context.Context, req v1.GetForwardingRequest) (v1.WebForwardingDataRequest, error) {
  84. var webForwarding model.WebForwarding
  85. var backend model.WebForwardingRule
  86. g, gCtx := errgroup.WithContext(ctx)
  87. g.Go(func() error {
  88. res, e := s.webForwardingRepository.GetWebForwarding(gCtx, int64(req.Id))
  89. if e != nil {
  90. // 直接返回错误,errgroup 会捕获它
  91. return fmt.Errorf("GetWebForwarding failed: %w", e)
  92. }
  93. if res != nil {
  94. webForwarding = *res
  95. }
  96. return nil
  97. })
  98. g.Go(func() error {
  99. res, e := s.webForwardingRepository.GetWebForwardingIpsByID(ctx, req.Id)
  100. if e != nil {
  101. return fmt.Errorf("GetWebForwardingByID failed: %w", e)
  102. }
  103. if res != nil {
  104. backend = *res
  105. }
  106. return nil
  107. })
  108. if err := g.Wait(); err != nil {
  109. return v1.WebForwardingDataRequest{}, err
  110. }
  111. return v1.WebForwardingDataRequest{
  112. Id: webForwarding.Id,
  113. WafWebId: webForwarding.WafWebId,
  114. Tag: webForwarding.Tag,
  115. Port: webForwarding.Port,
  116. Domain: webForwarding.Domain,
  117. CustomHost: webForwarding.CustomHost,
  118. WafWebLimitId: webForwarding.WebLimitRuleId,
  119. WafGatewayGroupId: webForwarding.WafGatewayGroupId,
  120. CcCount: webForwarding.CcCount,
  121. CcDuration: webForwarding.CcDuration,
  122. CcBlockCount: webForwarding.CcBlockCount,
  123. CcBlockDuration: webForwarding.CcBlockDuration,
  124. Cc4xxCount: webForwarding.Cc4xxCount,
  125. Cc4xxDuration: webForwarding.Cc4xxDuration,
  126. Cc4xxBlockCount: webForwarding.Cc4xxBlockCount,
  127. Cc4xxBlockDuration: webForwarding.Cc4xxBlockDuration,
  128. Cc5xxCount: webForwarding.Cc5xxCount,
  129. Cc5xxDuration: webForwarding.Cc5xxDuration,
  130. Cc5xxBlockCount: webForwarding.Cc5xxBlockCount,
  131. Cc5xxBlockDuration: webForwarding.Cc5xxBlockDuration,
  132. IsHttps: webForwarding.IsHttps,
  133. Comment: webForwarding.Comment,
  134. BackendList: backend.BackendList,
  135. AllowIpList: backend.AllowIpList,
  136. DenyIpList: backend.DenyIpList,
  137. AccessRule: backend.AccessRule,
  138. HttpsKey: webForwarding.HttpsKey,
  139. HttpsCert: webForwarding.HttpsCert,
  140. }, nil
  141. }
  142. // buildWafFormData 辅助函数,用于构建通用的 formData
  143. func (s *webForwardingService) buildWafFormData(req *v1.WebForwardingDataSend, require v1.GlobalRequire) map[string]interface{} {
  144. // 将BackendList序列化为JSON字符串
  145. backendJSON, err := json.MarshalIndent(req.BackendList, "", " ")
  146. var backendStr interface{}
  147. if err != nil {
  148. // 如果序列化失败,使用空数组
  149. backendStr = "[]"
  150. } else {
  151. // 成功序列化后,使用JSON字符串
  152. backendStr = string(backendJSON)
  153. }
  154. return map[string]interface{}{
  155. "waf_web_id": req.WafWebId,
  156. "tag": require.Tag,
  157. "port": req.Port,
  158. "domain": req.Domain,
  159. "custom_host": req.CustomHost,
  160. "waf_gateway_group_id": require.WafGatewayGroupId,
  161. "waf_web_limit_id": require.LimitRuleId,
  162. "cc_count": req.CcCount,
  163. "cc_duration": req.CcDuration,
  164. "cc_block_count": req.CcBlockCount,
  165. "cc_block_duration": req.CcBlockDuration,
  166. "cc_4xx_count": req.Cc4xxCount,
  167. "cc_4xx_duration": req.Cc4xxDuration,
  168. "cc_4xx_block_count": req.Cc4xxBlockCount,
  169. "cc_4xx_block_duration": req.Cc4xxBlockDuration,
  170. "cc_5xx_count": req.Cc5xxCount,
  171. "cc_5xx_duration": req.Cc5xxDuration,
  172. "cc_5xx_block_count": req.Cc5xxBlockCount,
  173. "cc_5xx_block_duration": req.Cc5xxBlockDuration,
  174. "backend": backendStr,
  175. "allow_ip_list": req.AllowIpList,
  176. "deny_ip_list": req.DenyIpList,
  177. "access_rule": req.AccessRule,
  178. "is_https": req.IsHttps,
  179. "comment": req.Comment,
  180. "https_cert": req.HttpsCert,
  181. "https_key": req.HttpsKey,
  182. }
  183. }
  184. // buildWebForwardingModel 辅助函数,用于构建通用的 WebForwarding 模型
  185. // ruleId 是从 WAF 系统获取的 ID
  186. func (s *webForwardingService) buildWebForwardingModel(req *v1.WebForwardingDataRequest,ruleId int, require v1.GlobalRequire) *model.WebForwarding {
  187. return &model.WebForwarding{
  188. HostId: require.HostId,
  189. WafWebId: ruleId,
  190. Tag: require.Tag,
  191. Port: req.Port,
  192. Domain: req.Domain,
  193. CustomHost: req.CustomHost,
  194. WafGatewayGroupId: require.WafGatewayGroupId,
  195. WebLimitRuleId: require.LimitRuleId,
  196. CcCount: req.CcCount,
  197. CcDuration: req.CcDuration,
  198. CcBlockCount: req.CcBlockCount,
  199. CcBlockDuration: req.CcBlockDuration,
  200. Cc4xxCount: req.Cc4xxCount,
  201. Cc4xxDuration: req.Cc4xxDuration,
  202. Cc4xxBlockCount: req.Cc4xxBlockCount,
  203. Cc4xxBlockDuration: req.Cc4xxBlockDuration,
  204. Cc5xxCount: req.Cc5xxCount,
  205. Cc5xxDuration: req.Cc5xxDuration,
  206. Cc5xxBlockCount: req.Cc5xxBlockCount,
  207. Cc5xxBlockDuration: req.Cc5xxBlockDuration,
  208. IsHttps: req.IsHttps,
  209. Comment: req.Comment,
  210. HttpsCert: req.HttpsCert,
  211. HttpsKey: req.HttpsKey,
  212. }
  213. }
  214. func (s *webForwardingService) buildWebRuleModel(reqData *v1.WebForwardingDataRequest, require v1.GlobalRequire, localDbId int) *model.WebForwardingRule {
  215. return &model.WebForwardingRule{
  216. Uid: require.Uid,
  217. HostId: require.HostId,
  218. WebId: localDbId, // 关联到本地数据库的主记录 ID
  219. BackendList: reqData.BackendList,
  220. AllowIpList: reqData.AllowIpList,
  221. DenyIpList: reqData.DenyIpList,
  222. AccessRule: reqData.AccessRule,
  223. }
  224. }
  225. func (s *webForwardingService) prepareWafData(ctx context.Context, req *v1.WebForwardingRequest) (v1.GlobalRequire, map[string]interface{}, error) {
  226. // 1. 获取必要的全局信息
  227. require, err := s.require(ctx, v1.GlobalRequire{
  228. HostId: req.HostId,
  229. Uid: req.Uid,
  230. Comment: req.WebForwardingData.Comment,
  231. Domain: req.WebForwardingData.Domain,
  232. })
  233. if err != nil {
  234. return v1.GlobalRequire{}, nil, err
  235. }
  236. if require.WafGatewayGroupId == 0 || require.LimitRuleId == 0 {
  237. return v1.GlobalRequire{}, nil, fmt.Errorf("请先配置实例")
  238. }
  239. // 2. 将字符串切片拼接成字符串,用于 WAF API
  240. allowIpListStr := strings.Join(req.WebForwardingData.AllowIpList, "\n")
  241. denyIpListStr := strings.Join(req.WebForwardingData.DenyIpList, "\n")
  242. PortInt, err := strconv.Atoi(req.WebForwardingData.Port)
  243. if err != nil {
  244. return v1.GlobalRequire{}, nil, err
  245. }
  246. // 3. 创建用于构建 WAF 表单的数据结构
  247. formDataBase := v1.WebForwardingDataSend{
  248. Tag: require.Tag,
  249. WafWebId: req.WebForwardingData.WafWebId,
  250. WafGatewayGroupId: require.WafGatewayGroupId,
  251. WafWebLimitId: require.LimitRuleId,
  252. Port: PortInt,
  253. Domain: req.WebForwardingData.Domain,
  254. CustomHost: req.WebForwardingData.CustomHost,
  255. CcCount: req.WebForwardingData.CcCount,
  256. CcDuration: req.WebForwardingData.CcDuration,
  257. CcBlockCount: req.WebForwardingData.CcBlockCount,
  258. CcBlockDuration: req.WebForwardingData.CcBlockDuration,
  259. Cc4xxCount: req.WebForwardingData.Cc4xxCount,
  260. Cc4xxDuration: req.WebForwardingData.Cc4xxDuration,
  261. Cc4xxBlockCount: req.WebForwardingData.Cc4xxBlockCount,
  262. Cc4xxBlockDuration: req.WebForwardingData.Cc4xxBlockDuration,
  263. Cc5xxCount: req.WebForwardingData.Cc5xxCount,
  264. Cc5xxDuration: req.WebForwardingData.Cc5xxDuration,
  265. Cc5xxBlockCount: req.WebForwardingData.Cc5xxBlockCount,
  266. Cc5xxBlockDuration: req.WebForwardingData.Cc5xxBlockDuration,
  267. IsHttps: req.WebForwardingData.IsHttps,
  268. BackendList: req.WebForwardingData.BackendList,
  269. AllowIpList: allowIpListStr,
  270. DenyIpList: denyIpListStr,
  271. AccessRule: req.WebForwardingData.AccessRule,
  272. Comment: req.WebForwardingData.Comment,
  273. HttpsCert: req.WebForwardingData.HttpsCert,
  274. HttpsKey: req.WebForwardingData.HttpsKey,
  275. }
  276. // 4. 构建 WAF 表单数据映射
  277. formData := s.buildWafFormData(&formDataBase, require)
  278. return require, formData, nil
  279. }
  280. func (s *webForwardingService) AddWebForwarding(ctx context.Context, req *v1.WebForwardingRequest) error {
  281. require, formData, err := s.prepareWafData(ctx, req)
  282. if err != nil {
  283. return err
  284. }
  285. err = s.wafformatter.validateWafPortCount(ctx, require.HostId)
  286. if err != nil {
  287. return err
  288. }
  289. wafWebId, err := s.wafformatter.sendFormData(ctx, "admin/info/waf_web/new", "admin/new/waf_web", formData)
  290. if err != nil {
  291. return err
  292. }
  293. spew.Dump(req.WebForwardingData.Domain)
  294. if req.WebForwardingData.Domain != "" {
  295. // 异步任务:将域名添加到白名单
  296. doMain, err := s.wafformatter.ConvertToWildcardDomain(ctx, req.WebForwardingData.Domain)
  297. if err != nil {
  298. return err
  299. }
  300. ip, err := s.gatewayGroupIpRep.GetGateWayGroupFirstIpByGatewayGroupId(ctx, require.WafGatewayGroupId)
  301. if err != nil {
  302. return err
  303. }
  304. spew.Dump(ip,"=================================")
  305. go s.publishDomainWhitelistTask(doMain,ip, "add")
  306. }
  307. webModel := s.buildWebForwardingModel(&req.WebForwardingData, wafWebId, require)
  308. id, err := s.webForwardingRepository.AddWebForwarding(ctx, webModel)
  309. if err != nil {
  310. return err
  311. }
  312. webRuleModel := s.buildWebRuleModel(&req.WebForwardingData, require, id)
  313. //var ips []v1.IpInfo
  314. //for _, v := range req.WebForwardingData.AllowIpList {
  315. // ips = append(ips, v1.IpInfo{
  316. // FType: "allow",
  317. // FStartIp: v,
  318. // FEndIp: v,
  319. // FRemark: "宁波高防IP过白",
  320. // FServerIp: "",
  321. // })
  322. //}
  323. //err = s.aoDun.AddDomainWhiteList(ctx, req.WebForwardingData.Domain)
  324. if _, err = s.webForwardingRepository.AddWebForwardingIps(ctx, *webRuleModel); err != nil {
  325. return err
  326. }
  327. return nil
  328. }
  329. func (s *webForwardingService) EditWebForwarding(ctx context.Context, req *v1.WebForwardingRequest) error {
  330. WafWebId, err := s.webForwardingRepository.GetWebForwardingWafWebIdById(ctx, req.WebForwardingData.Id)
  331. if err != nil {
  332. return err
  333. }
  334. req.WebForwardingData.WafWebId = WafWebId
  335. require, formData, err := s.prepareWafData(ctx, req)
  336. if err != nil {
  337. return err
  338. }
  339. _, err = s.wafformatter.sendFormData(ctx, "admin/info/waf_web/edit?&__goadmin_edit_pk="+strconv.Itoa(req.WebForwardingData.WafWebId), "admin/edit/waf_web", formData)
  340. if err != nil {
  341. return err
  342. }
  343. webData, err := s.webForwardingRepository.GetWebForwarding(ctx, int64(req.WebForwardingData.Id))
  344. if err != nil {
  345. return err
  346. }
  347. if webData.Domain != req.WebForwardingData.Domain {
  348. Ip, err := s.gatewayGroupIpRep.GetGateWayGroupFirstIpByGatewayGroupId(ctx, webData.WafGatewayGroupId)
  349. if err != nil {
  350. }
  351. // 异步任务:将域名添加到白名单
  352. doMain, err := s.wafformatter.ConvertToWildcardDomain(ctx, req.WebForwardingData.Domain)
  353. if err != nil {
  354. return err
  355. }
  356. go s.publishDomainWhitelistTask(webData.Domain, Ip, "del")
  357. go s.publishDomainWhitelistTask(doMain, Ip, "add")
  358. }
  359. webModel := s.buildWebForwardingModel(&req.WebForwardingData, req.WebForwardingData.WafWebId, require)
  360. webModel.Id = req.WebForwardingData.Id
  361. if err = s.webForwardingRepository.EditWebForwarding(ctx, webModel); err != nil {
  362. return err
  363. }
  364. webRuleModel := s.buildWebRuleModel(&req.WebForwardingData, require, req.WebForwardingData.Id)
  365. if err = s.webForwardingRepository.EditWebForwardingIps(ctx, *webRuleModel); err != nil {
  366. return err
  367. }
  368. return nil
  369. }
  370. func (s *webForwardingService) DeleteWebForwarding(ctx context.Context, Ids []int) error {
  371. for _, Id := range Ids {
  372. wafWebId, err := s.webForwardingRepository.GetWebForwardingWafWebIdById(ctx, Id)
  373. if err != nil {
  374. return err
  375. }
  376. webData, err := s.webForwardingRepository.GetWebForwarding(ctx, int64(Id))
  377. if err != nil {
  378. return err
  379. }
  380. Ip, err := s.gatewayGroupIpRep.GetGateWayGroupFirstIpByGatewayGroupId(ctx, webData.WafGatewayGroupId)
  381. if err != nil {
  382. }
  383. if webData.Domain != "" {
  384. doMain, err := s.wafformatter.ConvertToWildcardDomain(ctx, webData.Domain)
  385. if err != nil {
  386. return err
  387. }
  388. go s.publishDomainWhitelistTask(doMain,Ip, "del")
  389. }
  390. _, err = s.crawler.DeleteRule(ctx, wafWebId, "admin/delete/waf_web?page=1&__pageSize=10&__sort=waf_web_id&__sort_type=desc")
  391. if err != nil {
  392. return err
  393. }
  394. if err = s.webForwardingRepository.DeleteWebForwarding(ctx, int64(Id)); err != nil {
  395. return err
  396. }
  397. if err = s.webForwardingRepository.DeleteWebForwardingIpsById(ctx, Id); err != nil {
  398. return err
  399. }
  400. }
  401. return nil
  402. }
  403. func (s *webForwardingService) GetWebForwardingWafWebAllIps(ctx context.Context, req v1.GetForwardingRequest) ([]v1.WebForwardingDataRequest, error) {
  404. type CombinedResult struct {
  405. Id int
  406. Forwarding *model.WebForwarding
  407. BackendRule *model.WebForwardingRule
  408. Err error // 如果此ID的处理出错,则携带错误
  409. }
  410. g, gCtx := errgroup.WithContext(ctx)
  411. ids, err := s.webForwardingRepository.GetWebForwardingWafWebAllIds(gCtx, req.HostId)
  412. if err != nil {
  413. return nil, fmt.Errorf("GetWebForwardingWafWebAllIds failed: %w", err)
  414. }
  415. if len(ids) == 0 {
  416. return nil, nil // 没有ID,直接返回空切片
  417. }
  418. // 创建一个通道来接收每个ID的处理结果
  419. // 通道缓冲区大小设为ID数量,这样发送者不会因为接收者慢而阻塞(在所有goroutine都启动后)
  420. resultsChan := make(chan CombinedResult, len(ids))
  421. for _, idVal := range ids {
  422. currentID := idVal // 捕获循环变量
  423. g.Go(func() error {
  424. var wf *model.WebForwarding
  425. var bk *model.WebForwardingRule
  426. var localErr error
  427. // 1. 获取 WebForwarding 信息
  428. wf, localErr = s.webForwardingRepository.GetWebForwarding(gCtx, int64(currentID))
  429. if localErr != nil {
  430. // 发送错误到通道,并由 errgroup 捕获
  431. // errgroup 会处理第一个非nil错误,并取消其他 goroutine
  432. resultsChan <- CombinedResult{Id: currentID, Err: fmt.Errorf("GetWebForwarding for id %d failed: %w", currentID, localErr)}
  433. return localErr // 返回错误给 errgroup
  434. }
  435. if wf == nil { // 正常情况下,如果没错误,wf不应为nil,但防御性检查
  436. localErr = fmt.Errorf("GetWebForwarding for id %d returned nil data without error", currentID)
  437. resultsChan <- CombinedResult{Id: currentID, Err: localErr}
  438. return localErr
  439. }
  440. // 2. 获取 Backend IP 信息
  441. // 注意:这里我们允许 GetWebForwardingIpsByID 可能返回 nil 数据(例如没有规则)而不是错误
  442. // 如果它也可能返回错误,则处理方式与上面类似
  443. bk, localErr = s.webForwardingRepository.GetWebForwardingIpsByID(gCtx, currentID)
  444. if localErr != nil {
  445. // 如果获取IP信息失败是一个致命错误,则也应返回错误
  446. // 如果允许部分成功(比如有WebForwarding但没有IP信息),则可以不将此视为errgroup的错误
  447. // 这里假设它也是一个需要errgroup捕获的错误
  448. resultsChan <- CombinedResult{Id: currentID, Forwarding: wf, Err: fmt.Errorf("GetWebForwardingIpsByID for id %d failed: %w", currentID, localErr)}
  449. return localErr // 返回错误给 errgroup
  450. }
  451. // bk 可能是 nil 如果没有错误且没有规则,这取决于业务逻辑
  452. // 发送成功的结果到通道
  453. resultsChan <- CombinedResult{Id: currentID, Forwarding: wf, BackendRule: bk}
  454. return nil // 此goroutine成功
  455. })
  456. }
  457. // 等待所有goroutine完成
  458. groupErr := g.Wait()
  459. // 关闭通道,表示所有发送者都已完成
  460. // 这一步很重要,这样下面的 range 循环才能正常结束
  461. close(resultsChan)
  462. // 如果 errgroup 捕获到任何错误,优先返回该错误
  463. if groupErr != nil {
  464. // 虽然errgroup已经出错了,但通道中可能已经有一些结果(来自出错前成功或出错的goroutine)
  465. // 我们需要排空通道以避免goroutine泄漏(如果它们在发送时阻塞)
  466. // 但由于我们优先返回groupErr,这些结果将被丢弃。
  467. // 在这种设计下,通常任何一个子任务失败都会导致整个操作失败。
  468. return nil, groupErr
  469. }
  470. // 如果没有错误,收集所有成功的结果
  471. finalResults := make([]v1.WebForwardingDataRequest, 0, len(ids))
  472. for res := range resultsChan {
  473. // 再次检查通道中的错误,尽管 errgroup 应该已经捕获了
  474. // 但这是一种更细致的错误处理,以防万一有goroutine在errgroup.Wait()前发送了错误但未被errgroup捕获
  475. // (理论上,如果goroutine返回了错误,errgroup会处理)
  476. // 主要目的是处理 res.forwarding 为 nil 的情况 (如果上面允许不返回错误)
  477. if res.Err != nil {
  478. // 如果到这里还有错误,说明逻辑可能有问题,或者我们决定忽略某些类型的子错误
  479. // 在此示例中,因为 g.Wait() 没有错误,所以这里的 res.err 应该是nil
  480. // 如果不是,那么可能是goroutine在return nil前发送了带有错误的res。
  481. // 严格来说,如果errgroup没有错误,这里res.err也应该是nil
  482. // 但以防万一,我们可以记录日志
  483. return nil, fmt.Errorf("received error from goroutine for ID %d: %w", res.Id, res.Err)
  484. }
  485. if res.Forwarding == nil {
  486. return nil, fmt.Errorf("received nil forwarding from goroutine for ID %d", res.Id)
  487. }
  488. dataReq := v1.WebForwardingDataRequest{
  489. Id: res.Forwarding.Id,
  490. Port: res.Forwarding.Port,
  491. Domain: res.Forwarding.Domain,
  492. CustomHost: res.Forwarding.CustomHost,
  493. CcCount: res.Forwarding.CcCount,
  494. CcDuration: res.Forwarding.CcDuration,
  495. CcBlockCount: res.Forwarding.CcBlockCount,
  496. CcBlockDuration: res.Forwarding.CcBlockDuration,
  497. Cc4xxCount: res.Forwarding.Cc4xxCount,
  498. Cc4xxDuration: res.Forwarding.Cc4xxDuration,
  499. Cc4xxBlockCount: res.Forwarding.Cc4xxBlockCount,
  500. Cc4xxBlockDuration: res.Forwarding.Cc4xxBlockDuration,
  501. Cc5xxCount: res.Forwarding.Cc5xxCount,
  502. Cc5xxDuration: res.Forwarding.Cc5xxDuration,
  503. Cc5xxBlockCount: res.Forwarding.Cc5xxBlockCount,
  504. Cc5xxBlockDuration: res.Forwarding.Cc5xxBlockDuration,
  505. IsHttps: res.Forwarding.IsHttps,
  506. Comment: res.Forwarding.Comment,
  507. HttpsKey: res.Forwarding.HttpsKey,
  508. HttpsCert: res.Forwarding.HttpsCert,
  509. }
  510. if res.BackendRule != nil { // 只有当 BackendRule 存在时才填充相关字段
  511. dataReq.BackendList = res.BackendRule.BackendList
  512. dataReq.AllowIpList = res.BackendRule.AllowIpList
  513. dataReq.DenyIpList = res.BackendRule.DenyIpList
  514. dataReq.AccessRule = res.BackendRule.AccessRule
  515. }
  516. finalResults = append(finalResults, dataReq)
  517. }
  518. sort.Slice(finalResults, func(i, j int) bool {
  519. return finalResults[i].Id > finalResults[j].Id
  520. })
  521. return finalResults, nil
  522. }
  523. // publishDomainWhitelistTask is a helper function to publish domain whitelist tasks to RabbitMQ.
  524. // It can handle different actions like "add" or "del".
  525. func (s *webForwardingService) publishDomainWhitelistTask(domain, ip, action string) {
  526. // Define message payload, including the action
  527. type domainTaskPayload struct {
  528. Domain string `json:"domain"`
  529. Ip string `json:"ip"`
  530. Action string `json:"action"`
  531. }
  532. payload := domainTaskPayload{
  533. Domain: domain,
  534. Ip: ip,
  535. Action: action,
  536. }
  537. // Serialize the message
  538. msgBody, err := json.Marshal(payload)
  539. if err != nil {
  540. s.logger.Error("Failed to serialize domain whitelist task message", zap.Error(err), zap.String("domain", domain), zap.String("ip", ip), zap.String("action", action))
  541. return
  542. }
  543. // Get task configuration
  544. taskCfg, ok := s.mq.GetTaskConfig("domain_whitelist")
  545. if !ok {
  546. s.logger.Error("Failed to get 'domain_whitelist' task configuration")
  547. return
  548. }
  549. // Construct the routing key dynamically based on the action
  550. routingKey := fmt.Sprintf("whitelist.domain.%s", action)
  551. // Construct the amqp.Publishing message
  552. publishingMsg := amqp.Publishing{
  553. ContentType: "application/json",
  554. Body: msgBody,
  555. DeliveryMode: amqp.Persistent, // Persistent message
  556. }
  557. // Publish the message
  558. err = s.mq.PublishWithCh(taskCfg.Exchange, routingKey, publishingMsg)
  559. if err != nil {
  560. s.logger.Error("Failed to publish domain whitelist task to MQ", zap.Error(err), zap.String("domain", domain), zap.String("action", action))
  561. } else {
  562. s.logger.Info("Successfully published domain whitelist task to MQ", zap.String("domain", domain), zap.String("action", action))
  563. }
  564. }