mux.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. package mux
  2. import (
  3. "errors"
  4. "io"
  5. "math"
  6. "net"
  7. "os"
  8. "sync/atomic"
  9. "time"
  10. "ehang.io/nps/lib/common"
  11. "github.com/astaxie/beego/logs"
  12. )
  13. type Mux struct {
  14. latency uint64 // we store latency in bits, but it's float64
  15. net.Listener
  16. conn net.Conn
  17. connMap *connMap
  18. newConnCh chan *conn
  19. id int32
  20. closeChan chan struct{}
  21. IsClose bool
  22. pingOk uint32
  23. counter *latencyCounter
  24. bw *bandwidth
  25. pingCh chan []byte
  26. pingCheckTime uint32
  27. connType string
  28. writeQueue PriorityQueue
  29. newConnQueue ConnQueue
  30. }
  31. func NewMux(c net.Conn, connType string) *Mux {
  32. //c.(*net.TCPConn).SetReadBuffer(0)
  33. //c.(*net.TCPConn).SetWriteBuffer(0)
  34. _ = c.SetDeadline(time.Time{})
  35. fd, err := getConnFd(c)
  36. if err != nil {
  37. logs.Warn(err)
  38. }
  39. m := &Mux{
  40. conn: c,
  41. connMap: NewConnMap(),
  42. id: 0,
  43. closeChan: make(chan struct{}, 1),
  44. newConnCh: make(chan *conn),
  45. bw: NewBandwidth(fd),
  46. IsClose: false,
  47. connType: connType,
  48. pingCh: make(chan []byte),
  49. counter: newLatencyCounter(),
  50. }
  51. m.writeQueue.New()
  52. m.newConnQueue.New()
  53. //read session by flag
  54. m.readSession()
  55. //ping
  56. m.ping()
  57. m.pingReturn()
  58. m.writeSession()
  59. return m
  60. }
  61. func (s *Mux) NewConn() (*conn, error) {
  62. if s.IsClose {
  63. return nil, errors.New("the mux has closed")
  64. }
  65. conn := NewConn(s.getId(), s, "nps ")
  66. //it must be set before send
  67. s.connMap.Set(conn.connId, conn)
  68. s.sendInfo(common.MUX_NEW_CONN, conn.connId, nil)
  69. //set a timer timeout 30 second
  70. timer := time.NewTimer(time.Minute * 2)
  71. defer timer.Stop()
  72. select {
  73. case <-conn.connStatusOkCh:
  74. return conn, nil
  75. case <-conn.connStatusFailCh:
  76. case <-timer.C:
  77. }
  78. return nil, errors.New("create connection fail,the server refused the connection")
  79. }
  80. func (s *Mux) Accept() (net.Conn, error) {
  81. if s.IsClose {
  82. return nil, errors.New("accpet error,the mux has closed")
  83. }
  84. conn := <-s.newConnCh
  85. if conn == nil {
  86. return nil, errors.New("accpet error,the conn has closed")
  87. }
  88. return conn, nil
  89. }
  90. func (s *Mux) Addr() net.Addr {
  91. return s.conn.LocalAddr()
  92. }
  93. func (s *Mux) sendInfo(flag uint8, id int32, data ...interface{}) {
  94. if s.IsClose {
  95. return
  96. }
  97. var err error
  98. pack := common.MuxPack.Get()
  99. err = pack.NewPac(flag, id, data...)
  100. if err != nil {
  101. common.MuxPack.Put(pack)
  102. logs.Error("mux: new pack err", err)
  103. s.Close()
  104. return
  105. }
  106. s.writeQueue.Push(pack)
  107. return
  108. }
  109. func (s *Mux) writeSession() {
  110. go s.packBuf()
  111. //go s.writeBuf()
  112. }
  113. func (s *Mux) packBuf() {
  114. //buffer := common.BuffPool.Get()
  115. for {
  116. if s.IsClose {
  117. break
  118. }
  119. //buffer.Reset()
  120. pack := s.writeQueue.Pop()
  121. if s.IsClose {
  122. break
  123. }
  124. //buffer := common.BuffPool.Get()
  125. err := pack.Pack(s.conn)
  126. common.MuxPack.Put(pack)
  127. if err != nil {
  128. logs.Error("mux: pack err", err)
  129. //common.BuffPool.Put(buffer)
  130. s.Close()
  131. break
  132. }
  133. //logs.Warn(buffer.String())
  134. //s.bufQueue.Push(buffer)
  135. //l := buffer.Len()
  136. //n, err := buffer.WriteTo(s.conn)
  137. //common.BuffPool.Put(buffer)
  138. //if err != nil || int(n) != l {
  139. // logs.Error("mux: close from write session fail ", err, n, l)
  140. // s.Close()
  141. // break
  142. //}
  143. }
  144. }
  145. //func (s *Mux) writeBuf() {
  146. // for {
  147. // if s.IsClose {
  148. // break
  149. // }
  150. // buffer, err := s.bufQueue.Pop()
  151. // if err != nil {
  152. // break
  153. // }
  154. // l := buffer.Len()
  155. // n, err := buffer.WriteTo(s.conn)
  156. // common.BuffPool.Put(buffer)
  157. // if err != nil || int(n) != l {
  158. // logs.Warn("close from write session fail ", err, n, l)
  159. // s.Close()
  160. // break
  161. // }
  162. // }
  163. //}
  164. func (s *Mux) ping() {
  165. go func() {
  166. now, _ := time.Now().UTC().MarshalText()
  167. s.sendInfo(common.MUX_PING_FLAG, common.MUX_PING, now)
  168. // send the ping flag and get the latency first
  169. ticker := time.NewTicker(time.Second * 5)
  170. defer ticker.Stop()
  171. for {
  172. if s.IsClose {
  173. break
  174. }
  175. select {
  176. case <-ticker.C:
  177. }
  178. if atomic.LoadUint32(&s.pingCheckTime) >= 60 {
  179. logs.Error("mux: ping time out")
  180. s.Close()
  181. // more than 5 minutes not receive the ping return package,
  182. // mux conn is damaged, maybe a packet drop, close it
  183. break
  184. }
  185. now, _ := time.Now().UTC().MarshalText()
  186. s.sendInfo(common.MUX_PING_FLAG, common.MUX_PING, now)
  187. atomic.AddUint32(&s.pingCheckTime, 1)
  188. if atomic.LoadUint32(&s.pingOk) > 10 && s.connType == "kcp" {
  189. logs.Error("mux: kcp ping err")
  190. s.Close()
  191. break
  192. }
  193. atomic.AddUint32(&s.pingOk, 1)
  194. }
  195. return
  196. }()
  197. }
  198. func (s *Mux) pingReturn() {
  199. go func() {
  200. var now time.Time
  201. var data []byte
  202. for {
  203. if s.IsClose {
  204. break
  205. }
  206. select {
  207. case data = <-s.pingCh:
  208. atomic.StoreUint32(&s.pingCheckTime, 0)
  209. case <-s.closeChan:
  210. return
  211. }
  212. _ = now.UnmarshalText(data)
  213. latency := time.Now().UTC().Sub(now).Seconds() / 2
  214. if latency > 0 {
  215. atomic.StoreUint64(&s.latency, math.Float64bits(s.counter.Latency(latency)))
  216. // convert float64 to bits, store it atomic
  217. }
  218. //logs.Warn("latency", math.Float64frombits(atomic.LoadUint64(&s.latency)))
  219. if cap(data) > 0 {
  220. common.WindowBuff.Put(data)
  221. }
  222. }
  223. }()
  224. }
  225. func (s *Mux) readSession() {
  226. go func() {
  227. var connection *conn
  228. for {
  229. if s.IsClose {
  230. break
  231. }
  232. connection = s.newConnQueue.Pop()
  233. if s.IsClose {
  234. break // make sure that is closed
  235. }
  236. s.connMap.Set(connection.connId, connection) //it has been set before send ok
  237. s.newConnCh <- connection
  238. s.sendInfo(common.MUX_NEW_CONN_OK, connection.connId, nil)
  239. }
  240. }()
  241. go func() {
  242. pack := common.MuxPack.Get()
  243. var l uint16
  244. var err error
  245. for {
  246. if s.IsClose {
  247. break
  248. }
  249. pack = common.MuxPack.Get()
  250. s.bw.StartRead()
  251. if l, err = pack.UnPack(s.conn); err != nil {
  252. logs.Error("mux: read session unpack from connection err", err)
  253. s.Close()
  254. break
  255. }
  256. s.bw.SetCopySize(l)
  257. atomic.StoreUint32(&s.pingOk, 0)
  258. switch pack.Flag {
  259. case common.MUX_NEW_CONN: //new connection
  260. connection := NewConn(pack.Id, s)
  261. s.newConnQueue.Push(connection)
  262. continue
  263. case common.MUX_PING_FLAG: //ping
  264. s.sendInfo(common.MUX_PING_RETURN, common.MUX_PING, pack.Content)
  265. common.WindowBuff.Put(pack.Content)
  266. continue
  267. case common.MUX_PING_RETURN:
  268. //go func(content []byte) {
  269. s.pingCh <- pack.Content
  270. //}(pack.Content)
  271. continue
  272. }
  273. if connection, ok := s.connMap.Get(pack.Id); ok && !connection.isClose {
  274. switch pack.Flag {
  275. case common.MUX_NEW_MSG, common.MUX_NEW_MSG_PART: //new msg from remote connection
  276. err = s.newMsg(connection, pack)
  277. if err != nil {
  278. logs.Error("mux: read session connection new msg err", err)
  279. connection.Close()
  280. }
  281. continue
  282. case common.MUX_NEW_CONN_OK: //connection ok
  283. connection.connStatusOkCh <- struct{}{}
  284. continue
  285. case common.MUX_NEW_CONN_Fail:
  286. connection.connStatusFailCh <- struct{}{}
  287. continue
  288. case common.MUX_MSG_SEND_OK:
  289. if connection.isClose {
  290. continue
  291. }
  292. connection.sendWindow.SetSize(pack.Window)
  293. continue
  294. case common.MUX_CONN_CLOSE: //close the connection
  295. connection.closeFlag = true
  296. //s.connMap.Delete(pack.Id)
  297. //go func(connection *conn) {
  298. connection.receiveWindow.Stop() // close signal to receive window
  299. //}(connection)
  300. continue
  301. }
  302. } else if pack.Flag == common.MUX_CONN_CLOSE {
  303. continue
  304. }
  305. common.MuxPack.Put(pack)
  306. }
  307. common.MuxPack.Put(pack)
  308. s.Close()
  309. }()
  310. }
  311. func (s *Mux) newMsg(connection *conn, pack *common.MuxPackager) (err error) {
  312. if connection.isClose {
  313. err = io.ErrClosedPipe
  314. return
  315. }
  316. //logs.Warn("read session receive new msg", pack.Length)
  317. //go func(connection *conn, pack *common.MuxPackager) { // do not block read session
  318. //insert into queue
  319. if pack.Flag == common.MUX_NEW_MSG_PART {
  320. err = connection.receiveWindow.Write(pack.Content, pack.Length, true, pack.Id)
  321. }
  322. if pack.Flag == common.MUX_NEW_MSG {
  323. err = connection.receiveWindow.Write(pack.Content, pack.Length, false, pack.Id)
  324. }
  325. //logs.Warn("read session write success", pack.Length)
  326. return
  327. }
  328. func (s *Mux) Close() (err error) {
  329. logs.Warn("close mux")
  330. if s.IsClose {
  331. return errors.New("the mux has closed")
  332. }
  333. s.IsClose = true
  334. s.connMap.Close()
  335. s.connMap = nil
  336. //s.bufQueue.Stop()
  337. s.closeChan <- struct{}{}
  338. close(s.newConnCh)
  339. err = s.conn.Close()
  340. s.release()
  341. return
  342. }
  343. func (s *Mux) release() {
  344. for {
  345. pack := s.writeQueue.TryPop()
  346. if pack == nil {
  347. break
  348. }
  349. if pack.BasePackager.Content != nil {
  350. common.WindowBuff.Put(pack.BasePackager.Content)
  351. }
  352. common.MuxPack.Put(pack)
  353. }
  354. for {
  355. connection := s.newConnQueue.TryPop()
  356. if connection == nil {
  357. break
  358. }
  359. connection = nil
  360. }
  361. s.writeQueue.Stop()
  362. s.newConnQueue.Stop()
  363. }
  364. //get new connId as unique flag
  365. func (s *Mux) getId() (id int32) {
  366. //Avoid going beyond the scope
  367. if (math.MaxInt32 - s.id) < 10000 {
  368. atomic.StoreInt32(&s.id, 0)
  369. }
  370. id = atomic.AddInt32(&s.id, 1)
  371. if _, ok := s.connMap.Get(id); ok {
  372. return s.getId()
  373. }
  374. return
  375. }
  376. type bandwidth struct {
  377. readBandwidth uint64 // store in bits, but it's float64
  378. readStart time.Time
  379. lastReadStart time.Time
  380. bufLength uint32
  381. fd *os.File
  382. calcThreshold uint32
  383. }
  384. func NewBandwidth(fd *os.File) *bandwidth {
  385. return &bandwidth{fd: fd}
  386. }
  387. func (Self *bandwidth) StartRead() {
  388. if Self.readStart.IsZero() {
  389. Self.readStart = time.Now()
  390. }
  391. if Self.bufLength >= Self.calcThreshold {
  392. Self.lastReadStart, Self.readStart = Self.readStart, time.Now()
  393. Self.calcBandWidth()
  394. }
  395. }
  396. func (Self *bandwidth) SetCopySize(n uint16) {
  397. Self.bufLength += uint32(n)
  398. }
  399. func (Self *bandwidth) calcBandWidth() {
  400. t := Self.readStart.Sub(Self.lastReadStart)
  401. bufferSize, err := sysGetSock(Self.fd)
  402. //logs.Warn(bufferSize)
  403. if err != nil {
  404. logs.Warn(err)
  405. Self.bufLength = 0
  406. return
  407. }
  408. if Self.bufLength >= uint32(bufferSize) {
  409. atomic.StoreUint64(&Self.readBandwidth, math.Float64bits(float64(Self.bufLength)/t.Seconds()))
  410. // calculate the whole socket buffer, the time meaning to fill the buffer
  411. //logs.Warn(Self.Get())
  412. } else {
  413. Self.calcThreshold = uint32(bufferSize)
  414. }
  415. // socket buffer size is bigger than bufLength, so we don't calculate it
  416. Self.bufLength = 0
  417. }
  418. func (Self *bandwidth) Get() (bw float64) {
  419. // The zero value, 0 for numeric types
  420. bw = math.Float64frombits(atomic.LoadUint64(&Self.readBandwidth))
  421. if bw <= 0 {
  422. bw = 0
  423. }
  424. //logs.Warn(bw)
  425. return
  426. }
  427. const counterBits = 4
  428. const counterMask = 1<<counterBits - 1
  429. func newLatencyCounter() *latencyCounter {
  430. return &latencyCounter{
  431. buf: make([]float64, 1<<counterBits, 1<<counterBits),
  432. headMin: 0,
  433. }
  434. }
  435. type latencyCounter struct {
  436. buf []float64 //buf is a fixed length ring buffer,
  437. // if buffer is full, new value will replace the oldest one.
  438. headMin uint8 //head indicate the head in ring buffer,
  439. // in meaning, slot in list will be replaced;
  440. // min indicate this slot value is minimal in list.
  441. }
  442. func (Self *latencyCounter) unpack(idxs uint8) (head, min uint8) {
  443. head = uint8((idxs >> counterBits) & counterMask)
  444. // we set head is 4 bits
  445. min = uint8(idxs & counterMask)
  446. return
  447. }
  448. func (Self *latencyCounter) pack(head, min uint8) uint8 {
  449. return uint8(head<<counterBits) |
  450. uint8(min&counterMask)
  451. }
  452. func (Self *latencyCounter) add(value float64) {
  453. head, min := Self.unpack(Self.headMin)
  454. Self.buf[head] = value
  455. if head == min {
  456. min = Self.minimal()
  457. //if head equals min, means the min slot already be replaced,
  458. // so we need to find another minimal value in the list,
  459. // and change the min indicator
  460. }
  461. if Self.buf[min] > value {
  462. min = head
  463. }
  464. head++
  465. Self.headMin = Self.pack(head, min)
  466. }
  467. func (Self *latencyCounter) minimal() (min uint8) {
  468. var val float64
  469. var i uint8
  470. for i = 0; i < counterMask; i++ {
  471. if Self.buf[i] > 0 {
  472. if val > Self.buf[i] {
  473. val = Self.buf[i]
  474. min = i
  475. }
  476. }
  477. }
  478. return
  479. }
  480. func (Self *latencyCounter) Latency(value float64) (latency float64) {
  481. Self.add(value)
  482. _, min := Self.unpack(Self.headMin)
  483. latency = Self.buf[min] * Self.countSuccess()
  484. return
  485. }
  486. const lossRatio = 1.6
  487. func (Self *latencyCounter) countSuccess() (successRate float64) {
  488. var success, loss, i uint8
  489. _, min := Self.unpack(Self.headMin)
  490. for i = 0; i < counterMask; i++ {
  491. if Self.buf[i] > lossRatio*Self.buf[min] && Self.buf[i] > 0 {
  492. loss++
  493. }
  494. if Self.buf[i] <= lossRatio*Self.buf[min] && Self.buf[i] > 0 {
  495. success++
  496. }
  497. }
  498. // counting all the data in the ring buf, except zero
  499. successRate = float64(success) / float64(loss+success)
  500. return
  501. }