health.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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. "net"
  21. "net/http"
  22. "strings"
  23. "time"
  24. v1 "github.com/fatedier/frp/pkg/config/v1"
  25. "github.com/fatedier/frp/pkg/util/xlog"
  26. )
  27. var ErrHealthCheckType = errors.New("error health check type")
  28. type Monitor struct {
  29. checkType string
  30. interval time.Duration
  31. timeout time.Duration
  32. maxFailedTimes int
  33. // For tcp
  34. addr string
  35. // For http
  36. url string
  37. header http.Header
  38. failedTimes uint64
  39. statusOK bool
  40. statusNormalFn func()
  41. statusFailedFn func()
  42. ctx context.Context
  43. cancel context.CancelFunc
  44. }
  45. func NewMonitor(ctx context.Context, cfg v1.HealthCheckConfig, addr string,
  46. statusNormalFn func(), statusFailedFn func(),
  47. ) *Monitor {
  48. if cfg.IntervalSeconds <= 0 {
  49. cfg.IntervalSeconds = 10
  50. }
  51. if cfg.TimeoutSeconds <= 0 {
  52. cfg.TimeoutSeconds = 3
  53. }
  54. if cfg.MaxFailed <= 0 {
  55. cfg.MaxFailed = 1
  56. }
  57. newctx, cancel := context.WithCancel(ctx)
  58. var url string
  59. if cfg.Type == "http" && cfg.Path != "" {
  60. s := "http://" + addr
  61. if !strings.HasPrefix(cfg.Path, "/") {
  62. s += "/"
  63. }
  64. url = s + cfg.Path
  65. }
  66. header := make(http.Header)
  67. for _, h := range cfg.HTTPHeaders {
  68. header.Set(h.Name, h.Value)
  69. }
  70. return &Monitor{
  71. checkType: cfg.Type,
  72. interval: time.Duration(cfg.IntervalSeconds) * time.Second,
  73. timeout: time.Duration(cfg.TimeoutSeconds) * time.Second,
  74. maxFailedTimes: cfg.MaxFailed,
  75. addr: addr,
  76. url: url,
  77. header: header,
  78. statusOK: false,
  79. statusNormalFn: statusNormalFn,
  80. statusFailedFn: statusFailedFn,
  81. ctx: newctx,
  82. cancel: cancel,
  83. }
  84. }
  85. func (monitor *Monitor) Start() {
  86. go monitor.checkWorker()
  87. }
  88. func (monitor *Monitor) Stop() {
  89. monitor.cancel()
  90. }
  91. func (monitor *Monitor) checkWorker() {
  92. xl := xlog.FromContextSafe(monitor.ctx)
  93. for {
  94. doCtx, cancel := context.WithDeadline(monitor.ctx, time.Now().Add(monitor.timeout))
  95. err := monitor.doCheck(doCtx)
  96. // check if this monitor has been closed
  97. select {
  98. case <-monitor.ctx.Done():
  99. cancel()
  100. return
  101. default:
  102. cancel()
  103. }
  104. if err == nil {
  105. xl.Tracef("do one health check success")
  106. if !monitor.statusOK && monitor.statusNormalFn != nil {
  107. xl.Infof("health check status change to success")
  108. monitor.statusOK = true
  109. monitor.statusNormalFn()
  110. }
  111. } else {
  112. xl.Warnf("do one health check failed: %v", err)
  113. monitor.failedTimes++
  114. if monitor.statusOK && int(monitor.failedTimes) >= monitor.maxFailedTimes && monitor.statusFailedFn != nil {
  115. xl.Warnf("health check status change to failed")
  116. monitor.statusOK = false
  117. monitor.statusFailedFn()
  118. }
  119. }
  120. time.Sleep(monitor.interval)
  121. }
  122. }
  123. func (monitor *Monitor) doCheck(ctx context.Context) error {
  124. switch monitor.checkType {
  125. case "tcp":
  126. return monitor.doTCPCheck(ctx)
  127. case "http":
  128. return monitor.doHTTPCheck(ctx)
  129. default:
  130. return ErrHealthCheckType
  131. }
  132. }
  133. func (monitor *Monitor) doTCPCheck(ctx context.Context) error {
  134. // if tcp address is not specified, always return nil
  135. if monitor.addr == "" {
  136. return nil
  137. }
  138. var d net.Dialer
  139. conn, err := d.DialContext(ctx, "tcp", monitor.addr)
  140. if err != nil {
  141. return err
  142. }
  143. conn.Close()
  144. return nil
  145. }
  146. func (monitor *Monitor) doHTTPCheck(ctx context.Context) error {
  147. req, err := http.NewRequestWithContext(ctx, "GET", monitor.url, nil)
  148. if err != nil {
  149. return err
  150. }
  151. req.Header = monitor.header
  152. req.Host = monitor.header.Get("Host")
  153. resp, err := http.DefaultClient.Do(req)
  154. if err != nil {
  155. return err
  156. }
  157. defer resp.Body.Close()
  158. _, _ = io.Copy(io.Discard, resp.Body)
  159. if resp.StatusCode/100 != 2 {
  160. return fmt.Errorf("do http health check, StatusCode is [%d] not 2xx", resp.StatusCode)
  161. }
  162. return nil
  163. }