health.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package client
  2. import (
  3. "container/heap"
  4. "github.com/cnlh/nps/lib/conn"
  5. "github.com/cnlh/nps/lib/file"
  6. "github.com/cnlh/nps/lib/sheap"
  7. "github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
  8. "github.com/pkg/errors"
  9. "net"
  10. "net/http"
  11. "strings"
  12. "time"
  13. )
  14. var isStart bool
  15. var serverConn *conn.Conn
  16. func heathCheck(healths []*file.Health, c *conn.Conn) bool {
  17. serverConn = c
  18. if isStart {
  19. for _, v := range healths {
  20. v.HealthMap = make(map[string]int)
  21. }
  22. return true
  23. }
  24. isStart = true
  25. h := &sheap.IntHeap{}
  26. for _, v := range healths {
  27. if v.HealthMaxFail > 0 && v.HealthCheckTimeout > 0 && v.HealthCheckInterval > 0 {
  28. v.HealthNextTime = time.Now().Add(time.Duration(v.HealthCheckInterval) * time.Second)
  29. heap.Push(h, v.HealthNextTime.Unix())
  30. v.HealthMap = make(map[string]int)
  31. }
  32. }
  33. go session(healths, h)
  34. return true
  35. }
  36. func session(healths []*file.Health, h *sheap.IntHeap) {
  37. for {
  38. if h.Len() == 0 {
  39. logs.Error("health check error")
  40. break
  41. }
  42. rs := heap.Pop(h).(int64) - time.Now().Unix()
  43. if rs <= 0 {
  44. continue
  45. }
  46. timer := time.NewTimer(time.Duration(rs) * time.Second)
  47. select {
  48. case <-timer.C:
  49. for _, v := range healths {
  50. if v.HealthNextTime.Before(time.Now()) {
  51. v.HealthNextTime = time.Now().Add(time.Duration(v.HealthCheckInterval) * time.Second)
  52. //check
  53. go check(v)
  54. //reset time
  55. heap.Push(h, v.HealthNextTime.Unix())
  56. }
  57. }
  58. }
  59. }
  60. }
  61. //只针对一个端口 面向多个目标的情况
  62. func check(t *file.Health) {
  63. arr := strings.Split(t.HealthCheckTarget, ",")
  64. var err error
  65. var rs *http.Response
  66. for _, v := range arr {
  67. if t.HealthCheckType == "tcp" {
  68. _, err = net.DialTimeout("tcp", v, time.Duration(t.HealthCheckTimeout)*time.Second);
  69. } else {
  70. client := &http.Client{}
  71. client.Timeout = time.Duration(t.HealthCheckTimeout) * time.Second
  72. rs, err = client.Get("http://" + v + t.HttpHealthUrl)
  73. if err == nil && rs.StatusCode != 200 {
  74. err = errors.New("status code is not match")
  75. }
  76. }
  77. if err != nil {
  78. t.HealthMap[v] += 1
  79. } else if t.HealthMap[v] >= t.HealthMaxFail {
  80. //send recovery add
  81. serverConn.SendHealthInfo(v, "1")
  82. t.HealthMap[v] = 0
  83. }
  84. if t.HealthMap[v] == t.HealthMaxFail {
  85. //send fail remove
  86. serverConn.SendHealthInfo(v, "0")
  87. }
  88. }
  89. }