health.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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/xlog"
  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. }
  45. func NewHealthCheckMonitor(ctx context.Context, checkType string,
  46. intervalS int, timeoutS int, maxFailedTimes int,
  47. addr string, url string,
  48. statusNormalFn func(), statusFailedFn func()) *HealthCheckMonitor {
  49. if intervalS <= 0 {
  50. intervalS = 10
  51. }
  52. if timeoutS <= 0 {
  53. timeoutS = 3
  54. }
  55. if maxFailedTimes <= 0 {
  56. maxFailedTimes = 1
  57. }
  58. newctx, cancel := context.WithCancel(ctx)
  59. return &HealthCheckMonitor{
  60. checkType: checkType,
  61. interval: time.Duration(intervalS) * time.Second,
  62. timeout: time.Duration(timeoutS) * time.Second,
  63. maxFailedTimes: maxFailedTimes,
  64. addr: addr,
  65. url: url,
  66. statusOK: false,
  67. statusNormalFn: statusNormalFn,
  68. statusFailedFn: statusFailedFn,
  69. ctx: newctx,
  70. cancel: cancel,
  71. }
  72. }
  73. func (monitor *HealthCheckMonitor) Start() {
  74. go monitor.checkWorker()
  75. }
  76. func (monitor *HealthCheckMonitor) Stop() {
  77. monitor.cancel()
  78. }
  79. func (monitor *HealthCheckMonitor) checkWorker() {
  80. xl := xlog.FromContextSafe(monitor.ctx)
  81. for {
  82. doCtx, cancel := context.WithDeadline(monitor.ctx, time.Now().Add(monitor.timeout))
  83. err := monitor.doCheck(doCtx)
  84. // check if this monitor has been closed
  85. select {
  86. case <-monitor.ctx.Done():
  87. cancel()
  88. return
  89. default:
  90. cancel()
  91. }
  92. if err == nil {
  93. xl.Trace("do one health check success")
  94. if !monitor.statusOK && monitor.statusNormalFn != nil {
  95. xl.Info("health check status change to success")
  96. monitor.statusOK = true
  97. monitor.statusNormalFn()
  98. }
  99. } else {
  100. xl.Warn("do one health check failed: %v", err)
  101. monitor.failedTimes++
  102. if monitor.statusOK && int(monitor.failedTimes) >= monitor.maxFailedTimes && monitor.statusFailedFn != nil {
  103. xl.Warn("health check status change to failed")
  104. monitor.statusOK = false
  105. monitor.statusFailedFn()
  106. }
  107. }
  108. time.Sleep(monitor.interval)
  109. }
  110. }
  111. func (monitor *HealthCheckMonitor) doCheck(ctx context.Context) error {
  112. switch monitor.checkType {
  113. case "tcp":
  114. return monitor.doTcpCheck(ctx)
  115. case "http":
  116. return monitor.doHttpCheck(ctx)
  117. default:
  118. return ErrHealthCheckType
  119. }
  120. }
  121. func (monitor *HealthCheckMonitor) doTcpCheck(ctx context.Context) error {
  122. // if tcp address is not specified, always return nil
  123. if monitor.addr == "" {
  124. return nil
  125. }
  126. var d net.Dialer
  127. conn, err := d.DialContext(ctx, "tcp", monitor.addr)
  128. if err != nil {
  129. return err
  130. }
  131. conn.Close()
  132. return nil
  133. }
  134. func (monitor *HealthCheckMonitor) doHttpCheck(ctx context.Context) error {
  135. req, err := http.NewRequest("GET", monitor.url, nil)
  136. if err != nil {
  137. return err
  138. }
  139. resp, err := http.DefaultClient.Do(req)
  140. if err != nil {
  141. return err
  142. }
  143. defer resp.Body.Close()
  144. io.Copy(ioutil.Discard, resp.Body)
  145. if resp.StatusCode/100 != 2 {
  146. return fmt.Errorf("do http health check, StatusCode is [%d] not 2xx", resp.StatusCode)
  147. }
  148. return nil
  149. }