1
0

proxy_wrapper.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. // Copyright 2023 The frp Authors
  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 proxy
  15. import (
  16. "context"
  17. "fmt"
  18. "net"
  19. "sync"
  20. "sync/atomic"
  21. "time"
  22. "github.com/fatedier/golib/errors"
  23. "github.com/fatedier/frp/client/event"
  24. "github.com/fatedier/frp/client/health"
  25. "github.com/fatedier/frp/pkg/config"
  26. "github.com/fatedier/frp/pkg/msg"
  27. "github.com/fatedier/frp/pkg/transport"
  28. "github.com/fatedier/frp/pkg/util/xlog"
  29. )
  30. const (
  31. ProxyPhaseNew = "new"
  32. ProxyPhaseWaitStart = "wait start"
  33. ProxyPhaseStartErr = "start error"
  34. ProxyPhaseRunning = "running"
  35. ProxyPhaseCheckFailed = "check failed"
  36. ProxyPhaseClosed = "closed"
  37. )
  38. var (
  39. statusCheckInterval = 3 * time.Second
  40. waitResponseTimeout = 20 * time.Second
  41. startErrTimeout = 30 * time.Second
  42. )
  43. type WorkingStatus struct {
  44. Name string `json:"name"`
  45. Type string `json:"type"`
  46. Phase string `json:"status"`
  47. Err string `json:"err"`
  48. Cfg config.ProxyConf `json:"cfg"`
  49. // Got from server.
  50. RemoteAddr string `json:"remote_addr"`
  51. }
  52. type Wrapper struct {
  53. WorkingStatus
  54. // underlying proxy
  55. pxy Proxy
  56. // if ProxyConf has healcheck config
  57. // monitor will watch if it is alive
  58. monitor *health.Monitor
  59. // event handler
  60. handler event.Handler
  61. msgTransporter transport.MessageTransporter
  62. health uint32
  63. lastSendStartMsg time.Time
  64. lastStartErr time.Time
  65. closeCh chan struct{}
  66. healthNotifyCh chan struct{}
  67. mu sync.RWMutex
  68. xl *xlog.Logger
  69. ctx context.Context
  70. }
  71. func NewWrapper(
  72. ctx context.Context,
  73. cfg config.ProxyConf,
  74. clientCfg config.ClientCommonConf,
  75. eventHandler event.Handler,
  76. msgTransporter transport.MessageTransporter,
  77. ) *Wrapper {
  78. baseInfo := cfg.GetBaseInfo()
  79. xl := xlog.FromContextSafe(ctx).Spawn().AppendPrefix(baseInfo.ProxyName)
  80. pw := &Wrapper{
  81. WorkingStatus: WorkingStatus{
  82. Name: baseInfo.ProxyName,
  83. Type: baseInfo.ProxyType,
  84. Phase: ProxyPhaseNew,
  85. Cfg: cfg,
  86. },
  87. closeCh: make(chan struct{}),
  88. healthNotifyCh: make(chan struct{}),
  89. handler: eventHandler,
  90. msgTransporter: msgTransporter,
  91. xl: xl,
  92. ctx: xlog.NewContext(ctx, xl),
  93. }
  94. if baseInfo.HealthCheckType != "" {
  95. pw.health = 1 // means failed
  96. pw.monitor = health.NewMonitor(pw.ctx, baseInfo.HealthCheckType, baseInfo.HealthCheckIntervalS,
  97. baseInfo.HealthCheckTimeoutS, baseInfo.HealthCheckMaxFailed, baseInfo.HealthCheckAddr,
  98. baseInfo.HealthCheckURL, pw.statusNormalCallback, pw.statusFailedCallback)
  99. xl.Trace("enable health check monitor")
  100. }
  101. pw.pxy = NewProxy(pw.ctx, pw.Cfg, clientCfg, pw.msgTransporter)
  102. return pw
  103. }
  104. func (pw *Wrapper) SetRunningStatus(remoteAddr string, respErr string) error {
  105. pw.mu.Lock()
  106. defer pw.mu.Unlock()
  107. if pw.Phase != ProxyPhaseWaitStart {
  108. return fmt.Errorf("status not wait start, ignore start message")
  109. }
  110. pw.RemoteAddr = remoteAddr
  111. if respErr != "" {
  112. pw.Phase = ProxyPhaseStartErr
  113. pw.Err = respErr
  114. pw.lastStartErr = time.Now()
  115. return fmt.Errorf(pw.Err)
  116. }
  117. if err := pw.pxy.Run(); err != nil {
  118. pw.close()
  119. pw.Phase = ProxyPhaseStartErr
  120. pw.Err = err.Error()
  121. pw.lastStartErr = time.Now()
  122. return err
  123. }
  124. pw.Phase = ProxyPhaseRunning
  125. pw.Err = ""
  126. return nil
  127. }
  128. func (pw *Wrapper) Start() {
  129. go pw.checkWorker()
  130. if pw.monitor != nil {
  131. go pw.monitor.Start()
  132. }
  133. }
  134. func (pw *Wrapper) Stop() {
  135. pw.mu.Lock()
  136. defer pw.mu.Unlock()
  137. close(pw.closeCh)
  138. close(pw.healthNotifyCh)
  139. pw.pxy.Close()
  140. if pw.monitor != nil {
  141. pw.monitor.Stop()
  142. }
  143. pw.Phase = ProxyPhaseClosed
  144. pw.close()
  145. }
  146. func (pw *Wrapper) close() {
  147. _ = pw.handler(&event.CloseProxyPayload{
  148. CloseProxyMsg: &msg.CloseProxy{
  149. ProxyName: pw.Name,
  150. },
  151. })
  152. }
  153. func (pw *Wrapper) checkWorker() {
  154. xl := pw.xl
  155. if pw.monitor != nil {
  156. // let monitor do check request first
  157. time.Sleep(500 * time.Millisecond)
  158. }
  159. for {
  160. // check proxy status
  161. now := time.Now()
  162. if atomic.LoadUint32(&pw.health) == 0 {
  163. pw.mu.Lock()
  164. if pw.Phase == ProxyPhaseNew ||
  165. pw.Phase == ProxyPhaseCheckFailed ||
  166. (pw.Phase == ProxyPhaseWaitStart && now.After(pw.lastSendStartMsg.Add(waitResponseTimeout))) ||
  167. (pw.Phase == ProxyPhaseStartErr && now.After(pw.lastStartErr.Add(startErrTimeout))) {
  168. xl.Trace("change status from [%s] to [%s]", pw.Phase, ProxyPhaseWaitStart)
  169. pw.Phase = ProxyPhaseWaitStart
  170. var newProxyMsg msg.NewProxy
  171. pw.Cfg.MarshalToMsg(&newProxyMsg)
  172. pw.lastSendStartMsg = now
  173. _ = pw.handler(&event.StartProxyPayload{
  174. NewProxyMsg: &newProxyMsg,
  175. })
  176. }
  177. pw.mu.Unlock()
  178. } else {
  179. pw.mu.Lock()
  180. if pw.Phase == ProxyPhaseRunning || pw.Phase == ProxyPhaseWaitStart {
  181. pw.close()
  182. xl.Trace("change status from [%s] to [%s]", pw.Phase, ProxyPhaseCheckFailed)
  183. pw.Phase = ProxyPhaseCheckFailed
  184. }
  185. pw.mu.Unlock()
  186. }
  187. select {
  188. case <-pw.closeCh:
  189. return
  190. case <-time.After(statusCheckInterval):
  191. case <-pw.healthNotifyCh:
  192. }
  193. }
  194. }
  195. func (pw *Wrapper) statusNormalCallback() {
  196. xl := pw.xl
  197. atomic.StoreUint32(&pw.health, 0)
  198. _ = errors.PanicToError(func() {
  199. select {
  200. case pw.healthNotifyCh <- struct{}{}:
  201. default:
  202. }
  203. })
  204. xl.Info("health check success")
  205. }
  206. func (pw *Wrapper) statusFailedCallback() {
  207. xl := pw.xl
  208. atomic.StoreUint32(&pw.health, 1)
  209. _ = errors.PanicToError(func() {
  210. select {
  211. case pw.healthNotifyCh <- struct{}{}:
  212. default:
  213. }
  214. })
  215. xl.Info("health check failed")
  216. }
  217. func (pw *Wrapper) InWorkConn(workConn net.Conn, m *msg.StartWorkConn) {
  218. xl := pw.xl
  219. pw.mu.RLock()
  220. pxy := pw.pxy
  221. pw.mu.RUnlock()
  222. if pxy != nil && pw.Phase == ProxyPhaseRunning {
  223. xl.Debug("start a new work connection, localAddr: %s remoteAddr: %s", workConn.LocalAddr().String(), workConn.RemoteAddr().String())
  224. go pxy.InWorkConn(workConn, m)
  225. } else {
  226. workConn.Close()
  227. }
  228. }
  229. func (pw *Wrapper) GetStatus() *WorkingStatus {
  230. pw.mu.RLock()
  231. defer pw.mu.RUnlock()
  232. ps := &WorkingStatus{
  233. Name: pw.Name,
  234. Type: pw.Type,
  235. Phase: pw.Phase,
  236. Err: pw.Err,
  237. Cfg: pw.Cfg,
  238. RemoteAddr: pw.RemoteAddr,
  239. }
  240. return ps
  241. }