1
0

proxy_wrapper.go 6.4 KB

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