health.go 3.8 KB

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