health.go 3.8 KB

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