health.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. // Copyright 2018 fatedier, fatedier@gmail.com
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package health
  15. import (
  16. "context"
  17. "errors"
  18. "fmt"
  19. "io"
  20. "io/ioutil"
  21. "net"
  22. "net/http"
  23. "time"
  24. "github.com/fatedier/frp/utils/log"
  25. )
  26. var (
  27. ErrHealthCheckType = errors.New("error health check type")
  28. )
  29. type HealthCheckMonitor struct {
  30. checkType string
  31. interval time.Duration
  32. timeout time.Duration
  33. maxFailedTimes int
  34. // For tcp
  35. addr string
  36. // For http
  37. url string
  38. failedTimes uint64
  39. statusOK bool
  40. statusNormalFn func()
  41. statusFailedFn func()
  42. ctx context.Context
  43. cancel context.CancelFunc
  44. l log.Logger
  45. }
  46. func NewHealthCheckMonitor(checkType string, intervalS int, timeoutS int, maxFailedTimes int, addr string, url string,
  47. statusNormalFn func(), statusFailedFn func()) *HealthCheckMonitor {
  48. if intervalS <= 0 {
  49. intervalS = 10
  50. }
  51. if timeoutS <= 0 {
  52. timeoutS = 3
  53. }
  54. if maxFailedTimes <= 0 {
  55. maxFailedTimes = 1
  56. }
  57. ctx, cancel := context.WithCancel(context.Background())
  58. return &HealthCheckMonitor{
  59. checkType: checkType,
  60. interval: time.Duration(intervalS) * time.Second,
  61. timeout: time.Duration(timeoutS) * time.Second,
  62. maxFailedTimes: maxFailedTimes,
  63. addr: addr,
  64. url: url,
  65. statusOK: false,
  66. statusNormalFn: statusNormalFn,
  67. statusFailedFn: statusFailedFn,
  68. ctx: ctx,
  69. cancel: cancel,
  70. }
  71. }
  72. func (monitor *HealthCheckMonitor) SetLogger(l log.Logger) {
  73. monitor.l = l
  74. }
  75. func (monitor *HealthCheckMonitor) Start() {
  76. go monitor.checkWorker()
  77. }
  78. func (monitor *HealthCheckMonitor) Stop() {
  79. monitor.cancel()
  80. }
  81. func (monitor *HealthCheckMonitor) checkWorker() {
  82. for {
  83. doCtx, cancel := context.WithDeadline(monitor.ctx, time.Now().Add(monitor.timeout))
  84. err := monitor.doCheck(doCtx)
  85. // check if this monitor has been closed
  86. select {
  87. case <-monitor.ctx.Done():
  88. cancel()
  89. return
  90. default:
  91. cancel()
  92. }
  93. if err == nil {
  94. if monitor.l != nil {
  95. monitor.l.Trace("do one health check success")
  96. }
  97. if !monitor.statusOK && monitor.statusNormalFn != nil {
  98. if monitor.l != nil {
  99. monitor.l.Info("health check status change to success")
  100. }
  101. monitor.statusOK = true
  102. monitor.statusNormalFn()
  103. }
  104. } else {
  105. if monitor.l != nil {
  106. monitor.l.Warn("do one health check failed: %v", err)
  107. }
  108. monitor.failedTimes++
  109. if monitor.statusOK && int(monitor.failedTimes) >= monitor.maxFailedTimes && monitor.statusFailedFn != nil {
  110. if monitor.l != nil {
  111. monitor.l.Warn("health check status change to failed")
  112. }
  113. monitor.statusOK = false
  114. monitor.statusFailedFn()
  115. }
  116. }
  117. time.Sleep(monitor.interval)
  118. }
  119. }
  120. func (monitor *HealthCheckMonitor) doCheck(ctx context.Context) error {
  121. switch monitor.checkType {
  122. case "tcp":
  123. return monitor.doTcpCheck(ctx)
  124. case "http":
  125. return monitor.doHttpCheck(ctx)
  126. default:
  127. return ErrHealthCheckType
  128. }
  129. }
  130. func (monitor *HealthCheckMonitor) doTcpCheck(ctx context.Context) error {
  131. // if tcp address is not specified, always return nil
  132. if monitor.addr == "" {
  133. return nil
  134. }
  135. var d net.Dialer
  136. conn, err := d.DialContext(ctx, "tcp", monitor.addr)
  137. if err != nil {
  138. return err
  139. }
  140. conn.Close()
  141. return nil
  142. }
  143. func (monitor *HealthCheckMonitor) doHttpCheck(ctx context.Context) error {
  144. req, err := http.NewRequest("GET", monitor.url, nil)
  145. if err != nil {
  146. return err
  147. }
  148. resp, err := http.DefaultClient.Do(req)
  149. if err != nil {
  150. return err
  151. }
  152. defer resp.Body.Close()
  153. io.Copy(ioutil.Discard, resp.Body)
  154. if resp.StatusCode/100 != 2 {
  155. return fmt.Errorf("do http health check, StatusCode is [%d] not 2xx", resp.StatusCode)
  156. }
  157. return nil
  158. }