1
0

proxy_wrapper.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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.Tracef("enable health check monitor")
  101. }
  102. pw.pxy = NewProxy(pw.ctx, pw.Cfg, clientCfg, pw.msgTransporter)
  103. return pw
  104. }
  105. func (pw *Wrapper) SetInWorkConnCallback(cb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool) {
  106. pw.pxy.SetInWorkConnCallback(cb)
  107. }
  108. func (pw *Wrapper) SetRunningStatus(remoteAddr string, respErr string) error {
  109. pw.mu.Lock()
  110. defer pw.mu.Unlock()
  111. if pw.Phase != ProxyPhaseWaitStart {
  112. return fmt.Errorf("status not wait start, ignore start message")
  113. }
  114. pw.RemoteAddr = remoteAddr
  115. if respErr != "" {
  116. pw.Phase = ProxyPhaseStartErr
  117. pw.Err = respErr
  118. pw.lastStartErr = time.Now()
  119. return fmt.Errorf("%s", pw.Err)
  120. }
  121. if err := pw.pxy.Run(); err != nil {
  122. pw.close()
  123. pw.Phase = ProxyPhaseStartErr
  124. pw.Err = err.Error()
  125. pw.lastStartErr = time.Now()
  126. return err
  127. }
  128. pw.Phase = ProxyPhaseRunning
  129. pw.Err = ""
  130. return nil
  131. }
  132. func (pw *Wrapper) Start() {
  133. go pw.checkWorker()
  134. if pw.monitor != nil {
  135. go pw.monitor.Start()
  136. }
  137. }
  138. func (pw *Wrapper) Stop() {
  139. pw.mu.Lock()
  140. defer pw.mu.Unlock()
  141. close(pw.closeCh)
  142. close(pw.healthNotifyCh)
  143. pw.pxy.Close()
  144. if pw.monitor != nil {
  145. pw.monitor.Stop()
  146. }
  147. pw.Phase = ProxyPhaseClosed
  148. pw.close()
  149. }
  150. func (pw *Wrapper) close() {
  151. _ = pw.handler(&event.CloseProxyPayload{
  152. CloseProxyMsg: &msg.CloseProxy{
  153. ProxyName: pw.Name,
  154. },
  155. })
  156. }
  157. func (pw *Wrapper) checkWorker() {
  158. xl := pw.xl
  159. if pw.monitor != nil {
  160. // let monitor do check request first
  161. time.Sleep(500 * time.Millisecond)
  162. }
  163. for {
  164. // check proxy status
  165. now := time.Now()
  166. if atomic.LoadUint32(&pw.health) == 0 {
  167. pw.mu.Lock()
  168. if pw.Phase == ProxyPhaseNew ||
  169. pw.Phase == ProxyPhaseCheckFailed ||
  170. (pw.Phase == ProxyPhaseWaitStart && now.After(pw.lastSendStartMsg.Add(waitResponseTimeout))) ||
  171. (pw.Phase == ProxyPhaseStartErr && now.After(pw.lastStartErr.Add(startErrTimeout))) {
  172. xl.Tracef("change status from [%s] to [%s]", pw.Phase, ProxyPhaseWaitStart)
  173. pw.Phase = ProxyPhaseWaitStart
  174. var newProxyMsg msg.NewProxy
  175. pw.Cfg.MarshalToMsg(&newProxyMsg)
  176. pw.lastSendStartMsg = now
  177. _ = pw.handler(&event.StartProxyPayload{
  178. NewProxyMsg: &newProxyMsg,
  179. })
  180. }
  181. pw.mu.Unlock()
  182. } else {
  183. pw.mu.Lock()
  184. if pw.Phase == ProxyPhaseRunning || pw.Phase == ProxyPhaseWaitStart {
  185. pw.close()
  186. xl.Tracef("change status from [%s] to [%s]", pw.Phase, ProxyPhaseCheckFailed)
  187. pw.Phase = ProxyPhaseCheckFailed
  188. }
  189. pw.mu.Unlock()
  190. }
  191. select {
  192. case <-pw.closeCh:
  193. return
  194. case <-time.After(statusCheckInterval):
  195. case <-pw.healthNotifyCh:
  196. }
  197. }
  198. }
  199. func (pw *Wrapper) statusNormalCallback() {
  200. xl := pw.xl
  201. atomic.StoreUint32(&pw.health, 0)
  202. _ = errors.PanicToError(func() {
  203. select {
  204. case pw.healthNotifyCh <- struct{}{}:
  205. default:
  206. }
  207. })
  208. xl.Infof("health check success")
  209. }
  210. func (pw *Wrapper) statusFailedCallback() {
  211. xl := pw.xl
  212. atomic.StoreUint32(&pw.health, 1)
  213. _ = errors.PanicToError(func() {
  214. select {
  215. case pw.healthNotifyCh <- struct{}{}:
  216. default:
  217. }
  218. })
  219. xl.Infof("health check failed")
  220. }
  221. func (pw *Wrapper) InWorkConn(workConn net.Conn, m *msg.StartWorkConn) {
  222. xl := pw.xl
  223. pw.mu.RLock()
  224. pxy := pw.pxy
  225. pw.mu.RUnlock()
  226. if pxy != nil && pw.Phase == ProxyPhaseRunning {
  227. xl.Debugf("start a new work connection, localAddr: %s remoteAddr: %s", workConn.LocalAddr().String(), workConn.RemoteAddr().String())
  228. go pxy.InWorkConn(workConn, m)
  229. } else {
  230. workConn.Close()
  231. }
  232. }
  233. func (pw *Wrapper) GetStatus() *WorkingStatus {
  234. pw.mu.RLock()
  235. defer pw.mu.RUnlock()
  236. ps := &WorkingStatus{
  237. Name: pw.Name,
  238. Type: pw.Type,
  239. Phase: pw.Phase,
  240. Err: pw.Err,
  241. Cfg: pw.Cfg,
  242. RemoteAddr: pw.RemoteAddr,
  243. }
  244. return ps
  245. }