manager.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. package service
  2. import (
  3. "context"
  4. "esproxy/internal/consts"
  5. "fmt"
  6. "github.com/gogf/gf/v2/frame/g"
  7. "github.com/gogf/gf/v2/os/glog"
  8. "net/http/httputil"
  9. "net/url"
  10. "os"
  11. "sync"
  12. "sync/atomic"
  13. "time"
  14. )
  15. var (
  16. EsProxyManager *esProxyManager = initManager(context.Background())
  17. )
  18. type esProxyManager struct {
  19. esStatus consts.EsStatus
  20. proxyPool chan *httputil.ReverseProxy
  21. simpleQueryPool, aggsQueryPool, complexQueryPool chan struct{}
  22. redisPrefix string
  23. }
  24. // initManager 初始化代理Manager
  25. func initManager(ctx context.Context) *esProxyManager {
  26. consts.LogTime = g.Cfg().MustGet(ctx, "logTime").Float64()
  27. consts.LogEquity = g.Cfg().MustGet(ctx, "logEquity").Bool()
  28. esAddr := g.Cfg().MustGet(ctx, "elasticSearch.address").Strings()
  29. if len(esAddr) < 1 {
  30. glog.Error(ctx, "加载出错,退出")
  31. os.Exit(0)
  32. }
  33. pool := make(chan *httputil.ReverseProxy, len(esAddr))
  34. for _, v := range esAddr {
  35. u, err := url.Parse(v)
  36. if err != nil {
  37. glog.Error(ctx, "init parse esAddr err:", err)
  38. } else {
  39. pool <- CreateDefaultProxyClient(u)
  40. }
  41. }
  42. emp := &esProxyManager{
  43. esStatus: consts.EsStatus_Free,
  44. proxyPool: pool,
  45. simpleQueryPool: makeEmptyChan(g.Cfg().MustGet(ctx, "elasticSearch.pool.simple", 10).Int()),
  46. aggsQueryPool: makeEmptyChan(g.Cfg().MustGet(ctx, "elasticSearch.pool.aggs", 10).Int()),
  47. complexQueryPool: makeEmptyChan(g.Cfg().MustGet(ctx, "elasticSearch.pool.complex", 10).Int()),
  48. redisPrefix: g.Cfg().MustGet(ctx, "server.redisPrefix", "es").String(),
  49. }
  50. go emp.UpdateEsStatus(ctx)
  51. return emp
  52. }
  53. func makeEmptyChan(total int) chan struct{} {
  54. c := make(chan struct{}, total)
  55. for i := 0; i < total; i++ {
  56. c <- struct{}{}
  57. }
  58. return c
  59. }
  60. // UpdateEsStatus 更新es状态
  61. func (epm *esProxyManager) UpdateEsStatus(ctx context.Context) {
  62. if cron := g.Cfg().MustGet(ctx, "elasticSearch.queryState.cron").String(); cron != "" {
  63. err := EsStatusQuery.GetEsStatusRunning(cron, func(ctx context.Context) {
  64. finalStatus := EsStatusQuery.GetEsStatus(ctx)
  65. epm.esStatus = finalStatus
  66. _, _ = g.Redis().Set(ctx, fmt.Sprintf("%s_status", epm.redisPrefix), finalStatus)
  67. g.Log().Debugf(ctx, "当前 epm.esStatus:%v", epm.esStatus)
  68. })
  69. if err != nil {
  70. panic(err)
  71. }
  72. }
  73. }
  74. // GetProxy 获取代理对象
  75. func (epm *esProxyManager) GetProxy(ctx context.Context, queryLevel int) (*httputil.ReverseProxy, error) {
  76. if queryLevel+int(epm.esStatus) > 2 {
  77. go RejectedIncrement(ctx, epm.redisPrefix) //程序拒绝数
  78. return nil, fmt.Errorf("server is busy")
  79. }
  80. g.Log().Debugf(ctx, "esProxyManager pool %+v", epm.Status())
  81. Increment() //增加等待数
  82. defer Decrement()
  83. select {
  84. case <-epm.getPool(queryLevel):
  85. c := <-epm.proxyPool
  86. epm.proxyPool <- c
  87. return c, nil
  88. case <-time.After(time.Second * time.Duration(g.Cfg().MustGet(ctx, "elasticSearch.queryState.waitTime", 5).Int())):
  89. go OvertimeIncrement(ctx, epm.redisPrefix) //超时退出数
  90. return nil, fmt.Errorf("wait time out")
  91. }
  92. }
  93. // Release 归还链接池
  94. func (epm *esProxyManager) Release(ctx context.Context, queryLevel int) {
  95. go func() {
  96. epm.getPool(queryLevel) <- struct{}{}
  97. }()
  98. }
  99. // 获取对应查询复杂度的链接池
  100. func (epm *esProxyManager) getPool(queryLevel int) chan struct{} {
  101. switch queryLevel {
  102. case int(consts.QueryLevelSimple):
  103. return epm.simpleQueryPool
  104. case int(consts.QueryLevelAggs):
  105. return epm.aggsQueryPool
  106. default:
  107. return epm.complexQueryPool
  108. }
  109. }
  110. func (epm *esProxyManager) Status() map[string]interface{} {
  111. return map[string]interface{}{
  112. "simple": len(epm.simpleQueryPool),
  113. "aggs": len(epm.aggsQueryPool),
  114. "complex": len(epm.complexQueryPool),
  115. }
  116. }
  117. // QueueCounter 程序等待数 RejectedCounter程序繁忙拒绝数 OvertimeCounter超时拒绝数
  118. var (
  119. QueueCounter int64
  120. sy, sn sync.Mutex
  121. )
  122. func InformationNumber(ctx context.Context) map[string]interface{} {
  123. rejectedCount, _ := g.Redis().Get(ctx, "es_rejected_count")
  124. timeoutCount, _ := g.Redis().Get(ctx, "es_timeout_count")
  125. return map[string]interface{}{
  126. "simple": g.Cfg().MustGet(ctx, "elasticSearch.pool.simple", 10).Int() - len(EsProxyManager.simpleQueryPool), //简单执行数
  127. "aggs": g.Cfg().MustGet(ctx, "elasticSearch.pool.aggs", 10).Int() - len(EsProxyManager.aggsQueryPool), //聚合执行数
  128. "complex": g.Cfg().MustGet(ctx, "elasticSearch.pool.complex", 10).Int() - len(EsProxyManager.complexQueryPool), //复杂执行数
  129. "queueCount": QueueCounter, //等待数
  130. "rejectedCount": rejectedCount.Val(), //拒绝数
  131. "timeOutCount": timeoutCount.Val(), //超时数
  132. }
  133. }
  134. // RejectedIncrement queryLevel+int(epm.esStatus) > 2拒绝数
  135. func RejectedIncrement(ctx context.Context, redisPrefix string) {
  136. sy.Lock()
  137. defer sy.Unlock()
  138. _, _ = g.Redis().Incr(ctx, fmt.Sprintf("%s_rejected_count", redisPrefix))
  139. }
  140. // OvertimeIncrement 超时断开数
  141. func OvertimeIncrement(ctx context.Context, redisPrefix string) {
  142. sn.Lock()
  143. defer sn.Unlock()
  144. _, _ = g.Redis().Incr(ctx, fmt.Sprintf("%s_timeout_count", redisPrefix))
  145. }
  146. // Increment 程序等待数
  147. func Increment() {
  148. atomic.AddInt64(&QueueCounter, 1)
  149. }
  150. // Decrement 获取到连接池 减少程序等待数
  151. func Decrement() {
  152. atomic.AddInt64(&QueueCounter, -1)
  153. }