mux.go 12 KB

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