mux.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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. defer ticker.Stop()
  165. for {
  166. if s.IsClose {
  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. return
  190. }()
  191. }
  192. func (s *Mux) pingReturn() {
  193. go func() {
  194. var now time.Time
  195. var data []byte
  196. for {
  197. if s.IsClose {
  198. break
  199. }
  200. select {
  201. case data = <-s.pingCh:
  202. atomic.StoreUint32(&s.pingCheckTime, 0)
  203. case <-s.closeChan:
  204. break
  205. }
  206. _ = now.UnmarshalText(data)
  207. latency := time.Now().UTC().Sub(now).Seconds() / 2
  208. if latency > 0 {
  209. atomic.StoreUint64(&s.latency, math.Float64bits(s.counter.Latency(latency)))
  210. // convert float64 to bits, store it atomic
  211. }
  212. //logs.Warn("latency", math.Float64frombits(atomic.LoadUint64(&s.latency)))
  213. if cap(data) > 0 {
  214. common.WindowBuff.Put(data)
  215. }
  216. }
  217. }()
  218. }
  219. func (s *Mux) readSession() {
  220. go func() {
  221. var connection *conn
  222. for {
  223. if s.IsClose {
  224. break
  225. }
  226. connection = s.newConnQueue.Pop()
  227. if s.IsClose {
  228. break // make sure that is closed
  229. }
  230. s.connMap.Set(connection.connId, connection) //it has been set before send ok
  231. s.newConnCh <- connection
  232. s.sendInfo(common.MUX_NEW_CONN_OK, connection.connId, nil)
  233. }
  234. }()
  235. go func() {
  236. pack := common.MuxPack.Get()
  237. var l uint16
  238. var err error
  239. for {
  240. if s.IsClose {
  241. break
  242. }
  243. pack = common.MuxPack.Get()
  244. s.bw.StartRead()
  245. if l, err = pack.UnPack(s.conn); err != nil {
  246. logs.Error("mux: read session unpack from connection err", err)
  247. s.Close()
  248. break
  249. }
  250. s.bw.SetCopySize(l)
  251. atomic.StoreUint32(&s.pingOk, 0)
  252. switch pack.Flag {
  253. case common.MUX_NEW_CONN: //new connection
  254. connection := NewConn(pack.Id, s)
  255. s.newConnQueue.Push(connection)
  256. continue
  257. case common.MUX_PING_FLAG: //ping
  258. s.sendInfo(common.MUX_PING_RETURN, common.MUX_PING, pack.Content)
  259. common.WindowBuff.Put(pack.Content)
  260. continue
  261. case common.MUX_PING_RETURN:
  262. //go func(content []byte) {
  263. s.pingCh <- pack.Content
  264. //}(pack.Content)
  265. continue
  266. }
  267. if connection, ok := s.connMap.Get(pack.Id); ok && !connection.isClose {
  268. switch pack.Flag {
  269. case common.MUX_NEW_MSG, common.MUX_NEW_MSG_PART: //new msg from remote connection
  270. err = s.newMsg(connection, pack)
  271. if err != nil {
  272. logs.Error("mux: read session connection new msg err", err)
  273. connection.Close()
  274. }
  275. continue
  276. case common.MUX_NEW_CONN_OK: //connection ok
  277. connection.connStatusOkCh <- struct{}{}
  278. continue
  279. case common.MUX_NEW_CONN_Fail:
  280. connection.connStatusFailCh <- struct{}{}
  281. continue
  282. case common.MUX_MSG_SEND_OK:
  283. if connection.isClose {
  284. continue
  285. }
  286. connection.sendWindow.SetSize(pack.RemainLength)
  287. continue
  288. case common.MUX_CONN_CLOSE: //close the connection
  289. connection.closeFlag = true
  290. //s.connMap.Delete(pack.Id)
  291. //go func(connection *conn) {
  292. connection.receiveWindow.Stop() // close signal to receive window
  293. //}(connection)
  294. continue
  295. }
  296. } else if pack.Flag == common.MUX_CONN_CLOSE {
  297. continue
  298. }
  299. common.MuxPack.Put(pack)
  300. }
  301. common.MuxPack.Put(pack)
  302. s.Close()
  303. }()
  304. }
  305. func (s *Mux) newMsg(connection *conn, pack *common.MuxPackager) (err error) {
  306. if connection.isClose {
  307. err = io.ErrClosedPipe
  308. return
  309. }
  310. //logs.Warn("read session receive new msg", pack.Length)
  311. //go func(connection *conn, pack *common.MuxPackager) { // do not block read session
  312. //insert into queue
  313. if pack.Flag == common.MUX_NEW_MSG_PART {
  314. err = connection.receiveWindow.Write(pack.Content, pack.Length, true, pack.Id)
  315. }
  316. if pack.Flag == common.MUX_NEW_MSG {
  317. err = connection.receiveWindow.Write(pack.Content, pack.Length, false, pack.Id)
  318. }
  319. //logs.Warn("read session write success", pack.Length)
  320. return
  321. }
  322. func (s *Mux) Close() (err error) {
  323. logs.Warn("close mux")
  324. if s.IsClose {
  325. return errors.New("the mux has closed")
  326. }
  327. s.IsClose = true
  328. s.connMap.Close()
  329. s.connMap = nil
  330. //s.bufQueue.Stop()
  331. s.closeChan <- struct{}{}
  332. close(s.newConnCh)
  333. err = s.conn.Close()
  334. s.release()
  335. return
  336. }
  337. func (s *Mux) release() {
  338. for {
  339. pack := s.writeQueue.TryPop()
  340. if pack == nil {
  341. break
  342. }
  343. if pack.BasePackager.Content != nil {
  344. common.WindowBuff.Put(pack.BasePackager.Content)
  345. }
  346. common.MuxPack.Put(pack)
  347. }
  348. for {
  349. connection := s.newConnQueue.TryPop()
  350. if connection == nil {
  351. break
  352. }
  353. connection = nil
  354. }
  355. s.writeQueue.Stop()
  356. s.newConnQueue.Stop()
  357. }
  358. //get new connId as unique flag
  359. func (s *Mux) getId() (id int32) {
  360. //Avoid going beyond the scope
  361. if (math.MaxInt32 - s.id) < 10000 {
  362. atomic.StoreInt32(&s.id, 0)
  363. }
  364. id = atomic.AddInt32(&s.id, 1)
  365. if _, ok := s.connMap.Get(id); ok {
  366. return s.getId()
  367. }
  368. return
  369. }
  370. type bandwidth struct {
  371. readBandwidth uint64 // store in bits, but it's float64
  372. readStart time.Time
  373. lastReadStart time.Time
  374. bufLength uint32
  375. }
  376. func (Self *bandwidth) StartRead() {
  377. if Self.readStart.IsZero() {
  378. Self.readStart = time.Now()
  379. }
  380. if Self.bufLength >= common.MAXIMUM_SEGMENT_SIZE*300 {
  381. Self.lastReadStart, Self.readStart = Self.readStart, time.Now()
  382. Self.calcBandWidth()
  383. }
  384. }
  385. func (Self *bandwidth) SetCopySize(n uint16) {
  386. Self.bufLength += uint32(n)
  387. }
  388. func (Self *bandwidth) calcBandWidth() {
  389. t := Self.readStart.Sub(Self.lastReadStart)
  390. atomic.StoreUint64(&Self.readBandwidth, math.Float64bits(float64(Self.bufLength)/t.Seconds()))
  391. Self.bufLength = 0
  392. }
  393. func (Self *bandwidth) Get() (bw float64) {
  394. // The zero value, 0 for numeric types
  395. bw = math.Float64frombits(atomic.LoadUint64(&Self.readBandwidth))
  396. if bw <= 0 {
  397. bw = 100
  398. }
  399. //logs.Warn(bw)
  400. return
  401. }
  402. const counterBits = 4
  403. const counterMask = 1<<counterBits - 1
  404. func newLatencyCounter() *latencyCounter {
  405. return &latencyCounter{
  406. buf: make([]float64, 1<<counterBits, 1<<counterBits),
  407. headMin: 0,
  408. }
  409. }
  410. type latencyCounter struct {
  411. buf []float64 //buf is a fixed length ring buffer,
  412. // if buffer is full, new value will replace the oldest one.
  413. headMin uint8 //head indicate the head in ring buffer,
  414. // in meaning, slot in list will be replaced;
  415. // min indicate this slot value is minimal in list.
  416. }
  417. func (Self *latencyCounter) unpack(idxs uint8) (head, min uint8) {
  418. head = uint8((idxs >> counterBits) & counterMask)
  419. // we set head is 4 bits
  420. min = uint8(idxs & counterMask)
  421. return
  422. }
  423. func (Self *latencyCounter) pack(head, min uint8) uint8 {
  424. return uint8(head<<counterBits) |
  425. uint8(min&counterMask)
  426. }
  427. func (Self *latencyCounter) add(value float64) {
  428. head, min := Self.unpack(Self.headMin)
  429. Self.buf[head] = value
  430. if head == min {
  431. min = Self.minimal()
  432. //if head equals min, means the min slot already be replaced,
  433. // so we need to find another minimal value in the list,
  434. // and change the min indicator
  435. }
  436. if Self.buf[min] > value {
  437. min = head
  438. }
  439. head++
  440. Self.headMin = Self.pack(head, min)
  441. }
  442. func (Self *latencyCounter) minimal() (min uint8) {
  443. var val float64
  444. var i uint8
  445. for i = 0; i < counterMask; i++ {
  446. if Self.buf[i] > 0 {
  447. if val > Self.buf[i] {
  448. val = Self.buf[i]
  449. min = i
  450. }
  451. }
  452. }
  453. return
  454. }
  455. func (Self *latencyCounter) Latency(value float64) (latency float64) {
  456. Self.add(value)
  457. _, min := Self.unpack(Self.headMin)
  458. latency = Self.buf[min] * Self.countSuccess()
  459. return
  460. }
  461. const lossRatio = 1.6
  462. func (Self *latencyCounter) countSuccess() (successRate float64) {
  463. var success, loss, i uint8
  464. _, min := Self.unpack(Self.headMin)
  465. for i = 0; i < counterMask; i++ {
  466. if Self.buf[i] > lossRatio*Self.buf[min] && Self.buf[i] > 0 {
  467. loss++
  468. }
  469. if Self.buf[i] <= lossRatio*Self.buf[min] && Self.buf[i] > 0 {
  470. success++
  471. }
  472. }
  473. // counting all the data in the ring buf, except zero
  474. successRate = float64(success) / float64(loss+success)
  475. return
  476. }