control.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. package server
  2. import (
  3. "fmt"
  4. "io"
  5. "sync"
  6. "time"
  7. "github.com/fatedier/frp/models/config"
  8. "github.com/fatedier/frp/models/consts"
  9. "github.com/fatedier/frp/models/msg"
  10. "github.com/fatedier/frp/utils/errors"
  11. "github.com/fatedier/frp/utils/net"
  12. "github.com/fatedier/frp/utils/shutdown"
  13. "github.com/fatedier/frp/utils/version"
  14. )
  15. type Control struct {
  16. // frps service
  17. svr *Service
  18. // login message
  19. loginMsg *msg.Login
  20. // control connection
  21. conn net.Conn
  22. // put a message in this channel to send it over control connection to client
  23. sendCh chan (msg.Message)
  24. // read from this channel to get the next message sent by client
  25. readCh chan (msg.Message)
  26. // work connections
  27. workConnCh chan net.Conn
  28. // proxies in one client
  29. proxies []Proxy
  30. // pool count
  31. poolCount int
  32. // last time got the Ping message
  33. lastPing time.Time
  34. // A new run id will be generated when a new client login.
  35. // If run id got from login message has same run id, it means it's the same client, so we can
  36. // replace old controller instantly.
  37. runId string
  38. // control status
  39. status string
  40. readerShutdown *shutdown.Shutdown
  41. writerShutdown *shutdown.Shutdown
  42. managerShutdown *shutdown.Shutdown
  43. allShutdown *shutdown.Shutdown
  44. mu sync.RWMutex
  45. }
  46. func NewControl(svr *Service, ctlConn net.Conn, loginMsg *msg.Login) *Control {
  47. return &Control{
  48. svr: svr,
  49. conn: ctlConn,
  50. loginMsg: loginMsg,
  51. sendCh: make(chan msg.Message, 10),
  52. readCh: make(chan msg.Message, 10),
  53. workConnCh: make(chan net.Conn, loginMsg.PoolCount+10),
  54. proxies: make([]Proxy, 0),
  55. poolCount: loginMsg.PoolCount,
  56. lastPing: time.Now(),
  57. runId: loginMsg.RunId,
  58. status: consts.Working,
  59. readerShutdown: shutdown.New(),
  60. writerShutdown: shutdown.New(),
  61. managerShutdown: shutdown.New(),
  62. allShutdown: shutdown.New(),
  63. }
  64. }
  65. // Start send a login success message to client and start working.
  66. func (ctl *Control) Start() {
  67. go ctl.writer()
  68. ctl.sendCh <- &msg.LoginResp{
  69. Version: version.Full(),
  70. RunId: ctl.runId,
  71. Error: "",
  72. }
  73. for i := 0; i < ctl.poolCount; i++ {
  74. ctl.sendCh <- &msg.ReqWorkConn{}
  75. }
  76. go ctl.manager()
  77. go ctl.reader()
  78. go ctl.stoper()
  79. }
  80. func (ctl *Control) RegisterWorkConn(conn net.Conn) {
  81. defer func() {
  82. if err := recover(); err != nil {
  83. ctl.conn.Error("panic error: %v", err)
  84. }
  85. }()
  86. select {
  87. case ctl.workConnCh <- conn:
  88. ctl.conn.Debug("new work connection registered.")
  89. default:
  90. ctl.conn.Debug("work connection pool is full, discarding.")
  91. conn.Close()
  92. }
  93. }
  94. // When frps get one user connection, we get one work connection from the pool and return it.
  95. // If no workConn available in the pool, send message to frpc to get one or more
  96. // and wait until it is available.
  97. // return an error if wait timeout
  98. func (ctl *Control) GetWorkConn() (workConn net.Conn, err error) {
  99. defer func() {
  100. if err := recover(); err != nil {
  101. ctl.conn.Error("panic error: %v", err)
  102. }
  103. }()
  104. var ok bool
  105. // get a work connection from the pool
  106. select {
  107. case workConn, ok = <-ctl.workConnCh:
  108. if !ok {
  109. err = fmt.Errorf("no work connections available, control is closing")
  110. return
  111. }
  112. ctl.conn.Debug("get work connection from pool")
  113. default:
  114. // no work connections available in the poll, send message to frpc to get more
  115. err = errors.PanicToError(func() {
  116. ctl.sendCh <- &msg.ReqWorkConn{}
  117. })
  118. if err != nil {
  119. ctl.conn.Error("%v", err)
  120. return
  121. }
  122. select {
  123. case workConn, ok = <-ctl.workConnCh:
  124. if !ok {
  125. err = fmt.Errorf("no work connections available, control is closing")
  126. ctl.conn.Warn("%v", err)
  127. return
  128. }
  129. case <-time.After(time.Duration(config.ServerCommonCfg.UserConnTimeout) * time.Second):
  130. err = fmt.Errorf("timeout trying to get work connection")
  131. ctl.conn.Warn("%v", err)
  132. return
  133. }
  134. }
  135. // When we get a work connection from pool, replace it with a new one.
  136. errors.PanicToError(func() {
  137. ctl.sendCh <- &msg.ReqWorkConn{}
  138. })
  139. return
  140. }
  141. func (ctl *Control) Replaced(newCtl *Control) {
  142. ctl.conn.Info("Replaced by client [%s]", newCtl.runId)
  143. ctl.runId = ""
  144. ctl.allShutdown.Start()
  145. }
  146. func (ctl *Control) writer() {
  147. defer func() {
  148. if err := recover(); err != nil {
  149. ctl.conn.Error("panic error: %v", err)
  150. }
  151. }()
  152. defer ctl.allShutdown.Start()
  153. defer ctl.writerShutdown.Done()
  154. for {
  155. if m, ok := <-ctl.sendCh; !ok {
  156. ctl.conn.Info("control writer is closing")
  157. return
  158. } else {
  159. if err := msg.WriteMsg(ctl.conn, m); err != nil {
  160. ctl.conn.Warn("write message to control connection error: %v", err)
  161. return
  162. }
  163. }
  164. }
  165. }
  166. func (ctl *Control) reader() {
  167. defer func() {
  168. if err := recover(); err != nil {
  169. ctl.conn.Error("panic error: %v", err)
  170. }
  171. }()
  172. defer ctl.allShutdown.Start()
  173. defer ctl.readerShutdown.Done()
  174. for {
  175. if m, err := msg.ReadMsg(ctl.conn); err != nil {
  176. if err == io.EOF {
  177. ctl.conn.Debug("control connection closed")
  178. return
  179. } else {
  180. ctl.conn.Warn("read error: %v", err)
  181. return
  182. }
  183. } else {
  184. ctl.readCh <- m
  185. }
  186. }
  187. }
  188. func (ctl *Control) stoper() {
  189. defer func() {
  190. if err := recover(); err != nil {
  191. ctl.conn.Error("panic error: %v", err)
  192. }
  193. }()
  194. ctl.allShutdown.WaitStart()
  195. close(ctl.readCh)
  196. ctl.managerShutdown.WaitDown()
  197. close(ctl.sendCh)
  198. ctl.writerShutdown.WaitDown()
  199. ctl.conn.Close()
  200. close(ctl.workConnCh)
  201. for workConn := range ctl.workConnCh {
  202. workConn.Close()
  203. }
  204. for _, pxy := range ctl.proxies {
  205. ctl.svr.DelProxy(pxy.GetName())
  206. pxy.Close()
  207. }
  208. ctl.allShutdown.Done()
  209. ctl.conn.Info("all shutdown success")
  210. }
  211. func (ctl *Control) manager() {
  212. defer func() {
  213. if err := recover(); err != nil {
  214. ctl.conn.Error("panic error: %v", err)
  215. }
  216. }()
  217. defer ctl.allShutdown.Start()
  218. defer ctl.managerShutdown.Done()
  219. heartbeat := time.NewTicker(time.Second)
  220. defer heartbeat.Stop()
  221. for {
  222. select {
  223. case <-heartbeat.C:
  224. if time.Since(ctl.lastPing) > time.Duration(config.ServerCommonCfg.HeartBeatTimeout)*time.Second {
  225. ctl.conn.Warn("heartbeat timeout")
  226. ctl.allShutdown.Start()
  227. }
  228. case rawMsg, ok := <-ctl.readCh:
  229. if !ok {
  230. return
  231. }
  232. switch m := rawMsg.(type) {
  233. case *msg.NewProxy:
  234. // register proxy in this control
  235. err := ctl.RegisterProxy(m)
  236. resp := &msg.NewProxyResp{
  237. ProxyName: m.ProxyName,
  238. }
  239. if err != nil {
  240. resp.Error = err.Error()
  241. ctl.conn.Warn("new proxy [%s] error: %v", m.ProxyName, err)
  242. } else {
  243. ctl.conn.Info("new proxy [%s] success", m.ProxyName)
  244. }
  245. ctl.sendCh <- resp
  246. case *msg.Ping:
  247. ctl.lastPing = time.Now()
  248. ctl.sendCh <- &msg.Pong{}
  249. }
  250. }
  251. }
  252. }
  253. func (ctl *Control) RegisterProxy(pxyMsg *msg.NewProxy) (err error) {
  254. var pxyConf config.ProxyConf
  255. // Load configures from NewProxy message and check.
  256. pxyConf, err = config.NewProxyConf(pxyMsg)
  257. if err != nil {
  258. return err
  259. }
  260. // NewProxy will return a interface Proxy.
  261. // In fact it create different proxies by different proxy type, we just call run() here.
  262. pxy, err := NewProxy(ctl, pxyConf)
  263. if err != nil {
  264. return err
  265. }
  266. err = pxy.Run()
  267. if err != nil {
  268. return err
  269. }
  270. defer func() {
  271. if err != nil {
  272. pxy.Close()
  273. }
  274. }()
  275. err = ctl.svr.RegisterProxy(pxyMsg.ProxyName, pxy)
  276. if err != nil {
  277. return err
  278. }
  279. ctl.proxies = append(ctl.proxies, pxy)
  280. return nil
  281. }