123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722 |
- package mux
- import (
- "ehang.io/nps/lib/common"
- "errors"
- "github.com/astaxie/beego/logs"
- "io"
- "math"
- "net"
- "runtime"
- "sync"
- "sync/atomic"
- "time"
- )
- type conn struct {
- net.Conn
- getStatusCh chan struct{}
- connStatusOkCh chan struct{}
- connStatusFailCh chan struct{}
- connId int32
- isClose bool
- closeFlag bool
- receiveWindow *ReceiveWindow
- sendWindow *SendWindow
- once sync.Once
-
- }
- func NewConn(connId int32, mux *Mux, label ...string) *conn {
- c := &conn{
- getStatusCh: make(chan struct{}),
- connStatusOkCh: make(chan struct{}),
- connStatusFailCh: make(chan struct{}),
- connId: connId,
- receiveWindow: new(ReceiveWindow),
- sendWindow: new(SendWindow),
- once: sync.Once{},
- }
-
-
-
- c.receiveWindow.New(mux)
- c.sendWindow.New(mux)
-
-
-
-
-
-
- return c
- }
- func (s *conn) Read(buf []byte) (n int, err error) {
- if s.isClose || buf == nil {
- return 0, errors.New("the conn has closed")
- }
- if len(buf) == 0 {
- return 0, nil
- }
-
-
- n, err = s.receiveWindow.Read(buf, s.connId)
-
-
-
-
-
-
-
-
-
-
-
-
-
- return
- }
- func (s *conn) Write(buf []byte) (n int, err error) {
- if s.isClose {
- return 0, errors.New("the conn has closed")
- }
- if s.closeFlag {
-
- return 0, errors.New("io: write on closed conn")
- }
- if len(buf) == 0 {
- return 0, nil
- }
-
-
- n, err = s.sendWindow.WriteFull(buf, s.connId)
-
-
-
-
- return
- }
- func (s *conn) Close() (err error) {
- s.once.Do(s.closeProcess)
- return
- }
- func (s *conn) closeProcess() {
- s.isClose = true
- s.receiveWindow.mux.connMap.Delete(s.connId)
- if !s.receiveWindow.mux.IsClose {
-
-
- s.receiveWindow.mux.sendInfo(common.MUX_CONN_CLOSE, s.connId, nil)
- }
- s.sendWindow.CloseWindow()
- s.receiveWindow.CloseWindow()
-
-
-
-
- return
- }
- func (s *conn) LocalAddr() net.Addr {
- return s.receiveWindow.mux.conn.LocalAddr()
- }
- func (s *conn) RemoteAddr() net.Addr {
- return s.receiveWindow.mux.conn.RemoteAddr()
- }
- func (s *conn) SetDeadline(t time.Time) error {
- _ = s.SetReadDeadline(t)
- _ = s.SetWriteDeadline(t)
- return nil
- }
- func (s *conn) SetReadDeadline(t time.Time) error {
- s.receiveWindow.SetTimeOut(t)
- return nil
- }
- func (s *conn) SetWriteDeadline(t time.Time) error {
- s.sendWindow.SetTimeOut(t)
- return nil
- }
- type window struct {
- maxSizeDone uint64
-
-
-
-
-
- off uint32
- closeOp bool
- closeOpCh chan struct{}
- mux *Mux
- }
- const windowBits = 31
- const waitBits = dequeueBits + windowBits
- const mask1 = 1
- const mask31 = 1<<windowBits - 1
- func (Self *window) unpack(ptrs uint64) (maxSize, done uint32, wait bool) {
- maxSize = uint32((ptrs >> dequeueBits) & mask31)
- done = uint32(ptrs & mask31)
-
- if ((ptrs >> waitBits) & mask1) == 1 {
- wait = true
- return
- }
- return
- }
- func (Self *window) pack(maxSize, done uint32, wait bool) uint64 {
-
- if wait {
- return (uint64(1)<<waitBits |
- uint64(maxSize&mask31)<<dequeueBits) |
- uint64(done&mask31)
- }
- return (uint64(0)<<waitBits |
- uint64(maxSize&mask31)<<dequeueBits) |
- uint64(done&mask31)
- }
- func (Self *window) New() {
- Self.closeOpCh = make(chan struct{}, 2)
- }
- func (Self *window) CloseWindow() {
- if !Self.closeOp {
- Self.closeOp = true
- Self.closeOpCh <- struct{}{}
- Self.closeOpCh <- struct{}{}
- }
- }
- type ReceiveWindow struct {
- window
- bufQueue *ReceiveWindowQueue
- element *common.ListElement
- count int8
- bw *writeBandwidth
- once sync.Once
-
-
- }
- func (Self *ReceiveWindow) New(mux *Mux) {
-
- Self.bufQueue = NewReceiveWindowQueue()
- Self.element = common.ListElementPool.Get()
- Self.maxSizeDone = Self.pack(common.MAXIMUM_SEGMENT_SIZE*30, 0, false)
- Self.mux = mux
- Self.window.New()
- Self.bw = NewWriteBandwidth()
- }
- func (Self *ReceiveWindow) remainingSize(maxSize uint32, delta uint16) (n uint32) {
-
- l := int64(maxSize) - int64(Self.bufQueue.Len())
- l -= int64(delta)
- if l > 0 {
- n = uint32(l)
- }
- return
- }
- func (Self *ReceiveWindow) calcSize() {
-
- if Self.count == 0 {
-
-
- muxBw := Self.mux.bw.Get()
- connBw := Self.bw.Get()
-
- var n uint32
- if connBw > 0 && muxBw > 0 {
- n = uint32(math.Float64frombits(atomic.LoadUint64(&Self.mux.latency)) *
- (muxBw + connBw))
- }
-
- if n < common.MAXIMUM_SEGMENT_SIZE*30 {
-
- n = common.MAXIMUM_SEGMENT_SIZE * 30
- }
- for {
- ptrs := atomic.LoadUint64(&Self.maxSizeDone)
- size, read, wait := Self.unpack(ptrs)
- if n < size/2 {
- n = size / 2
-
- }
-
- if n > 2*size {
- n = 2 * size
-
- }
- if connBw > 0 && muxBw > 0 {
- limit := uint32(common.MAXIMUM_WINDOW_SIZE * (connBw / (muxBw + connBw)))
- if n > limit {
- logs.Warn("window too large, calculated:", n, "limit:", limit, connBw, muxBw)
- n = limit
- }
- }
-
-
- if atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(n, read, wait)) {
-
- break
- }
- }
- Self.count = -10
- }
- Self.count += 1
- return
- }
- func (Self *ReceiveWindow) Write(buf []byte, l uint16, part bool, id int32) (err error) {
- if Self.closeOp {
- return errors.New("conn.receiveWindow: write on closed window")
- }
- element, err := NewListElement(buf, l, part)
-
- if err != nil {
- return
- }
- Self.calcSize()
- var wait bool
- var maxSize, read uint32
- start:
- ptrs := atomic.LoadUint64(&Self.maxSizeDone)
- maxSize, read, wait = Self.unpack(ptrs)
- remain := Self.remainingSize(maxSize, l)
-
- if remain == 0 && !wait {
-
- wait = true
- if !atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSize, read, wait)) {
-
- goto start
-
- }
-
- } else if !wait {
- if !atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSize, 0, wait)) {
-
- goto start
-
- }
- }
-
- Self.bufQueue.Push(element)
-
- if !wait {
- Self.mux.sendInfo(common.MUX_MSG_SEND_OK, id, Self.pack(maxSize, read, false))
-
- }
- return nil
- }
- func (Self *ReceiveWindow) Read(p []byte, id int32) (n int, err error) {
- if Self.closeOp {
- return 0, io.EOF
- }
- Self.bw.StartRead()
- n, err = Self.readFromQueue(p, id)
- Self.bw.SetCopySize(uint16(n))
- return
- }
- func (Self *ReceiveWindow) readFromQueue(p []byte, id int32) (n int, err error) {
- pOff := 0
- l := 0
-
- copyData:
- if Self.off == uint32(Self.element.L) {
-
-
- common.ListElementPool.Put(Self.element)
- if Self.closeOp {
- return 0, io.EOF
- }
- Self.element, err = Self.bufQueue.Pop()
-
-
-
- Self.off = 0
- if err != nil {
- Self.CloseWindow()
- return
- }
-
- }
- l = copy(p[pOff:], Self.element.Buf[Self.off:Self.element.L])
- pOff += l
- Self.off += uint32(l)
-
- n += l
- l = 0
- if Self.off == uint32(Self.element.L) {
-
- common.WindowBuff.Put(Self.element.Buf)
- Self.sendStatus(id, Self.element.L)
-
- }
- if pOff < len(p) && Self.element.Part {
-
- goto copyData
- }
- return
- }
- func (Self *ReceiveWindow) sendStatus(id int32, l uint16) {
- var maxSize, read uint32
- var wait bool
- for {
- ptrs := atomic.LoadUint64(&Self.maxSizeDone)
- maxSize, read, wait = Self.unpack(ptrs)
- if read <= (read+uint32(l))&mask31 {
- read += uint32(l)
- remain := Self.remainingSize(maxSize, 0)
- if wait && remain > 0 || read >= maxSize/2 || remain == maxSize {
- if atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSize, 0, false)) {
-
-
-
-
-
- Self.mux.sendInfo(common.MUX_MSG_SEND_OK, id, Self.pack(maxSize, read, false))
- break
- }
- } else {
- if atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSize, read, wait)) {
-
-
- break
- }
- }
- } else {
-
- if atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSize, uint32(l), wait)) {
-
- Self.mux.sendInfo(common.MUX_MSG_SEND_OK, id, Self.pack(maxSize, read, false))
- break
- }
- }
- runtime.Gosched()
-
- }
- return
- }
- func (Self *ReceiveWindow) SetTimeOut(t time.Time) {
-
- Self.bufQueue.SetTimeOut(t)
- }
- func (Self *ReceiveWindow) Stop() {
-
- Self.once.Do(Self.bufQueue.Stop)
- }
- func (Self *ReceiveWindow) CloseWindow() {
- Self.window.CloseWindow()
- Self.Stop()
- Self.release()
- }
- func (Self *ReceiveWindow) release() {
-
-
-
-
-
-
- for {
- ele := Self.bufQueue.TryPop()
- if ele == nil {
- return
- }
- if ele.Buf != nil {
- common.WindowBuff.Put(ele.Buf)
- }
- common.ListElementPool.Put(ele)
- }
- }
- type SendWindow struct {
- window
- buf []byte
- setSizeCh chan struct{}
- timeout time.Time
-
-
-
- }
- func (Self *SendWindow) New(mux *Mux) {
- Self.setSizeCh = make(chan struct{})
- Self.maxSizeDone = Self.pack(common.MAXIMUM_SEGMENT_SIZE*30, 0, false)
- Self.mux = mux
- Self.window.New()
- }
- func (Self *SendWindow) SetSendBuf(buf []byte) {
-
- Self.buf = buf
- Self.off = 0
- }
- func (Self *SendWindow) remainingSize(maxSize, send uint32) uint32 {
- l := int64(maxSize&mask31) - int64(send&mask31)
- if l > 0 {
- return uint32(l)
- }
- return 0
- }
- func (Self *SendWindow) SetSize(currentMaxSizeDone uint64) (closed bool) {
-
- defer func() {
- if recover() != nil {
- closed = true
- }
- }()
- if Self.closeOp {
- close(Self.setSizeCh)
- return true
- }
-
- var maxsize, send uint32
- var wait, newWait bool
- currentMaxSize, read, _ := Self.unpack(currentMaxSizeDone)
- for {
- ptrs := atomic.LoadUint64(&Self.maxSizeDone)
- maxsize, send, wait = Self.unpack(ptrs)
- if read > send {
- logs.Error("window read > send: max size:", currentMaxSize, "read:", read, "send", send)
- return
- }
- if read == 0 && currentMaxSize == maxsize {
- return
- }
- send -= read
- remain := Self.remainingSize(currentMaxSize, send)
- if remain == 0 && wait {
-
- newWait = true
- }
-
- if atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(currentMaxSize, send, newWait)) {
- break
- }
-
- }
- if wait && !newWait {
-
-
- Self.allow()
- }
-
- return false
- }
- func (Self *SendWindow) allow() {
- select {
- case Self.setSizeCh <- struct{}{}:
-
- return
- case <-Self.closeOpCh:
- close(Self.setSizeCh)
- return
- }
- }
- func (Self *SendWindow) sent(sentSize uint32) {
- var maxSie, send uint32
- var wait bool
- for {
- ptrs := atomic.LoadUint64(&Self.maxSizeDone)
- maxSie, send, wait = Self.unpack(ptrs)
- if (send+sentSize)&mask31 < send {
-
- runtime.Gosched()
- continue
- }
- if atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSie, send+sentSize, wait)) {
-
-
- break
- }
- }
- }
- func (Self *SendWindow) WriteTo() (p []byte, sendSize uint32, part bool, err error) {
-
-
- if Self.closeOp {
- return nil, 0, false, errors.New("conn.writeWindow: window closed")
- }
- if Self.off == uint32(len(Self.buf)) {
- return nil, 0, false, io.EOF
-
- }
- var maxSize, send uint32
- start:
- ptrs := atomic.LoadUint64(&Self.maxSizeDone)
- maxSize, send, _ = Self.unpack(ptrs)
- remain := Self.remainingSize(maxSize, send)
- if remain == 0 {
- if !atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSize, send, true)) {
-
- goto start
- }
-
-
- err = Self.waitReceiveWindow()
- if err != nil {
- return nil, 0, false, err
- }
-
- goto start
- }
-
-
- if len(Self.buf[Self.off:]) > common.MAXIMUM_SEGMENT_SIZE {
- sendSize = common.MAXIMUM_SEGMENT_SIZE
-
- } else {
- sendSize = uint32(len(Self.buf[Self.off:]))
- }
- if remain < sendSize {
-
-
- sendSize = remain
-
- }
-
- if sendSize < uint32(len(Self.buf[Self.off:])) {
- part = true
- }
- p = Self.buf[Self.off : sendSize+Self.off]
- Self.off += sendSize
- Self.sent(sendSize)
- return
- }
- func (Self *SendWindow) waitReceiveWindow() (err error) {
- t := Self.timeout.Sub(time.Now())
- if t < 0 {
- select {
- case _, ok := <-Self.setSizeCh:
- if !ok {
- return errors.New("conn.writeWindow: window closed")
- }
- return nil
- case <-Self.closeOpCh:
- return errors.New("conn.writeWindow: window closed")
- }
- }
- timer := time.NewTimer(t)
- defer timer.Stop()
-
- select {
- case _, ok := <-Self.setSizeCh:
- if !ok {
- return errors.New("conn.writeWindow: window closed")
- }
- return nil
- case <-timer.C:
- return errors.New("conn.writeWindow: write to time out")
- case <-Self.closeOpCh:
- return errors.New("conn.writeWindow: window closed")
- }
- }
- func (Self *SendWindow) WriteFull(buf []byte, id int32) (n int, err error) {
- Self.SetSendBuf(buf)
-
- var bufSeg []byte
- var part bool
- var l uint32
- for {
- bufSeg, l, part, err = Self.WriteTo()
-
-
- if bufSeg == nil && part == false && err == io.EOF {
-
- err = nil
- break
- }
- if err != nil {
- break
- }
- n += int(l)
- l = 0
- if part {
- Self.mux.sendInfo(common.MUX_NEW_MSG_PART, id, bufSeg)
- } else {
- Self.mux.sendInfo(common.MUX_NEW_MSG, id, bufSeg)
-
- }
-
- }
-
- return
- }
- func (Self *SendWindow) SetTimeOut(t time.Time) {
-
- Self.timeout = t
- }
- type writeBandwidth struct {
- writeBW uint64
- readEnd time.Time
- duration float64
- bufLength uint32
- }
- const writeCalcThreshold uint32 = 5 * 1024 * 1024
- func NewWriteBandwidth() *writeBandwidth {
- return &writeBandwidth{}
- }
- func (Self *writeBandwidth) StartRead() {
- if Self.readEnd.IsZero() {
- Self.readEnd = time.Now()
- }
- Self.duration += time.Now().Sub(Self.readEnd).Seconds()
- if Self.bufLength >= writeCalcThreshold {
- Self.calcBandWidth()
- }
- }
- func (Self *writeBandwidth) SetCopySize(n uint16) {
- Self.bufLength += uint32(n)
- Self.endRead()
- }
- func (Self *writeBandwidth) endRead() {
- Self.readEnd = time.Now()
- }
- func (Self *writeBandwidth) calcBandWidth() {
- atomic.StoreUint64(&Self.writeBW, math.Float64bits(float64(Self.bufLength)/Self.duration))
- Self.bufLength = 0
- Self.duration = 0
- }
- func (Self *writeBandwidth) Get() (bw float64) {
-
- bw = math.Float64frombits(atomic.LoadUint64(&Self.writeBW))
- if bw <= 0 {
- bw = 0
- }
- return
- }
|