repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
xtaci/kcp-go
sess.go
newUDPSession
func newUDPSession(conv uint32, dataShards, parityShards int, l *Listener, conn net.PacketConn, remote net.Addr, block BlockCrypt) *UDPSession { sess := new(UDPSession) sess.die = make(chan struct{}) sess.nonce = new(nonceAES128) sess.nonce.Init() sess.chReadEvent = make(chan struct{}, 1) sess.chWriteEvent = make(chan struct{}, 1) sess.chReadError = make(chan error, 1) sess.chWriteError = make(chan error, 1) sess.remote = remote sess.conn = conn sess.l = l sess.block = block sess.recvbuf = make([]byte, mtuLimit) // FEC codec initialization sess.fecDecoder = newFECDecoder(rxFECMulti*(dataShards+parityShards), dataShards, parityShards) if sess.block != nil { sess.fecEncoder = newFECEncoder(dataShards, parityShards, cryptHeaderSize) } else { sess.fecEncoder = newFECEncoder(dataShards, parityShards, 0) } // calculate additional header size introduced by FEC and encryption if sess.block != nil { sess.headerSize += cryptHeaderSize } if sess.fecEncoder != nil { sess.headerSize += fecHeaderSizePlus2 } sess.kcp = NewKCP(conv, func(buf []byte, size int) { if size >= IKCP_OVERHEAD+sess.headerSize { sess.output(buf[:size]) } }) sess.kcp.ReserveBytes(sess.headerSize) // register current session to the global updater, // which call sess.update() periodically. updater.addSession(sess) if sess.l == nil { // it's a client connection go sess.readLoop() atomic.AddUint64(&DefaultSnmp.ActiveOpens, 1) } else { atomic.AddUint64(&DefaultSnmp.PassiveOpens, 1) } currestab := atomic.AddUint64(&DefaultSnmp.CurrEstab, 1) maxconn := atomic.LoadUint64(&DefaultSnmp.MaxConn) if currestab > maxconn { atomic.CompareAndSwapUint64(&DefaultSnmp.MaxConn, maxconn, currestab) } return sess }
go
func newUDPSession(conv uint32, dataShards, parityShards int, l *Listener, conn net.PacketConn, remote net.Addr, block BlockCrypt) *UDPSession { sess := new(UDPSession) sess.die = make(chan struct{}) sess.nonce = new(nonceAES128) sess.nonce.Init() sess.chReadEvent = make(chan struct{}, 1) sess.chWriteEvent = make(chan struct{}, 1) sess.chReadError = make(chan error, 1) sess.chWriteError = make(chan error, 1) sess.remote = remote sess.conn = conn sess.l = l sess.block = block sess.recvbuf = make([]byte, mtuLimit) // FEC codec initialization sess.fecDecoder = newFECDecoder(rxFECMulti*(dataShards+parityShards), dataShards, parityShards) if sess.block != nil { sess.fecEncoder = newFECEncoder(dataShards, parityShards, cryptHeaderSize) } else { sess.fecEncoder = newFECEncoder(dataShards, parityShards, 0) } // calculate additional header size introduced by FEC and encryption if sess.block != nil { sess.headerSize += cryptHeaderSize } if sess.fecEncoder != nil { sess.headerSize += fecHeaderSizePlus2 } sess.kcp = NewKCP(conv, func(buf []byte, size int) { if size >= IKCP_OVERHEAD+sess.headerSize { sess.output(buf[:size]) } }) sess.kcp.ReserveBytes(sess.headerSize) // register current session to the global updater, // which call sess.update() periodically. updater.addSession(sess) if sess.l == nil { // it's a client connection go sess.readLoop() atomic.AddUint64(&DefaultSnmp.ActiveOpens, 1) } else { atomic.AddUint64(&DefaultSnmp.PassiveOpens, 1) } currestab := atomic.AddUint64(&DefaultSnmp.CurrEstab, 1) maxconn := atomic.LoadUint64(&DefaultSnmp.MaxConn) if currestab > maxconn { atomic.CompareAndSwapUint64(&DefaultSnmp.MaxConn, maxconn, currestab) } return sess }
[ "func", "newUDPSession", "(", "conv", "uint32", ",", "dataShards", ",", "parityShards", "int", ",", "l", "*", "Listener", ",", "conn", "net", ".", "PacketConn", ",", "remote", "net", ".", "Addr", ",", "block", "BlockCrypt", ")", "*", "UDPSession", "{", "sess", ":=", "new", "(", "UDPSession", ")", "\n", "sess", ".", "die", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "sess", ".", "nonce", "=", "new", "(", "nonceAES128", ")", "\n", "sess", ".", "nonce", ".", "Init", "(", ")", "\n", "sess", ".", "chReadEvent", "=", "make", "(", "chan", "struct", "{", "}", ",", "1", ")", "\n", "sess", ".", "chWriteEvent", "=", "make", "(", "chan", "struct", "{", "}", ",", "1", ")", "\n", "sess", ".", "chReadError", "=", "make", "(", "chan", "error", ",", "1", ")", "\n", "sess", ".", "chWriteError", "=", "make", "(", "chan", "error", ",", "1", ")", "\n", "sess", ".", "remote", "=", "remote", "\n", "sess", ".", "conn", "=", "conn", "\n", "sess", ".", "l", "=", "l", "\n", "sess", ".", "block", "=", "block", "\n", "sess", ".", "recvbuf", "=", "make", "(", "[", "]", "byte", ",", "mtuLimit", ")", "\n", "sess", ".", "fecDecoder", "=", "newFECDecoder", "(", "rxFECMulti", "*", "(", "dataShards", "+", "parityShards", ")", ",", "dataShards", ",", "parityShards", ")", "\n", "if", "sess", ".", "block", "!=", "nil", "{", "sess", ".", "fecEncoder", "=", "newFECEncoder", "(", "dataShards", ",", "parityShards", ",", "cryptHeaderSize", ")", "\n", "}", "else", "{", "sess", ".", "fecEncoder", "=", "newFECEncoder", "(", "dataShards", ",", "parityShards", ",", "0", ")", "\n", "}", "\n", "if", "sess", ".", "block", "!=", "nil", "{", "sess", ".", "headerSize", "+=", "cryptHeaderSize", "\n", "}", "\n", "if", "sess", ".", "fecEncoder", "!=", "nil", "{", "sess", ".", "headerSize", "+=", "fecHeaderSizePlus2", "\n", "}", "\n", "sess", ".", "kcp", "=", "NewKCP", "(", "conv", ",", "func", "(", "buf", "[", "]", "byte", ",", "size", "int", ")", "{", "if", "size", ">=", "IKCP_OVERHEAD", "+", "sess", ".", "headerSize", "{", "sess", ".", "output", "(", "buf", "[", ":", "size", "]", ")", "\n", "}", "\n", "}", ")", "\n", "sess", ".", "kcp", ".", "ReserveBytes", "(", "sess", ".", "headerSize", ")", "\n", "updater", ".", "addSession", "(", "sess", ")", "\n", "if", "sess", ".", "l", "==", "nil", "{", "go", "sess", ".", "readLoop", "(", ")", "\n", "atomic", ".", "AddUint64", "(", "&", "DefaultSnmp", ".", "ActiveOpens", ",", "1", ")", "\n", "}", "else", "{", "atomic", ".", "AddUint64", "(", "&", "DefaultSnmp", ".", "PassiveOpens", ",", "1", ")", "\n", "}", "\n", "currestab", ":=", "atomic", ".", "AddUint64", "(", "&", "DefaultSnmp", ".", "CurrEstab", ",", "1", ")", "\n", "maxconn", ":=", "atomic", ".", "LoadUint64", "(", "&", "DefaultSnmp", ".", "MaxConn", ")", "\n", "if", "currestab", ">", "maxconn", "{", "atomic", ".", "CompareAndSwapUint64", "(", "&", "DefaultSnmp", ".", "MaxConn", ",", "maxconn", ",", "currestab", ")", "\n", "}", "\n", "return", "sess", "\n", "}" ]
// newUDPSession create a new udp session for client or server
[ "newUDPSession", "create", "a", "new", "udp", "session", "for", "client", "or", "server" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L113-L168
train
xtaci/kcp-go
sess.go
WriteBuffers
func (s *UDPSession) WriteBuffers(v [][]byte) (n int, err error) { for { s.mu.Lock() if s.isClosed { s.mu.Unlock() return 0, errors.New(errBrokenPipe) } if s.kcp.WaitSnd() < int(s.kcp.snd_wnd) { for _, b := range v { n += len(b) for { if len(b) <= int(s.kcp.mss) { s.kcp.Send(b) break } else { s.kcp.Send(b[:s.kcp.mss]) b = b[s.kcp.mss:] } } } if s.kcp.WaitSnd() >= int(s.kcp.snd_wnd) || !s.writeDelay { s.kcp.flush(false) } s.mu.Unlock() atomic.AddUint64(&DefaultSnmp.BytesSent, uint64(n)) return n, nil } var timeout *time.Timer var c <-chan time.Time if !s.wd.IsZero() { if time.Now().After(s.wd) { s.mu.Unlock() return 0, errTimeout{} } delay := s.wd.Sub(time.Now()) timeout = time.NewTimer(delay) c = timeout.C } s.mu.Unlock() select { case <-s.chWriteEvent: case <-c: case <-s.die: case err = <-s.chWriteError: if timeout != nil { timeout.Stop() } return n, err } if timeout != nil { timeout.Stop() } } }
go
func (s *UDPSession) WriteBuffers(v [][]byte) (n int, err error) { for { s.mu.Lock() if s.isClosed { s.mu.Unlock() return 0, errors.New(errBrokenPipe) } if s.kcp.WaitSnd() < int(s.kcp.snd_wnd) { for _, b := range v { n += len(b) for { if len(b) <= int(s.kcp.mss) { s.kcp.Send(b) break } else { s.kcp.Send(b[:s.kcp.mss]) b = b[s.kcp.mss:] } } } if s.kcp.WaitSnd() >= int(s.kcp.snd_wnd) || !s.writeDelay { s.kcp.flush(false) } s.mu.Unlock() atomic.AddUint64(&DefaultSnmp.BytesSent, uint64(n)) return n, nil } var timeout *time.Timer var c <-chan time.Time if !s.wd.IsZero() { if time.Now().After(s.wd) { s.mu.Unlock() return 0, errTimeout{} } delay := s.wd.Sub(time.Now()) timeout = time.NewTimer(delay) c = timeout.C } s.mu.Unlock() select { case <-s.chWriteEvent: case <-c: case <-s.die: case err = <-s.chWriteError: if timeout != nil { timeout.Stop() } return n, err } if timeout != nil { timeout.Stop() } } }
[ "func", "(", "s", "*", "UDPSession", ")", "WriteBuffers", "(", "v", "[", "]", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "for", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "s", ".", "isClosed", "{", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "0", ",", "errors", ".", "New", "(", "errBrokenPipe", ")", "\n", "}", "\n", "if", "s", ".", "kcp", ".", "WaitSnd", "(", ")", "<", "int", "(", "s", ".", "kcp", ".", "snd_wnd", ")", "{", "for", "_", ",", "b", ":=", "range", "v", "{", "n", "+=", "len", "(", "b", ")", "\n", "for", "{", "if", "len", "(", "b", ")", "<=", "int", "(", "s", ".", "kcp", ".", "mss", ")", "{", "s", ".", "kcp", ".", "Send", "(", "b", ")", "\n", "break", "\n", "}", "else", "{", "s", ".", "kcp", ".", "Send", "(", "b", "[", ":", "s", ".", "kcp", ".", "mss", "]", ")", "\n", "b", "=", "b", "[", "s", ".", "kcp", ".", "mss", ":", "]", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "s", ".", "kcp", ".", "WaitSnd", "(", ")", ">=", "int", "(", "s", ".", "kcp", ".", "snd_wnd", ")", "||", "!", "s", ".", "writeDelay", "{", "s", ".", "kcp", ".", "flush", "(", "false", ")", "\n", "}", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "atomic", ".", "AddUint64", "(", "&", "DefaultSnmp", ".", "BytesSent", ",", "uint64", "(", "n", ")", ")", "\n", "return", "n", ",", "nil", "\n", "}", "\n", "var", "timeout", "*", "time", ".", "Timer", "\n", "var", "c", "<-", "chan", "time", ".", "Time", "\n", "if", "!", "s", ".", "wd", ".", "IsZero", "(", ")", "{", "if", "time", ".", "Now", "(", ")", ".", "After", "(", "s", ".", "wd", ")", "{", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "0", ",", "errTimeout", "{", "}", "\n", "}", "\n", "delay", ":=", "s", ".", "wd", ".", "Sub", "(", "time", ".", "Now", "(", ")", ")", "\n", "timeout", "=", "time", ".", "NewTimer", "(", "delay", ")", "\n", "c", "=", "timeout", ".", "C", "\n", "}", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "select", "{", "case", "<-", "s", ".", "chWriteEvent", ":", "case", "<-", "c", ":", "case", "<-", "s", ".", "die", ":", "case", "err", "=", "<-", "s", ".", "chWriteError", ":", "if", "timeout", "!=", "nil", "{", "timeout", ".", "Stop", "(", ")", "\n", "}", "\n", "return", "n", ",", "err", "\n", "}", "\n", "if", "timeout", "!=", "nil", "{", "timeout", ".", "Stop", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// WriteBuffers write a vector of byte slices to the underlying connection
[ "WriteBuffers", "write", "a", "vector", "of", "byte", "slices", "to", "the", "underlying", "connection" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L247-L305
train
xtaci/kcp-go
sess.go
SetWriteDelay
func (s *UDPSession) SetWriteDelay(delay bool) { s.mu.Lock() defer s.mu.Unlock() s.writeDelay = delay }
go
func (s *UDPSession) SetWriteDelay(delay bool) { s.mu.Lock() defer s.mu.Unlock() s.writeDelay = delay }
[ "func", "(", "s", "*", "UDPSession", ")", "SetWriteDelay", "(", "delay", "bool", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "s", ".", "writeDelay", "=", "delay", "\n", "}" ]
// SetWriteDelay delays write for bulk transfer until the next update interval
[ "SetWriteDelay", "delays", "write", "for", "bulk", "transfer", "until", "the", "next", "update", "interval" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L365-L369
train
xtaci/kcp-go
sess.go
SetWindowSize
func (s *UDPSession) SetWindowSize(sndwnd, rcvwnd int) { s.mu.Lock() defer s.mu.Unlock() s.kcp.WndSize(sndwnd, rcvwnd) }
go
func (s *UDPSession) SetWindowSize(sndwnd, rcvwnd int) { s.mu.Lock() defer s.mu.Unlock() s.kcp.WndSize(sndwnd, rcvwnd) }
[ "func", "(", "s", "*", "UDPSession", ")", "SetWindowSize", "(", "sndwnd", ",", "rcvwnd", "int", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "s", ".", "kcp", ".", "WndSize", "(", "sndwnd", ",", "rcvwnd", ")", "\n", "}" ]
// SetWindowSize set maximum window size
[ "SetWindowSize", "set", "maximum", "window", "size" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L372-L376
train
xtaci/kcp-go
sess.go
SetACKNoDelay
func (s *UDPSession) SetACKNoDelay(nodelay bool) { s.mu.Lock() defer s.mu.Unlock() s.ackNoDelay = nodelay }
go
func (s *UDPSession) SetACKNoDelay(nodelay bool) { s.mu.Lock() defer s.mu.Unlock() s.ackNoDelay = nodelay }
[ "func", "(", "s", "*", "UDPSession", ")", "SetACKNoDelay", "(", "nodelay", "bool", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "s", ".", "ackNoDelay", "=", "nodelay", "\n", "}" ]
// SetACKNoDelay changes ack flush option, set true to flush ack immediately,
[ "SetACKNoDelay", "changes", "ack", "flush", "option", "set", "true", "to", "flush", "ack", "immediately" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L402-L406
train
xtaci/kcp-go
sess.go
SetDUP
func (s *UDPSession) SetDUP(dup int) { s.mu.Lock() defer s.mu.Unlock() s.dup = dup }
go
func (s *UDPSession) SetDUP(dup int) { s.mu.Lock() defer s.mu.Unlock() s.dup = dup }
[ "func", "(", "s", "*", "UDPSession", ")", "SetDUP", "(", "dup", "int", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "s", ".", "dup", "=", "dup", "\n", "}" ]
// SetDUP duplicates udp packets for kcp output, for testing purpose only
[ "SetDUP", "duplicates", "udp", "packets", "for", "kcp", "output", "for", "testing", "purpose", "only" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L409-L413
train
xtaci/kcp-go
sess.go
SetReadBuffer
func (s *UDPSession) SetReadBuffer(bytes int) error { s.mu.Lock() defer s.mu.Unlock() if s.l == nil { if nc, ok := s.conn.(setReadBuffer); ok { return nc.SetReadBuffer(bytes) } } return errors.New(errInvalidOperation) }
go
func (s *UDPSession) SetReadBuffer(bytes int) error { s.mu.Lock() defer s.mu.Unlock() if s.l == nil { if nc, ok := s.conn.(setReadBuffer); ok { return nc.SetReadBuffer(bytes) } } return errors.New(errInvalidOperation) }
[ "func", "(", "s", "*", "UDPSession", ")", "SetReadBuffer", "(", "bytes", "int", ")", "error", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "s", ".", "l", "==", "nil", "{", "if", "nc", ",", "ok", ":=", "s", ".", "conn", ".", "(", "setReadBuffer", ")", ";", "ok", "{", "return", "nc", ".", "SetReadBuffer", "(", "bytes", ")", "\n", "}", "\n", "}", "\n", "return", "errors", ".", "New", "(", "errInvalidOperation", ")", "\n", "}" ]
// SetReadBuffer sets the socket read buffer, no effect if it's accepted from Listener
[ "SetReadBuffer", "sets", "the", "socket", "read", "buffer", "no", "effect", "if", "it", "s", "accepted", "from", "Listener" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L441-L450
train
xtaci/kcp-go
sess.go
update
func (s *UDPSession) update() (interval time.Duration) { s.mu.Lock() waitsnd := s.kcp.WaitSnd() interval = time.Duration(s.kcp.flush(false)) * time.Millisecond if s.kcp.WaitSnd() < waitsnd { s.notifyWriteEvent() } s.mu.Unlock() return }
go
func (s *UDPSession) update() (interval time.Duration) { s.mu.Lock() waitsnd := s.kcp.WaitSnd() interval = time.Duration(s.kcp.flush(false)) * time.Millisecond if s.kcp.WaitSnd() < waitsnd { s.notifyWriteEvent() } s.mu.Unlock() return }
[ "func", "(", "s", "*", "UDPSession", ")", "update", "(", ")", "(", "interval", "time", ".", "Duration", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "waitsnd", ":=", "s", ".", "kcp", ".", "WaitSnd", "(", ")", "\n", "interval", "=", "time", ".", "Duration", "(", "s", ".", "kcp", ".", "flush", "(", "false", ")", ")", "*", "time", ".", "Millisecond", "\n", "if", "s", ".", "kcp", ".", "WaitSnd", "(", ")", "<", "waitsnd", "{", "s", ".", "notifyWriteEvent", "(", ")", "\n", "}", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "\n", "}" ]
// kcp update, returns interval for next calling
[ "kcp", "update", "returns", "interval", "for", "next", "calling" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L518-L527
train
xtaci/kcp-go
sess.go
SetReadBuffer
func (l *Listener) SetReadBuffer(bytes int) error { if nc, ok := l.conn.(setReadBuffer); ok { return nc.SetReadBuffer(bytes) } return errors.New(errInvalidOperation) }
go
func (l *Listener) SetReadBuffer(bytes int) error { if nc, ok := l.conn.(setReadBuffer); ok { return nc.SetReadBuffer(bytes) } return errors.New(errInvalidOperation) }
[ "func", "(", "l", "*", "Listener", ")", "SetReadBuffer", "(", "bytes", "int", ")", "error", "{", "if", "nc", ",", "ok", ":=", "l", ".", "conn", ".", "(", "setReadBuffer", ")", ";", "ok", "{", "return", "nc", ".", "SetReadBuffer", "(", "bytes", ")", "\n", "}", "\n", "return", "errors", ".", "New", "(", "errInvalidOperation", ")", "\n", "}" ]
// SetReadBuffer sets the socket read buffer for the Listener
[ "SetReadBuffer", "sets", "the", "socket", "read", "buffer", "for", "the", "Listener" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L733-L738
train
xtaci/kcp-go
sess.go
SetWriteBuffer
func (l *Listener) SetWriteBuffer(bytes int) error { if nc, ok := l.conn.(setWriteBuffer); ok { return nc.SetWriteBuffer(bytes) } return errors.New(errInvalidOperation) }
go
func (l *Listener) SetWriteBuffer(bytes int) error { if nc, ok := l.conn.(setWriteBuffer); ok { return nc.SetWriteBuffer(bytes) } return errors.New(errInvalidOperation) }
[ "func", "(", "l", "*", "Listener", ")", "SetWriteBuffer", "(", "bytes", "int", ")", "error", "{", "if", "nc", ",", "ok", ":=", "l", ".", "conn", ".", "(", "setWriteBuffer", ")", ";", "ok", "{", "return", "nc", ".", "SetWriteBuffer", "(", "bytes", ")", "\n", "}", "\n", "return", "errors", ".", "New", "(", "errInvalidOperation", ")", "\n", "}" ]
// SetWriteBuffer sets the socket write buffer for the Listener
[ "SetWriteBuffer", "sets", "the", "socket", "write", "buffer", "for", "the", "Listener" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L741-L746
train
xtaci/kcp-go
sess.go
SetDSCP
func (l *Listener) SetDSCP(dscp int) error { if nc, ok := l.conn.(net.Conn); ok { addr, _ := net.ResolveUDPAddr("udp", nc.LocalAddr().String()) if addr.IP.To4() != nil { return ipv4.NewConn(nc).SetTOS(dscp << 2) } else { return ipv6.NewConn(nc).SetTrafficClass(dscp) } } return errors.New(errInvalidOperation) }
go
func (l *Listener) SetDSCP(dscp int) error { if nc, ok := l.conn.(net.Conn); ok { addr, _ := net.ResolveUDPAddr("udp", nc.LocalAddr().String()) if addr.IP.To4() != nil { return ipv4.NewConn(nc).SetTOS(dscp << 2) } else { return ipv6.NewConn(nc).SetTrafficClass(dscp) } } return errors.New(errInvalidOperation) }
[ "func", "(", "l", "*", "Listener", ")", "SetDSCP", "(", "dscp", "int", ")", "error", "{", "if", "nc", ",", "ok", ":=", "l", ".", "conn", ".", "(", "net", ".", "Conn", ")", ";", "ok", "{", "addr", ",", "_", ":=", "net", ".", "ResolveUDPAddr", "(", "\"udp\"", ",", "nc", ".", "LocalAddr", "(", ")", ".", "String", "(", ")", ")", "\n", "if", "addr", ".", "IP", ".", "To4", "(", ")", "!=", "nil", "{", "return", "ipv4", ".", "NewConn", "(", "nc", ")", ".", "SetTOS", "(", "dscp", "<<", "2", ")", "\n", "}", "else", "{", "return", "ipv6", ".", "NewConn", "(", "nc", ")", ".", "SetTrafficClass", "(", "dscp", ")", "\n", "}", "\n", "}", "\n", "return", "errors", ".", "New", "(", "errInvalidOperation", ")", "\n", "}" ]
// SetDSCP sets the 6bit DSCP field of IP header
[ "SetDSCP", "sets", "the", "6bit", "DSCP", "field", "of", "IP", "header" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L749-L759
train
xtaci/kcp-go
sess.go
AcceptKCP
func (l *Listener) AcceptKCP() (*UDPSession, error) { var timeout <-chan time.Time if tdeadline, ok := l.rd.Load().(time.Time); ok && !tdeadline.IsZero() { timeout = time.After(tdeadline.Sub(time.Now())) } select { case <-timeout: return nil, &errTimeout{} case c := <-l.chAccepts: return c, nil case <-l.die: return nil, errors.New(errBrokenPipe) } }
go
func (l *Listener) AcceptKCP() (*UDPSession, error) { var timeout <-chan time.Time if tdeadline, ok := l.rd.Load().(time.Time); ok && !tdeadline.IsZero() { timeout = time.After(tdeadline.Sub(time.Now())) } select { case <-timeout: return nil, &errTimeout{} case c := <-l.chAccepts: return c, nil case <-l.die: return nil, errors.New(errBrokenPipe) } }
[ "func", "(", "l", "*", "Listener", ")", "AcceptKCP", "(", ")", "(", "*", "UDPSession", ",", "error", ")", "{", "var", "timeout", "<-", "chan", "time", ".", "Time", "\n", "if", "tdeadline", ",", "ok", ":=", "l", ".", "rd", ".", "Load", "(", ")", ".", "(", "time", ".", "Time", ")", ";", "ok", "&&", "!", "tdeadline", ".", "IsZero", "(", ")", "{", "timeout", "=", "time", ".", "After", "(", "tdeadline", ".", "Sub", "(", "time", ".", "Now", "(", ")", ")", ")", "\n", "}", "\n", "select", "{", "case", "<-", "timeout", ":", "return", "nil", ",", "&", "errTimeout", "{", "}", "\n", "case", "c", ":=", "<-", "l", ".", "chAccepts", ":", "return", "c", ",", "nil", "\n", "case", "<-", "l", ".", "die", ":", "return", "nil", ",", "errors", ".", "New", "(", "errBrokenPipe", ")", "\n", "}", "\n", "}" ]
// AcceptKCP accepts a KCP connection
[ "AcceptKCP", "accepts", "a", "KCP", "connection" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L767-L781
train
xtaci/kcp-go
sess.go
Close
func (l *Listener) Close() error { close(l.die) return l.conn.Close() }
go
func (l *Listener) Close() error { close(l.die) return l.conn.Close() }
[ "func", "(", "l", "*", "Listener", ")", "Close", "(", ")", "error", "{", "close", "(", "l", ".", "die", ")", "\n", "return", "l", ".", "conn", ".", "Close", "(", ")", "\n", "}" ]
// Close stops listening on the UDP address. Already Accepted connections are not closed.
[ "Close", "stops", "listening", "on", "the", "UDP", "address", ".", "Already", "Accepted", "connections", "are", "not", "closed", "." ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L803-L806
train
xtaci/kcp-go
sess.go
closeSession
func (l *Listener) closeSession(remote net.Addr) (ret bool) { l.sessionLock.Lock() defer l.sessionLock.Unlock() if _, ok := l.sessions[remote.String()]; ok { delete(l.sessions, remote.String()) return true } return false }
go
func (l *Listener) closeSession(remote net.Addr) (ret bool) { l.sessionLock.Lock() defer l.sessionLock.Unlock() if _, ok := l.sessions[remote.String()]; ok { delete(l.sessions, remote.String()) return true } return false }
[ "func", "(", "l", "*", "Listener", ")", "closeSession", "(", "remote", "net", ".", "Addr", ")", "(", "ret", "bool", ")", "{", "l", ".", "sessionLock", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "sessionLock", ".", "Unlock", "(", ")", "\n", "if", "_", ",", "ok", ":=", "l", ".", "sessions", "[", "remote", ".", "String", "(", ")", "]", ";", "ok", "{", "delete", "(", "l", ".", "sessions", ",", "remote", ".", "String", "(", ")", ")", "\n", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// closeSession notify the listener that a session has closed
[ "closeSession", "notify", "the", "listener", "that", "a", "session", "has", "closed" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L809-L817
train
xtaci/kcp-go
sess.go
ListenWithOptions
func ListenWithOptions(laddr string, block BlockCrypt, dataShards, parityShards int) (*Listener, error) { udpaddr, err := net.ResolveUDPAddr("udp", laddr) if err != nil { return nil, errors.Wrap(err, "net.ResolveUDPAddr") } conn, err := net.ListenUDP("udp", udpaddr) if err != nil { return nil, errors.Wrap(err, "net.ListenUDP") } return ServeConn(block, dataShards, parityShards, conn) }
go
func ListenWithOptions(laddr string, block BlockCrypt, dataShards, parityShards int) (*Listener, error) { udpaddr, err := net.ResolveUDPAddr("udp", laddr) if err != nil { return nil, errors.Wrap(err, "net.ResolveUDPAddr") } conn, err := net.ListenUDP("udp", udpaddr) if err != nil { return nil, errors.Wrap(err, "net.ListenUDP") } return ServeConn(block, dataShards, parityShards, conn) }
[ "func", "ListenWithOptions", "(", "laddr", "string", ",", "block", "BlockCrypt", ",", "dataShards", ",", "parityShards", "int", ")", "(", "*", "Listener", ",", "error", ")", "{", "udpaddr", ",", "err", ":=", "net", ".", "ResolveUDPAddr", "(", "\"udp\"", ",", "laddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"net.ResolveUDPAddr\"", ")", "\n", "}", "\n", "conn", ",", "err", ":=", "net", ".", "ListenUDP", "(", "\"udp\"", ",", "udpaddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"net.ListenUDP\"", ")", "\n", "}", "\n", "return", "ServeConn", "(", "block", ",", "dataShards", ",", "parityShards", ",", "conn", ")", "\n", "}" ]
// ListenWithOptions listens for incoming KCP packets addressed to the local address laddr on the network "udp" with packet encryption, // dataShards, parityShards defines Reed-Solomon Erasure Coding parameters
[ "ListenWithOptions", "listens", "for", "incoming", "KCP", "packets", "addressed", "to", "the", "local", "address", "laddr", "on", "the", "network", "udp", "with", "packet", "encryption", "dataShards", "parityShards", "defines", "Reed", "-", "Solomon", "Erasure", "Coding", "parameters" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L827-L838
train
xtaci/kcp-go
sess.go
ServeConn
func ServeConn(block BlockCrypt, dataShards, parityShards int, conn net.PacketConn) (*Listener, error) { l := new(Listener) l.conn = conn l.sessions = make(map[string]*UDPSession) l.chAccepts = make(chan *UDPSession, acceptBacklog) l.chSessionClosed = make(chan net.Addr) l.die = make(chan struct{}) l.dataShards = dataShards l.parityShards = parityShards l.block = block l.fecDecoder = newFECDecoder(rxFECMulti*(dataShards+parityShards), dataShards, parityShards) // calculate header size if l.block != nil { l.headerSize += cryptHeaderSize } if l.fecDecoder != nil { l.headerSize += fecHeaderSizePlus2 } go l.monitor() return l, nil }
go
func ServeConn(block BlockCrypt, dataShards, parityShards int, conn net.PacketConn) (*Listener, error) { l := new(Listener) l.conn = conn l.sessions = make(map[string]*UDPSession) l.chAccepts = make(chan *UDPSession, acceptBacklog) l.chSessionClosed = make(chan net.Addr) l.die = make(chan struct{}) l.dataShards = dataShards l.parityShards = parityShards l.block = block l.fecDecoder = newFECDecoder(rxFECMulti*(dataShards+parityShards), dataShards, parityShards) // calculate header size if l.block != nil { l.headerSize += cryptHeaderSize } if l.fecDecoder != nil { l.headerSize += fecHeaderSizePlus2 } go l.monitor() return l, nil }
[ "func", "ServeConn", "(", "block", "BlockCrypt", ",", "dataShards", ",", "parityShards", "int", ",", "conn", "net", ".", "PacketConn", ")", "(", "*", "Listener", ",", "error", ")", "{", "l", ":=", "new", "(", "Listener", ")", "\n", "l", ".", "conn", "=", "conn", "\n", "l", ".", "sessions", "=", "make", "(", "map", "[", "string", "]", "*", "UDPSession", ")", "\n", "l", ".", "chAccepts", "=", "make", "(", "chan", "*", "UDPSession", ",", "acceptBacklog", ")", "\n", "l", ".", "chSessionClosed", "=", "make", "(", "chan", "net", ".", "Addr", ")", "\n", "l", ".", "die", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "l", ".", "dataShards", "=", "dataShards", "\n", "l", ".", "parityShards", "=", "parityShards", "\n", "l", ".", "block", "=", "block", "\n", "l", ".", "fecDecoder", "=", "newFECDecoder", "(", "rxFECMulti", "*", "(", "dataShards", "+", "parityShards", ")", ",", "dataShards", ",", "parityShards", ")", "\n", "if", "l", ".", "block", "!=", "nil", "{", "l", ".", "headerSize", "+=", "cryptHeaderSize", "\n", "}", "\n", "if", "l", ".", "fecDecoder", "!=", "nil", "{", "l", ".", "headerSize", "+=", "fecHeaderSizePlus2", "\n", "}", "\n", "go", "l", ".", "monitor", "(", ")", "\n", "return", "l", ",", "nil", "\n", "}" ]
// ServeConn serves KCP protocol for a single packet connection.
[ "ServeConn", "serves", "KCP", "protocol", "for", "a", "single", "packet", "connection", "." ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L841-L863
train
xtaci/kcp-go
sess.go
DialWithOptions
func DialWithOptions(raddr string, block BlockCrypt, dataShards, parityShards int) (*UDPSession, error) { // network type detection udpaddr, err := net.ResolveUDPAddr("udp", raddr) if err != nil { return nil, errors.Wrap(err, "net.ResolveUDPAddr") } network := "udp4" if udpaddr.IP.To4() == nil { network = "udp" } conn, err := net.ListenUDP(network, nil) if err != nil { return nil, errors.Wrap(err, "net.DialUDP") } return NewConn(raddr, block, dataShards, parityShards, conn) }
go
func DialWithOptions(raddr string, block BlockCrypt, dataShards, parityShards int) (*UDPSession, error) { // network type detection udpaddr, err := net.ResolveUDPAddr("udp", raddr) if err != nil { return nil, errors.Wrap(err, "net.ResolveUDPAddr") } network := "udp4" if udpaddr.IP.To4() == nil { network = "udp" } conn, err := net.ListenUDP(network, nil) if err != nil { return nil, errors.Wrap(err, "net.DialUDP") } return NewConn(raddr, block, dataShards, parityShards, conn) }
[ "func", "DialWithOptions", "(", "raddr", "string", ",", "block", "BlockCrypt", ",", "dataShards", ",", "parityShards", "int", ")", "(", "*", "UDPSession", ",", "error", ")", "{", "udpaddr", ",", "err", ":=", "net", ".", "ResolveUDPAddr", "(", "\"udp\"", ",", "raddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"net.ResolveUDPAddr\"", ")", "\n", "}", "\n", "network", ":=", "\"udp4\"", "\n", "if", "udpaddr", ".", "IP", ".", "To4", "(", ")", "==", "nil", "{", "network", "=", "\"udp\"", "\n", "}", "\n", "conn", ",", "err", ":=", "net", ".", "ListenUDP", "(", "network", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"net.DialUDP\"", ")", "\n", "}", "\n", "return", "NewConn", "(", "raddr", ",", "block", ",", "dataShards", ",", "parityShards", ",", "conn", ")", "\n", "}" ]
// DialWithOptions connects to the remote address "raddr" on the network "udp" with packet encryption
[ "DialWithOptions", "connects", "to", "the", "remote", "address", "raddr", "on", "the", "network", "udp", "with", "packet", "encryption" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L869-L886
train
xtaci/kcp-go
sess.go
NewConn
func NewConn(raddr string, block BlockCrypt, dataShards, parityShards int, conn net.PacketConn) (*UDPSession, error) { udpaddr, err := net.ResolveUDPAddr("udp", raddr) if err != nil { return nil, errors.Wrap(err, "net.ResolveUDPAddr") } var convid uint32 binary.Read(rand.Reader, binary.LittleEndian, &convid) return newUDPSession(convid, dataShards, parityShards, nil, conn, udpaddr, block), nil }
go
func NewConn(raddr string, block BlockCrypt, dataShards, parityShards int, conn net.PacketConn) (*UDPSession, error) { udpaddr, err := net.ResolveUDPAddr("udp", raddr) if err != nil { return nil, errors.Wrap(err, "net.ResolveUDPAddr") } var convid uint32 binary.Read(rand.Reader, binary.LittleEndian, &convid) return newUDPSession(convid, dataShards, parityShards, nil, conn, udpaddr, block), nil }
[ "func", "NewConn", "(", "raddr", "string", ",", "block", "BlockCrypt", ",", "dataShards", ",", "parityShards", "int", ",", "conn", "net", ".", "PacketConn", ")", "(", "*", "UDPSession", ",", "error", ")", "{", "udpaddr", ",", "err", ":=", "net", ".", "ResolveUDPAddr", "(", "\"udp\"", ",", "raddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"net.ResolveUDPAddr\"", ")", "\n", "}", "\n", "var", "convid", "uint32", "\n", "binary", ".", "Read", "(", "rand", ".", "Reader", ",", "binary", ".", "LittleEndian", ",", "&", "convid", ")", "\n", "return", "newUDPSession", "(", "convid", ",", "dataShards", ",", "parityShards", ",", "nil", ",", "conn", ",", "udpaddr", ",", "block", ")", ",", "nil", "\n", "}" ]
// NewConn establishes a session and talks KCP protocol over a packet connection.
[ "NewConn", "establishes", "a", "session", "and", "talks", "KCP", "protocol", "over", "a", "packet", "connection", "." ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L889-L898
train
xtaci/kcp-go
snmp.go
ToSlice
func (s *Snmp) ToSlice() []string { snmp := s.Copy() return []string{ fmt.Sprint(snmp.BytesSent), fmt.Sprint(snmp.BytesReceived), fmt.Sprint(snmp.MaxConn), fmt.Sprint(snmp.ActiveOpens), fmt.Sprint(snmp.PassiveOpens), fmt.Sprint(snmp.CurrEstab), fmt.Sprint(snmp.InErrs), fmt.Sprint(snmp.InCsumErrors), fmt.Sprint(snmp.KCPInErrors), fmt.Sprint(snmp.InPkts), fmt.Sprint(snmp.OutPkts), fmt.Sprint(snmp.InSegs), fmt.Sprint(snmp.OutSegs), fmt.Sprint(snmp.InBytes), fmt.Sprint(snmp.OutBytes), fmt.Sprint(snmp.RetransSegs), fmt.Sprint(snmp.FastRetransSegs), fmt.Sprint(snmp.EarlyRetransSegs), fmt.Sprint(snmp.LostSegs), fmt.Sprint(snmp.RepeatSegs), fmt.Sprint(snmp.FECParityShards), fmt.Sprint(snmp.FECErrs), fmt.Sprint(snmp.FECRecovered), fmt.Sprint(snmp.FECShortShards), } }
go
func (s *Snmp) ToSlice() []string { snmp := s.Copy() return []string{ fmt.Sprint(snmp.BytesSent), fmt.Sprint(snmp.BytesReceived), fmt.Sprint(snmp.MaxConn), fmt.Sprint(snmp.ActiveOpens), fmt.Sprint(snmp.PassiveOpens), fmt.Sprint(snmp.CurrEstab), fmt.Sprint(snmp.InErrs), fmt.Sprint(snmp.InCsumErrors), fmt.Sprint(snmp.KCPInErrors), fmt.Sprint(snmp.InPkts), fmt.Sprint(snmp.OutPkts), fmt.Sprint(snmp.InSegs), fmt.Sprint(snmp.OutSegs), fmt.Sprint(snmp.InBytes), fmt.Sprint(snmp.OutBytes), fmt.Sprint(snmp.RetransSegs), fmt.Sprint(snmp.FastRetransSegs), fmt.Sprint(snmp.EarlyRetransSegs), fmt.Sprint(snmp.LostSegs), fmt.Sprint(snmp.RepeatSegs), fmt.Sprint(snmp.FECParityShards), fmt.Sprint(snmp.FECErrs), fmt.Sprint(snmp.FECRecovered), fmt.Sprint(snmp.FECShortShards), } }
[ "func", "(", "s", "*", "Snmp", ")", "ToSlice", "(", ")", "[", "]", "string", "{", "snmp", ":=", "s", ".", "Copy", "(", ")", "\n", "return", "[", "]", "string", "{", "fmt", ".", "Sprint", "(", "snmp", ".", "BytesSent", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "BytesReceived", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "MaxConn", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "ActiveOpens", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "PassiveOpens", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "CurrEstab", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "InErrs", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "InCsumErrors", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "KCPInErrors", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "InPkts", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "OutPkts", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "InSegs", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "OutSegs", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "InBytes", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "OutBytes", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "RetransSegs", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "FastRetransSegs", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "EarlyRetransSegs", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "LostSegs", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "RepeatSegs", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "FECParityShards", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "FECErrs", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "FECRecovered", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "FECShortShards", ")", ",", "}", "\n", "}" ]
// ToSlice returns current snmp info as slice
[ "ToSlice", "returns", "current", "snmp", "info", "as", "slice" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/snmp.go#L71-L99
train
xtaci/kcp-go
snmp.go
Copy
func (s *Snmp) Copy() *Snmp { d := newSnmp() d.BytesSent = atomic.LoadUint64(&s.BytesSent) d.BytesReceived = atomic.LoadUint64(&s.BytesReceived) d.MaxConn = atomic.LoadUint64(&s.MaxConn) d.ActiveOpens = atomic.LoadUint64(&s.ActiveOpens) d.PassiveOpens = atomic.LoadUint64(&s.PassiveOpens) d.CurrEstab = atomic.LoadUint64(&s.CurrEstab) d.InErrs = atomic.LoadUint64(&s.InErrs) d.InCsumErrors = atomic.LoadUint64(&s.InCsumErrors) d.KCPInErrors = atomic.LoadUint64(&s.KCPInErrors) d.InPkts = atomic.LoadUint64(&s.InPkts) d.OutPkts = atomic.LoadUint64(&s.OutPkts) d.InSegs = atomic.LoadUint64(&s.InSegs) d.OutSegs = atomic.LoadUint64(&s.OutSegs) d.InBytes = atomic.LoadUint64(&s.InBytes) d.OutBytes = atomic.LoadUint64(&s.OutBytes) d.RetransSegs = atomic.LoadUint64(&s.RetransSegs) d.FastRetransSegs = atomic.LoadUint64(&s.FastRetransSegs) d.EarlyRetransSegs = atomic.LoadUint64(&s.EarlyRetransSegs) d.LostSegs = atomic.LoadUint64(&s.LostSegs) d.RepeatSegs = atomic.LoadUint64(&s.RepeatSegs) d.FECParityShards = atomic.LoadUint64(&s.FECParityShards) d.FECErrs = atomic.LoadUint64(&s.FECErrs) d.FECRecovered = atomic.LoadUint64(&s.FECRecovered) d.FECShortShards = atomic.LoadUint64(&s.FECShortShards) return d }
go
func (s *Snmp) Copy() *Snmp { d := newSnmp() d.BytesSent = atomic.LoadUint64(&s.BytesSent) d.BytesReceived = atomic.LoadUint64(&s.BytesReceived) d.MaxConn = atomic.LoadUint64(&s.MaxConn) d.ActiveOpens = atomic.LoadUint64(&s.ActiveOpens) d.PassiveOpens = atomic.LoadUint64(&s.PassiveOpens) d.CurrEstab = atomic.LoadUint64(&s.CurrEstab) d.InErrs = atomic.LoadUint64(&s.InErrs) d.InCsumErrors = atomic.LoadUint64(&s.InCsumErrors) d.KCPInErrors = atomic.LoadUint64(&s.KCPInErrors) d.InPkts = atomic.LoadUint64(&s.InPkts) d.OutPkts = atomic.LoadUint64(&s.OutPkts) d.InSegs = atomic.LoadUint64(&s.InSegs) d.OutSegs = atomic.LoadUint64(&s.OutSegs) d.InBytes = atomic.LoadUint64(&s.InBytes) d.OutBytes = atomic.LoadUint64(&s.OutBytes) d.RetransSegs = atomic.LoadUint64(&s.RetransSegs) d.FastRetransSegs = atomic.LoadUint64(&s.FastRetransSegs) d.EarlyRetransSegs = atomic.LoadUint64(&s.EarlyRetransSegs) d.LostSegs = atomic.LoadUint64(&s.LostSegs) d.RepeatSegs = atomic.LoadUint64(&s.RepeatSegs) d.FECParityShards = atomic.LoadUint64(&s.FECParityShards) d.FECErrs = atomic.LoadUint64(&s.FECErrs) d.FECRecovered = atomic.LoadUint64(&s.FECRecovered) d.FECShortShards = atomic.LoadUint64(&s.FECShortShards) return d }
[ "func", "(", "s", "*", "Snmp", ")", "Copy", "(", ")", "*", "Snmp", "{", "d", ":=", "newSnmp", "(", ")", "\n", "d", ".", "BytesSent", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "BytesSent", ")", "\n", "d", ".", "BytesReceived", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "BytesReceived", ")", "\n", "d", ".", "MaxConn", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "MaxConn", ")", "\n", "d", ".", "ActiveOpens", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "ActiveOpens", ")", "\n", "d", ".", "PassiveOpens", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "PassiveOpens", ")", "\n", "d", ".", "CurrEstab", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "CurrEstab", ")", "\n", "d", ".", "InErrs", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "InErrs", ")", "\n", "d", ".", "InCsumErrors", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "InCsumErrors", ")", "\n", "d", ".", "KCPInErrors", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "KCPInErrors", ")", "\n", "d", ".", "InPkts", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "InPkts", ")", "\n", "d", ".", "OutPkts", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "OutPkts", ")", "\n", "d", ".", "InSegs", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "InSegs", ")", "\n", "d", ".", "OutSegs", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "OutSegs", ")", "\n", "d", ".", "InBytes", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "InBytes", ")", "\n", "d", ".", "OutBytes", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "OutBytes", ")", "\n", "d", ".", "RetransSegs", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "RetransSegs", ")", "\n", "d", ".", "FastRetransSegs", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "FastRetransSegs", ")", "\n", "d", ".", "EarlyRetransSegs", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "EarlyRetransSegs", ")", "\n", "d", ".", "LostSegs", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "LostSegs", ")", "\n", "d", ".", "RepeatSegs", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "RepeatSegs", ")", "\n", "d", ".", "FECParityShards", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "FECParityShards", ")", "\n", "d", ".", "FECErrs", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "FECErrs", ")", "\n", "d", ".", "FECRecovered", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "FECRecovered", ")", "\n", "d", ".", "FECShortShards", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "FECShortShards", ")", "\n", "return", "d", "\n", "}" ]
// Copy make a copy of current snmp snapshot
[ "Copy", "make", "a", "copy", "of", "current", "snmp", "snapshot" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/snmp.go#L102-L129
train
xtaci/kcp-go
snmp.go
Reset
func (s *Snmp) Reset() { atomic.StoreUint64(&s.BytesSent, 0) atomic.StoreUint64(&s.BytesReceived, 0) atomic.StoreUint64(&s.MaxConn, 0) atomic.StoreUint64(&s.ActiveOpens, 0) atomic.StoreUint64(&s.PassiveOpens, 0) atomic.StoreUint64(&s.CurrEstab, 0) atomic.StoreUint64(&s.InErrs, 0) atomic.StoreUint64(&s.InCsumErrors, 0) atomic.StoreUint64(&s.KCPInErrors, 0) atomic.StoreUint64(&s.InPkts, 0) atomic.StoreUint64(&s.OutPkts, 0) atomic.StoreUint64(&s.InSegs, 0) atomic.StoreUint64(&s.OutSegs, 0) atomic.StoreUint64(&s.InBytes, 0) atomic.StoreUint64(&s.OutBytes, 0) atomic.StoreUint64(&s.RetransSegs, 0) atomic.StoreUint64(&s.FastRetransSegs, 0) atomic.StoreUint64(&s.EarlyRetransSegs, 0) atomic.StoreUint64(&s.LostSegs, 0) atomic.StoreUint64(&s.RepeatSegs, 0) atomic.StoreUint64(&s.FECParityShards, 0) atomic.StoreUint64(&s.FECErrs, 0) atomic.StoreUint64(&s.FECRecovered, 0) atomic.StoreUint64(&s.FECShortShards, 0) }
go
func (s *Snmp) Reset() { atomic.StoreUint64(&s.BytesSent, 0) atomic.StoreUint64(&s.BytesReceived, 0) atomic.StoreUint64(&s.MaxConn, 0) atomic.StoreUint64(&s.ActiveOpens, 0) atomic.StoreUint64(&s.PassiveOpens, 0) atomic.StoreUint64(&s.CurrEstab, 0) atomic.StoreUint64(&s.InErrs, 0) atomic.StoreUint64(&s.InCsumErrors, 0) atomic.StoreUint64(&s.KCPInErrors, 0) atomic.StoreUint64(&s.InPkts, 0) atomic.StoreUint64(&s.OutPkts, 0) atomic.StoreUint64(&s.InSegs, 0) atomic.StoreUint64(&s.OutSegs, 0) atomic.StoreUint64(&s.InBytes, 0) atomic.StoreUint64(&s.OutBytes, 0) atomic.StoreUint64(&s.RetransSegs, 0) atomic.StoreUint64(&s.FastRetransSegs, 0) atomic.StoreUint64(&s.EarlyRetransSegs, 0) atomic.StoreUint64(&s.LostSegs, 0) atomic.StoreUint64(&s.RepeatSegs, 0) atomic.StoreUint64(&s.FECParityShards, 0) atomic.StoreUint64(&s.FECErrs, 0) atomic.StoreUint64(&s.FECRecovered, 0) atomic.StoreUint64(&s.FECShortShards, 0) }
[ "func", "(", "s", "*", "Snmp", ")", "Reset", "(", ")", "{", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "BytesSent", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "BytesReceived", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "MaxConn", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "ActiveOpens", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "PassiveOpens", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "CurrEstab", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "InErrs", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "InCsumErrors", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "KCPInErrors", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "InPkts", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "OutPkts", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "InSegs", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "OutSegs", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "InBytes", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "OutBytes", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "RetransSegs", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "FastRetransSegs", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "EarlyRetransSegs", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "LostSegs", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "RepeatSegs", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "FECParityShards", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "FECErrs", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "FECRecovered", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "FECShortShards", ",", "0", ")", "\n", "}" ]
// Reset values to zero
[ "Reset", "values", "to", "zero" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/snmp.go#L132-L157
train
xtaci/kcp-go
crypt.go
NewSimpleXORBlockCrypt
func NewSimpleXORBlockCrypt(key []byte) (BlockCrypt, error) { c := new(simpleXORBlockCrypt) c.xortbl = pbkdf2.Key(key, []byte(saltxor), 32, mtuLimit, sha1.New) return c, nil }
go
func NewSimpleXORBlockCrypt(key []byte) (BlockCrypt, error) { c := new(simpleXORBlockCrypt) c.xortbl = pbkdf2.Key(key, []byte(saltxor), 32, mtuLimit, sha1.New) return c, nil }
[ "func", "NewSimpleXORBlockCrypt", "(", "key", "[", "]", "byte", ")", "(", "BlockCrypt", ",", "error", ")", "{", "c", ":=", "new", "(", "simpleXORBlockCrypt", ")", "\n", "c", ".", "xortbl", "=", "pbkdf2", ".", "Key", "(", "key", ",", "[", "]", "byte", "(", "saltxor", ")", ",", "32", ",", "mtuLimit", ",", "sha1", ".", "New", ")", "\n", "return", "c", ",", "nil", "\n", "}" ]
// NewSimpleXORBlockCrypt simple xor with key expanding
[ "NewSimpleXORBlockCrypt", "simple", "xor", "with", "key", "expanding" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/crypt.go#L224-L228
train
xtaci/kcp-go
crypt.go
encrypt
func encrypt(block cipher.Block, dst, src, buf []byte) { switch block.BlockSize() { case 8: encrypt8(block, dst, src, buf) case 16: encrypt16(block, dst, src, buf) default: encryptVariant(block, dst, src, buf) } }
go
func encrypt(block cipher.Block, dst, src, buf []byte) { switch block.BlockSize() { case 8: encrypt8(block, dst, src, buf) case 16: encrypt16(block, dst, src, buf) default: encryptVariant(block, dst, src, buf) } }
[ "func", "encrypt", "(", "block", "cipher", ".", "Block", ",", "dst", ",", "src", ",", "buf", "[", "]", "byte", ")", "{", "switch", "block", ".", "BlockSize", "(", ")", "{", "case", "8", ":", "encrypt8", "(", "block", ",", "dst", ",", "src", ",", "buf", ")", "\n", "case", "16", ":", "encrypt16", "(", "block", ",", "dst", ",", "src", ",", "buf", ")", "\n", "default", ":", "encryptVariant", "(", "block", ",", "dst", ",", "src", ",", "buf", ")", "\n", "}", "\n", "}" ]
// packet encryption with local CFB mode
[ "packet", "encryption", "with", "local", "CFB", "mode" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/crypt.go#L244-L253
train
hashicorp/yamux
addr.go
LocalAddr
func (s *Session) LocalAddr() net.Addr { addr, ok := s.conn.(hasAddr) if !ok { return &yamuxAddr{"local"} } return addr.LocalAddr() }
go
func (s *Session) LocalAddr() net.Addr { addr, ok := s.conn.(hasAddr) if !ok { return &yamuxAddr{"local"} } return addr.LocalAddr() }
[ "func", "(", "s", "*", "Session", ")", "LocalAddr", "(", ")", "net", ".", "Addr", "{", "addr", ",", "ok", ":=", "s", ".", "conn", ".", "(", "hasAddr", ")", "\n", "if", "!", "ok", "{", "return", "&", "yamuxAddr", "{", "\"local\"", "}", "\n", "}", "\n", "return", "addr", ".", "LocalAddr", "(", ")", "\n", "}" ]
// LocalAddr is used to get the local address of the // underlying connection.
[ "LocalAddr", "is", "used", "to", "get", "the", "local", "address", "of", "the", "underlying", "connection", "." ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/addr.go#L34-L40
train
hashicorp/yamux
stream.go
newStream
func newStream(session *Session, id uint32, state streamState) *Stream { s := &Stream{ id: id, session: session, state: state, controlHdr: header(make([]byte, headerSize)), controlErr: make(chan error, 1), sendHdr: header(make([]byte, headerSize)), sendErr: make(chan error, 1), recvWindow: initialStreamWindow, sendWindow: initialStreamWindow, recvNotifyCh: make(chan struct{}, 1), sendNotifyCh: make(chan struct{}, 1), } s.readDeadline.Store(time.Time{}) s.writeDeadline.Store(time.Time{}) return s }
go
func newStream(session *Session, id uint32, state streamState) *Stream { s := &Stream{ id: id, session: session, state: state, controlHdr: header(make([]byte, headerSize)), controlErr: make(chan error, 1), sendHdr: header(make([]byte, headerSize)), sendErr: make(chan error, 1), recvWindow: initialStreamWindow, sendWindow: initialStreamWindow, recvNotifyCh: make(chan struct{}, 1), sendNotifyCh: make(chan struct{}, 1), } s.readDeadline.Store(time.Time{}) s.writeDeadline.Store(time.Time{}) return s }
[ "func", "newStream", "(", "session", "*", "Session", ",", "id", "uint32", ",", "state", "streamState", ")", "*", "Stream", "{", "s", ":=", "&", "Stream", "{", "id", ":", "id", ",", "session", ":", "session", ",", "state", ":", "state", ",", "controlHdr", ":", "header", "(", "make", "(", "[", "]", "byte", ",", "headerSize", ")", ")", ",", "controlErr", ":", "make", "(", "chan", "error", ",", "1", ")", ",", "sendHdr", ":", "header", "(", "make", "(", "[", "]", "byte", ",", "headerSize", ")", ")", ",", "sendErr", ":", "make", "(", "chan", "error", ",", "1", ")", ",", "recvWindow", ":", "initialStreamWindow", ",", "sendWindow", ":", "initialStreamWindow", ",", "recvNotifyCh", ":", "make", "(", "chan", "struct", "{", "}", ",", "1", ")", ",", "sendNotifyCh", ":", "make", "(", "chan", "struct", "{", "}", ",", "1", ")", ",", "}", "\n", "s", ".", "readDeadline", ".", "Store", "(", "time", ".", "Time", "{", "}", ")", "\n", "s", ".", "writeDeadline", ".", "Store", "(", "time", ".", "Time", "{", "}", ")", "\n", "return", "s", "\n", "}" ]
// newStream is used to construct a new stream within // a given session for an ID
[ "newStream", "is", "used", "to", "construct", "a", "new", "stream", "within", "a", "given", "session", "for", "an", "ID" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L56-L73
train
hashicorp/yamux
stream.go
Read
func (s *Stream) Read(b []byte) (n int, err error) { defer asyncNotify(s.recvNotifyCh) START: s.stateLock.Lock() switch s.state { case streamLocalClose: fallthrough case streamRemoteClose: fallthrough case streamClosed: s.recvLock.Lock() if s.recvBuf == nil || s.recvBuf.Len() == 0 { s.recvLock.Unlock() s.stateLock.Unlock() return 0, io.EOF } s.recvLock.Unlock() case streamReset: s.stateLock.Unlock() return 0, ErrConnectionReset } s.stateLock.Unlock() // If there is no data available, block s.recvLock.Lock() if s.recvBuf == nil || s.recvBuf.Len() == 0 { s.recvLock.Unlock() goto WAIT } // Read any bytes n, _ = s.recvBuf.Read(b) s.recvLock.Unlock() // Send a window update potentially err = s.sendWindowUpdate() return n, err WAIT: var timeout <-chan time.Time var timer *time.Timer readDeadline := s.readDeadline.Load().(time.Time) if !readDeadline.IsZero() { delay := readDeadline.Sub(time.Now()) timer = time.NewTimer(delay) timeout = timer.C } select { case <-s.recvNotifyCh: if timer != nil { timer.Stop() } goto START case <-timeout: return 0, ErrTimeout } }
go
func (s *Stream) Read(b []byte) (n int, err error) { defer asyncNotify(s.recvNotifyCh) START: s.stateLock.Lock() switch s.state { case streamLocalClose: fallthrough case streamRemoteClose: fallthrough case streamClosed: s.recvLock.Lock() if s.recvBuf == nil || s.recvBuf.Len() == 0 { s.recvLock.Unlock() s.stateLock.Unlock() return 0, io.EOF } s.recvLock.Unlock() case streamReset: s.stateLock.Unlock() return 0, ErrConnectionReset } s.stateLock.Unlock() // If there is no data available, block s.recvLock.Lock() if s.recvBuf == nil || s.recvBuf.Len() == 0 { s.recvLock.Unlock() goto WAIT } // Read any bytes n, _ = s.recvBuf.Read(b) s.recvLock.Unlock() // Send a window update potentially err = s.sendWindowUpdate() return n, err WAIT: var timeout <-chan time.Time var timer *time.Timer readDeadline := s.readDeadline.Load().(time.Time) if !readDeadline.IsZero() { delay := readDeadline.Sub(time.Now()) timer = time.NewTimer(delay) timeout = timer.C } select { case <-s.recvNotifyCh: if timer != nil { timer.Stop() } goto START case <-timeout: return 0, ErrTimeout } }
[ "func", "(", "s", "*", "Stream", ")", "Read", "(", "b", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "defer", "asyncNotify", "(", "s", ".", "recvNotifyCh", ")", "\n", "START", ":", "s", ".", "stateLock", ".", "Lock", "(", ")", "\n", "switch", "s", ".", "state", "{", "case", "streamLocalClose", ":", "fallthrough", "\n", "case", "streamRemoteClose", ":", "fallthrough", "\n", "case", "streamClosed", ":", "s", ".", "recvLock", ".", "Lock", "(", ")", "\n", "if", "s", ".", "recvBuf", "==", "nil", "||", "s", ".", "recvBuf", ".", "Len", "(", ")", "==", "0", "{", "s", ".", "recvLock", ".", "Unlock", "(", ")", "\n", "s", ".", "stateLock", ".", "Unlock", "(", ")", "\n", "return", "0", ",", "io", ".", "EOF", "\n", "}", "\n", "s", ".", "recvLock", ".", "Unlock", "(", ")", "\n", "case", "streamReset", ":", "s", ".", "stateLock", ".", "Unlock", "(", ")", "\n", "return", "0", ",", "ErrConnectionReset", "\n", "}", "\n", "s", ".", "stateLock", ".", "Unlock", "(", ")", "\n", "s", ".", "recvLock", ".", "Lock", "(", ")", "\n", "if", "s", ".", "recvBuf", "==", "nil", "||", "s", ".", "recvBuf", ".", "Len", "(", ")", "==", "0", "{", "s", ".", "recvLock", ".", "Unlock", "(", ")", "\n", "goto", "WAIT", "\n", "}", "\n", "n", ",", "_", "=", "s", ".", "recvBuf", ".", "Read", "(", "b", ")", "\n", "s", ".", "recvLock", ".", "Unlock", "(", ")", "\n", "err", "=", "s", ".", "sendWindowUpdate", "(", ")", "\n", "return", "n", ",", "err", "\n", "WAIT", ":", "var", "timeout", "<-", "chan", "time", ".", "Time", "\n", "var", "timer", "*", "time", ".", "Timer", "\n", "readDeadline", ":=", "s", ".", "readDeadline", ".", "Load", "(", ")", ".", "(", "time", ".", "Time", ")", "\n", "if", "!", "readDeadline", ".", "IsZero", "(", ")", "{", "delay", ":=", "readDeadline", ".", "Sub", "(", "time", ".", "Now", "(", ")", ")", "\n", "timer", "=", "time", ".", "NewTimer", "(", "delay", ")", "\n", "timeout", "=", "timer", ".", "C", "\n", "}", "\n", "select", "{", "case", "<-", "s", ".", "recvNotifyCh", ":", "if", "timer", "!=", "nil", "{", "timer", ".", "Stop", "(", ")", "\n", "}", "\n", "goto", "START", "\n", "case", "<-", "timeout", ":", "return", "0", ",", "ErrTimeout", "\n", "}", "\n", "}" ]
// Read is used to read from the stream
[ "Read", "is", "used", "to", "read", "from", "the", "stream" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L86-L142
train
hashicorp/yamux
stream.go
Write
func (s *Stream) Write(b []byte) (n int, err error) { s.sendLock.Lock() defer s.sendLock.Unlock() total := 0 for total < len(b) { n, err := s.write(b[total:]) total += n if err != nil { return total, err } } return total, nil }
go
func (s *Stream) Write(b []byte) (n int, err error) { s.sendLock.Lock() defer s.sendLock.Unlock() total := 0 for total < len(b) { n, err := s.write(b[total:]) total += n if err != nil { return total, err } } return total, nil }
[ "func", "(", "s", "*", "Stream", ")", "Write", "(", "b", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "s", ".", "sendLock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "sendLock", ".", "Unlock", "(", ")", "\n", "total", ":=", "0", "\n", "for", "total", "<", "len", "(", "b", ")", "{", "n", ",", "err", ":=", "s", ".", "write", "(", "b", "[", "total", ":", "]", ")", "\n", "total", "+=", "n", "\n", "if", "err", "!=", "nil", "{", "return", "total", ",", "err", "\n", "}", "\n", "}", "\n", "return", "total", ",", "nil", "\n", "}" ]
// Write is used to write to the stream
[ "Write", "is", "used", "to", "write", "to", "the", "stream" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L145-L157
train
hashicorp/yamux
stream.go
write
func (s *Stream) write(b []byte) (n int, err error) { var flags uint16 var max uint32 var body io.Reader START: s.stateLock.Lock() switch s.state { case streamLocalClose: fallthrough case streamClosed: s.stateLock.Unlock() return 0, ErrStreamClosed case streamReset: s.stateLock.Unlock() return 0, ErrConnectionReset } s.stateLock.Unlock() // If there is no data available, block window := atomic.LoadUint32(&s.sendWindow) if window == 0 { goto WAIT } // Determine the flags if any flags = s.sendFlags() // Send up to our send window max = min(window, uint32(len(b))) body = bytes.NewReader(b[:max]) // Send the header s.sendHdr.encode(typeData, flags, s.id, max) if err = s.session.waitForSendErr(s.sendHdr, body, s.sendErr); err != nil { return 0, err } // Reduce our send window atomic.AddUint32(&s.sendWindow, ^uint32(max-1)) // Unlock return int(max), err WAIT: var timeout <-chan time.Time writeDeadline := s.writeDeadline.Load().(time.Time) if !writeDeadline.IsZero() { delay := writeDeadline.Sub(time.Now()) timeout = time.After(delay) } select { case <-s.sendNotifyCh: goto START case <-timeout: return 0, ErrTimeout } return 0, nil }
go
func (s *Stream) write(b []byte) (n int, err error) { var flags uint16 var max uint32 var body io.Reader START: s.stateLock.Lock() switch s.state { case streamLocalClose: fallthrough case streamClosed: s.stateLock.Unlock() return 0, ErrStreamClosed case streamReset: s.stateLock.Unlock() return 0, ErrConnectionReset } s.stateLock.Unlock() // If there is no data available, block window := atomic.LoadUint32(&s.sendWindow) if window == 0 { goto WAIT } // Determine the flags if any flags = s.sendFlags() // Send up to our send window max = min(window, uint32(len(b))) body = bytes.NewReader(b[:max]) // Send the header s.sendHdr.encode(typeData, flags, s.id, max) if err = s.session.waitForSendErr(s.sendHdr, body, s.sendErr); err != nil { return 0, err } // Reduce our send window atomic.AddUint32(&s.sendWindow, ^uint32(max-1)) // Unlock return int(max), err WAIT: var timeout <-chan time.Time writeDeadline := s.writeDeadline.Load().(time.Time) if !writeDeadline.IsZero() { delay := writeDeadline.Sub(time.Now()) timeout = time.After(delay) } select { case <-s.sendNotifyCh: goto START case <-timeout: return 0, ErrTimeout } return 0, nil }
[ "func", "(", "s", "*", "Stream", ")", "write", "(", "b", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "var", "flags", "uint16", "\n", "var", "max", "uint32", "\n", "var", "body", "io", ".", "Reader", "\n", "START", ":", "s", ".", "stateLock", ".", "Lock", "(", ")", "\n", "switch", "s", ".", "state", "{", "case", "streamLocalClose", ":", "fallthrough", "\n", "case", "streamClosed", ":", "s", ".", "stateLock", ".", "Unlock", "(", ")", "\n", "return", "0", ",", "ErrStreamClosed", "\n", "case", "streamReset", ":", "s", ".", "stateLock", ".", "Unlock", "(", ")", "\n", "return", "0", ",", "ErrConnectionReset", "\n", "}", "\n", "s", ".", "stateLock", ".", "Unlock", "(", ")", "\n", "window", ":=", "atomic", ".", "LoadUint32", "(", "&", "s", ".", "sendWindow", ")", "\n", "if", "window", "==", "0", "{", "goto", "WAIT", "\n", "}", "\n", "flags", "=", "s", ".", "sendFlags", "(", ")", "\n", "max", "=", "min", "(", "window", ",", "uint32", "(", "len", "(", "b", ")", ")", ")", "\n", "body", "=", "bytes", ".", "NewReader", "(", "b", "[", ":", "max", "]", ")", "\n", "s", ".", "sendHdr", ".", "encode", "(", "typeData", ",", "flags", ",", "s", ".", "id", ",", "max", ")", "\n", "if", "err", "=", "s", ".", "session", ".", "waitForSendErr", "(", "s", ".", "sendHdr", ",", "body", ",", "s", ".", "sendErr", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "atomic", ".", "AddUint32", "(", "&", "s", ".", "sendWindow", ",", "^", "uint32", "(", "max", "-", "1", ")", ")", "\n", "return", "int", "(", "max", ")", ",", "err", "\n", "WAIT", ":", "var", "timeout", "<-", "chan", "time", ".", "Time", "\n", "writeDeadline", ":=", "s", ".", "writeDeadline", ".", "Load", "(", ")", ".", "(", "time", ".", "Time", ")", "\n", "if", "!", "writeDeadline", ".", "IsZero", "(", ")", "{", "delay", ":=", "writeDeadline", ".", "Sub", "(", "time", ".", "Now", "(", ")", ")", "\n", "timeout", "=", "time", ".", "After", "(", "delay", ")", "\n", "}", "\n", "select", "{", "case", "<-", "s", ".", "sendNotifyCh", ":", "goto", "START", "\n", "case", "<-", "timeout", ":", "return", "0", ",", "ErrTimeout", "\n", "}", "\n", "return", "0", ",", "nil", "\n", "}" ]
// write is used to write to the stream, may return on // a short write.
[ "write", "is", "used", "to", "write", "to", "the", "stream", "may", "return", "on", "a", "short", "write", "." ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L161-L218
train
hashicorp/yamux
stream.go
sendFlags
func (s *Stream) sendFlags() uint16 { s.stateLock.Lock() defer s.stateLock.Unlock() var flags uint16 switch s.state { case streamInit: flags |= flagSYN s.state = streamSYNSent case streamSYNReceived: flags |= flagACK s.state = streamEstablished } return flags }
go
func (s *Stream) sendFlags() uint16 { s.stateLock.Lock() defer s.stateLock.Unlock() var flags uint16 switch s.state { case streamInit: flags |= flagSYN s.state = streamSYNSent case streamSYNReceived: flags |= flagACK s.state = streamEstablished } return flags }
[ "func", "(", "s", "*", "Stream", ")", "sendFlags", "(", ")", "uint16", "{", "s", ".", "stateLock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "stateLock", ".", "Unlock", "(", ")", "\n", "var", "flags", "uint16", "\n", "switch", "s", ".", "state", "{", "case", "streamInit", ":", "flags", "|=", "flagSYN", "\n", "s", ".", "state", "=", "streamSYNSent", "\n", "case", "streamSYNReceived", ":", "flags", "|=", "flagACK", "\n", "s", ".", "state", "=", "streamEstablished", "\n", "}", "\n", "return", "flags", "\n", "}" ]
// sendFlags determines any flags that are appropriate // based on the current stream state
[ "sendFlags", "determines", "any", "flags", "that", "are", "appropriate", "based", "on", "the", "current", "stream", "state" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L222-L235
train
hashicorp/yamux
stream.go
sendWindowUpdate
func (s *Stream) sendWindowUpdate() error { s.controlHdrLock.Lock() defer s.controlHdrLock.Unlock() // Determine the delta update max := s.session.config.MaxStreamWindowSize var bufLen uint32 s.recvLock.Lock() if s.recvBuf != nil { bufLen = uint32(s.recvBuf.Len()) } delta := (max - bufLen) - s.recvWindow // Determine the flags if any flags := s.sendFlags() // Check if we can omit the update if delta < (max/2) && flags == 0 { s.recvLock.Unlock() return nil } // Update our window s.recvWindow += delta s.recvLock.Unlock() // Send the header s.controlHdr.encode(typeWindowUpdate, flags, s.id, delta) if err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil { return err } return nil }
go
func (s *Stream) sendWindowUpdate() error { s.controlHdrLock.Lock() defer s.controlHdrLock.Unlock() // Determine the delta update max := s.session.config.MaxStreamWindowSize var bufLen uint32 s.recvLock.Lock() if s.recvBuf != nil { bufLen = uint32(s.recvBuf.Len()) } delta := (max - bufLen) - s.recvWindow // Determine the flags if any flags := s.sendFlags() // Check if we can omit the update if delta < (max/2) && flags == 0 { s.recvLock.Unlock() return nil } // Update our window s.recvWindow += delta s.recvLock.Unlock() // Send the header s.controlHdr.encode(typeWindowUpdate, flags, s.id, delta) if err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil { return err } return nil }
[ "func", "(", "s", "*", "Stream", ")", "sendWindowUpdate", "(", ")", "error", "{", "s", ".", "controlHdrLock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "controlHdrLock", ".", "Unlock", "(", ")", "\n", "max", ":=", "s", ".", "session", ".", "config", ".", "MaxStreamWindowSize", "\n", "var", "bufLen", "uint32", "\n", "s", ".", "recvLock", ".", "Lock", "(", ")", "\n", "if", "s", ".", "recvBuf", "!=", "nil", "{", "bufLen", "=", "uint32", "(", "s", ".", "recvBuf", ".", "Len", "(", ")", ")", "\n", "}", "\n", "delta", ":=", "(", "max", "-", "bufLen", ")", "-", "s", ".", "recvWindow", "\n", "flags", ":=", "s", ".", "sendFlags", "(", ")", "\n", "if", "delta", "<", "(", "max", "/", "2", ")", "&&", "flags", "==", "0", "{", "s", ".", "recvLock", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}", "\n", "s", ".", "recvWindow", "+=", "delta", "\n", "s", ".", "recvLock", ".", "Unlock", "(", ")", "\n", "s", ".", "controlHdr", ".", "encode", "(", "typeWindowUpdate", ",", "flags", ",", "s", ".", "id", ",", "delta", ")", "\n", "if", "err", ":=", "s", ".", "session", ".", "waitForSendErr", "(", "s", ".", "controlHdr", ",", "nil", ",", "s", ".", "controlErr", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// sendWindowUpdate potentially sends a window update enabling // further writes to take place. Must be invoked with the lock.
[ "sendWindowUpdate", "potentially", "sends", "a", "window", "update", "enabling", "further", "writes", "to", "take", "place", ".", "Must", "be", "invoked", "with", "the", "lock", "." ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L239-L271
train
hashicorp/yamux
stream.go
sendClose
func (s *Stream) sendClose() error { s.controlHdrLock.Lock() defer s.controlHdrLock.Unlock() flags := s.sendFlags() flags |= flagFIN s.controlHdr.encode(typeWindowUpdate, flags, s.id, 0) if err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil { return err } return nil }
go
func (s *Stream) sendClose() error { s.controlHdrLock.Lock() defer s.controlHdrLock.Unlock() flags := s.sendFlags() flags |= flagFIN s.controlHdr.encode(typeWindowUpdate, flags, s.id, 0) if err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil { return err } return nil }
[ "func", "(", "s", "*", "Stream", ")", "sendClose", "(", ")", "error", "{", "s", ".", "controlHdrLock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "controlHdrLock", ".", "Unlock", "(", ")", "\n", "flags", ":=", "s", ".", "sendFlags", "(", ")", "\n", "flags", "|=", "flagFIN", "\n", "s", ".", "controlHdr", ".", "encode", "(", "typeWindowUpdate", ",", "flags", ",", "s", ".", "id", ",", "0", ")", "\n", "if", "err", ":=", "s", ".", "session", ".", "waitForSendErr", "(", "s", ".", "controlHdr", ",", "nil", ",", "s", ".", "controlErr", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// sendClose is used to send a FIN
[ "sendClose", "is", "used", "to", "send", "a", "FIN" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L274-L285
train
hashicorp/yamux
stream.go
Close
func (s *Stream) Close() error { closeStream := false s.stateLock.Lock() switch s.state { // Opened means we need to signal a close case streamSYNSent: fallthrough case streamSYNReceived: fallthrough case streamEstablished: s.state = streamLocalClose goto SEND_CLOSE case streamLocalClose: case streamRemoteClose: s.state = streamClosed closeStream = true goto SEND_CLOSE case streamClosed: case streamReset: default: panic("unhandled state") } s.stateLock.Unlock() return nil SEND_CLOSE: s.stateLock.Unlock() s.sendClose() s.notifyWaiting() if closeStream { s.session.closeStream(s.id) } return nil }
go
func (s *Stream) Close() error { closeStream := false s.stateLock.Lock() switch s.state { // Opened means we need to signal a close case streamSYNSent: fallthrough case streamSYNReceived: fallthrough case streamEstablished: s.state = streamLocalClose goto SEND_CLOSE case streamLocalClose: case streamRemoteClose: s.state = streamClosed closeStream = true goto SEND_CLOSE case streamClosed: case streamReset: default: panic("unhandled state") } s.stateLock.Unlock() return nil SEND_CLOSE: s.stateLock.Unlock() s.sendClose() s.notifyWaiting() if closeStream { s.session.closeStream(s.id) } return nil }
[ "func", "(", "s", "*", "Stream", ")", "Close", "(", ")", "error", "{", "closeStream", ":=", "false", "\n", "s", ".", "stateLock", ".", "Lock", "(", ")", "\n", "switch", "s", ".", "state", "{", "case", "streamSYNSent", ":", "fallthrough", "\n", "case", "streamSYNReceived", ":", "fallthrough", "\n", "case", "streamEstablished", ":", "s", ".", "state", "=", "streamLocalClose", "\n", "goto", "SEND_CLOSE", "\n", "case", "streamLocalClose", ":", "case", "streamRemoteClose", ":", "s", ".", "state", "=", "streamClosed", "\n", "closeStream", "=", "true", "\n", "goto", "SEND_CLOSE", "\n", "case", "streamClosed", ":", "case", "streamReset", ":", "default", ":", "panic", "(", "\"unhandled state\"", ")", "\n", "}", "\n", "s", ".", "stateLock", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "SEND_CLOSE", ":", "s", ".", "stateLock", ".", "Unlock", "(", ")", "\n", "s", ".", "sendClose", "(", ")", "\n", "s", ".", "notifyWaiting", "(", ")", "\n", "if", "closeStream", "{", "s", ".", "session", ".", "closeStream", "(", "s", ".", "id", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close is used to close the stream
[ "Close", "is", "used", "to", "close", "the", "stream" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L288-L322
train
hashicorp/yamux
stream.go
forceClose
func (s *Stream) forceClose() { s.stateLock.Lock() s.state = streamClosed s.stateLock.Unlock() s.notifyWaiting() }
go
func (s *Stream) forceClose() { s.stateLock.Lock() s.state = streamClosed s.stateLock.Unlock() s.notifyWaiting() }
[ "func", "(", "s", "*", "Stream", ")", "forceClose", "(", ")", "{", "s", ".", "stateLock", ".", "Lock", "(", ")", "\n", "s", ".", "state", "=", "streamClosed", "\n", "s", ".", "stateLock", ".", "Unlock", "(", ")", "\n", "s", ".", "notifyWaiting", "(", ")", "\n", "}" ]
// forceClose is used for when the session is exiting
[ "forceClose", "is", "used", "for", "when", "the", "session", "is", "exiting" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L325-L330
train
hashicorp/yamux
stream.go
processFlags
func (s *Stream) processFlags(flags uint16) error { // Close the stream without holding the state lock closeStream := false defer func() { if closeStream { s.session.closeStream(s.id) } }() s.stateLock.Lock() defer s.stateLock.Unlock() if flags&flagACK == flagACK { if s.state == streamSYNSent { s.state = streamEstablished } s.session.establishStream(s.id) } if flags&flagFIN == flagFIN { switch s.state { case streamSYNSent: fallthrough case streamSYNReceived: fallthrough case streamEstablished: s.state = streamRemoteClose s.notifyWaiting() case streamLocalClose: s.state = streamClosed closeStream = true s.notifyWaiting() default: s.session.logger.Printf("[ERR] yamux: unexpected FIN flag in state %d", s.state) return ErrUnexpectedFlag } } if flags&flagRST == flagRST { s.state = streamReset closeStream = true s.notifyWaiting() } return nil }
go
func (s *Stream) processFlags(flags uint16) error { // Close the stream without holding the state lock closeStream := false defer func() { if closeStream { s.session.closeStream(s.id) } }() s.stateLock.Lock() defer s.stateLock.Unlock() if flags&flagACK == flagACK { if s.state == streamSYNSent { s.state = streamEstablished } s.session.establishStream(s.id) } if flags&flagFIN == flagFIN { switch s.state { case streamSYNSent: fallthrough case streamSYNReceived: fallthrough case streamEstablished: s.state = streamRemoteClose s.notifyWaiting() case streamLocalClose: s.state = streamClosed closeStream = true s.notifyWaiting() default: s.session.logger.Printf("[ERR] yamux: unexpected FIN flag in state %d", s.state) return ErrUnexpectedFlag } } if flags&flagRST == flagRST { s.state = streamReset closeStream = true s.notifyWaiting() } return nil }
[ "func", "(", "s", "*", "Stream", ")", "processFlags", "(", "flags", "uint16", ")", "error", "{", "closeStream", ":=", "false", "\n", "defer", "func", "(", ")", "{", "if", "closeStream", "{", "s", ".", "session", ".", "closeStream", "(", "s", ".", "id", ")", "\n", "}", "\n", "}", "(", ")", "\n", "s", ".", "stateLock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "stateLock", ".", "Unlock", "(", ")", "\n", "if", "flags", "&", "flagACK", "==", "flagACK", "{", "if", "s", ".", "state", "==", "streamSYNSent", "{", "s", ".", "state", "=", "streamEstablished", "\n", "}", "\n", "s", ".", "session", ".", "establishStream", "(", "s", ".", "id", ")", "\n", "}", "\n", "if", "flags", "&", "flagFIN", "==", "flagFIN", "{", "switch", "s", ".", "state", "{", "case", "streamSYNSent", ":", "fallthrough", "\n", "case", "streamSYNReceived", ":", "fallthrough", "\n", "case", "streamEstablished", ":", "s", ".", "state", "=", "streamRemoteClose", "\n", "s", ".", "notifyWaiting", "(", ")", "\n", "case", "streamLocalClose", ":", "s", ".", "state", "=", "streamClosed", "\n", "closeStream", "=", "true", "\n", "s", ".", "notifyWaiting", "(", ")", "\n", "default", ":", "s", ".", "session", ".", "logger", ".", "Printf", "(", "\"[ERR] yamux: unexpected FIN flag in state %d\"", ",", "s", ".", "state", ")", "\n", "return", "ErrUnexpectedFlag", "\n", "}", "\n", "}", "\n", "if", "flags", "&", "flagRST", "==", "flagRST", "{", "s", ".", "state", "=", "streamReset", "\n", "closeStream", "=", "true", "\n", "s", ".", "notifyWaiting", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// processFlags is used to update the state of the stream // based on set flags, if any. Lock must be held
[ "processFlags", "is", "used", "to", "update", "the", "state", "of", "the", "stream", "based", "on", "set", "flags", "if", "any", ".", "Lock", "must", "be", "held" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L334-L375
train
hashicorp/yamux
stream.go
incrSendWindow
func (s *Stream) incrSendWindow(hdr header, flags uint16) error { if err := s.processFlags(flags); err != nil { return err } // Increase window, unblock a sender atomic.AddUint32(&s.sendWindow, hdr.Length()) asyncNotify(s.sendNotifyCh) return nil }
go
func (s *Stream) incrSendWindow(hdr header, flags uint16) error { if err := s.processFlags(flags); err != nil { return err } // Increase window, unblock a sender atomic.AddUint32(&s.sendWindow, hdr.Length()) asyncNotify(s.sendNotifyCh) return nil }
[ "func", "(", "s", "*", "Stream", ")", "incrSendWindow", "(", "hdr", "header", ",", "flags", "uint16", ")", "error", "{", "if", "err", ":=", "s", ".", "processFlags", "(", "flags", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "atomic", ".", "AddUint32", "(", "&", "s", ".", "sendWindow", ",", "hdr", ".", "Length", "(", ")", ")", "\n", "asyncNotify", "(", "s", ".", "sendNotifyCh", ")", "\n", "return", "nil", "\n", "}" ]
// incrSendWindow updates the size of our send window
[ "incrSendWindow", "updates", "the", "size", "of", "our", "send", "window" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L384-L393
train
hashicorp/yamux
stream.go
readData
func (s *Stream) readData(hdr header, flags uint16, conn io.Reader) error { if err := s.processFlags(flags); err != nil { return err } // Check that our recv window is not exceeded length := hdr.Length() if length == 0 { return nil } // Wrap in a limited reader conn = &io.LimitedReader{R: conn, N: int64(length)} // Copy into buffer s.recvLock.Lock() if length > s.recvWindow { s.session.logger.Printf("[ERR] yamux: receive window exceeded (stream: %d, remain: %d, recv: %d)", s.id, s.recvWindow, length) return ErrRecvWindowExceeded } if s.recvBuf == nil { // Allocate the receive buffer just-in-time to fit the full data frame. // This way we can read in the whole packet without further allocations. s.recvBuf = bytes.NewBuffer(make([]byte, 0, length)) } if _, err := io.Copy(s.recvBuf, conn); err != nil { s.session.logger.Printf("[ERR] yamux: Failed to read stream data: %v", err) s.recvLock.Unlock() return err } // Decrement the receive window s.recvWindow -= length s.recvLock.Unlock() // Unblock any readers asyncNotify(s.recvNotifyCh) return nil }
go
func (s *Stream) readData(hdr header, flags uint16, conn io.Reader) error { if err := s.processFlags(flags); err != nil { return err } // Check that our recv window is not exceeded length := hdr.Length() if length == 0 { return nil } // Wrap in a limited reader conn = &io.LimitedReader{R: conn, N: int64(length)} // Copy into buffer s.recvLock.Lock() if length > s.recvWindow { s.session.logger.Printf("[ERR] yamux: receive window exceeded (stream: %d, remain: %d, recv: %d)", s.id, s.recvWindow, length) return ErrRecvWindowExceeded } if s.recvBuf == nil { // Allocate the receive buffer just-in-time to fit the full data frame. // This way we can read in the whole packet without further allocations. s.recvBuf = bytes.NewBuffer(make([]byte, 0, length)) } if _, err := io.Copy(s.recvBuf, conn); err != nil { s.session.logger.Printf("[ERR] yamux: Failed to read stream data: %v", err) s.recvLock.Unlock() return err } // Decrement the receive window s.recvWindow -= length s.recvLock.Unlock() // Unblock any readers asyncNotify(s.recvNotifyCh) return nil }
[ "func", "(", "s", "*", "Stream", ")", "readData", "(", "hdr", "header", ",", "flags", "uint16", ",", "conn", "io", ".", "Reader", ")", "error", "{", "if", "err", ":=", "s", ".", "processFlags", "(", "flags", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "length", ":=", "hdr", ".", "Length", "(", ")", "\n", "if", "length", "==", "0", "{", "return", "nil", "\n", "}", "\n", "conn", "=", "&", "io", ".", "LimitedReader", "{", "R", ":", "conn", ",", "N", ":", "int64", "(", "length", ")", "}", "\n", "s", ".", "recvLock", ".", "Lock", "(", ")", "\n", "if", "length", ">", "s", ".", "recvWindow", "{", "s", ".", "session", ".", "logger", ".", "Printf", "(", "\"[ERR] yamux: receive window exceeded (stream: %d, remain: %d, recv: %d)\"", ",", "s", ".", "id", ",", "s", ".", "recvWindow", ",", "length", ")", "\n", "return", "ErrRecvWindowExceeded", "\n", "}", "\n", "if", "s", ".", "recvBuf", "==", "nil", "{", "s", ".", "recvBuf", "=", "bytes", ".", "NewBuffer", "(", "make", "(", "[", "]", "byte", ",", "0", ",", "length", ")", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "s", ".", "recvBuf", ",", "conn", ")", ";", "err", "!=", "nil", "{", "s", ".", "session", ".", "logger", ".", "Printf", "(", "\"[ERR] yamux: Failed to read stream data: %v\"", ",", "err", ")", "\n", "s", ".", "recvLock", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}", "\n", "s", ".", "recvWindow", "-=", "length", "\n", "s", ".", "recvLock", ".", "Unlock", "(", ")", "\n", "asyncNotify", "(", "s", ".", "recvNotifyCh", ")", "\n", "return", "nil", "\n", "}" ]
// readData is used to handle a data frame
[ "readData", "is", "used", "to", "handle", "a", "data", "frame" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L396-L436
train
hashicorp/yamux
stream.go
SetDeadline
func (s *Stream) SetDeadline(t time.Time) error { if err := s.SetReadDeadline(t); err != nil { return err } if err := s.SetWriteDeadline(t); err != nil { return err } return nil }
go
func (s *Stream) SetDeadline(t time.Time) error { if err := s.SetReadDeadline(t); err != nil { return err } if err := s.SetWriteDeadline(t); err != nil { return err } return nil }
[ "func", "(", "s", "*", "Stream", ")", "SetDeadline", "(", "t", "time", ".", "Time", ")", "error", "{", "if", "err", ":=", "s", ".", "SetReadDeadline", "(", "t", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "s", ".", "SetWriteDeadline", "(", "t", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetDeadline sets the read and write deadlines
[ "SetDeadline", "sets", "the", "read", "and", "write", "deadlines" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L439-L447
train
hashicorp/yamux
stream.go
SetWriteDeadline
func (s *Stream) SetWriteDeadline(t time.Time) error { s.writeDeadline.Store(t) return nil }
go
func (s *Stream) SetWriteDeadline(t time.Time) error { s.writeDeadline.Store(t) return nil }
[ "func", "(", "s", "*", "Stream", ")", "SetWriteDeadline", "(", "t", "time", ".", "Time", ")", "error", "{", "s", ".", "writeDeadline", ".", "Store", "(", "t", ")", "\n", "return", "nil", "\n", "}" ]
// SetWriteDeadline sets the deadline for future Write calls
[ "SetWriteDeadline", "sets", "the", "deadline", "for", "future", "Write", "calls" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L456-L459
train
hashicorp/yamux
stream.go
Shrink
func (s *Stream) Shrink() { s.recvLock.Lock() if s.recvBuf != nil && s.recvBuf.Len() == 0 { s.recvBuf = nil } s.recvLock.Unlock() }
go
func (s *Stream) Shrink() { s.recvLock.Lock() if s.recvBuf != nil && s.recvBuf.Len() == 0 { s.recvBuf = nil } s.recvLock.Unlock() }
[ "func", "(", "s", "*", "Stream", ")", "Shrink", "(", ")", "{", "s", ".", "recvLock", ".", "Lock", "(", ")", "\n", "if", "s", ".", "recvBuf", "!=", "nil", "&&", "s", ".", "recvBuf", ".", "Len", "(", ")", "==", "0", "{", "s", ".", "recvBuf", "=", "nil", "\n", "}", "\n", "s", ".", "recvLock", ".", "Unlock", "(", ")", "\n", "}" ]
// Shrink is used to compact the amount of buffers utilized // This is useful when using Yamux in a connection pool to reduce // the idle memory utilization.
[ "Shrink", "is", "used", "to", "compact", "the", "amount", "of", "buffers", "utilized", "This", "is", "useful", "when", "using", "Yamux", "in", "a", "connection", "pool", "to", "reduce", "the", "idle", "memory", "utilization", "." ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L464-L470
train
hashicorp/yamux
mux.go
Server
func Server(conn io.ReadWriteCloser, config *Config) (*Session, error) { if config == nil { config = DefaultConfig() } if err := VerifyConfig(config); err != nil { return nil, err } return newSession(config, conn, false), nil }
go
func Server(conn io.ReadWriteCloser, config *Config) (*Session, error) { if config == nil { config = DefaultConfig() } if err := VerifyConfig(config); err != nil { return nil, err } return newSession(config, conn, false), nil }
[ "func", "Server", "(", "conn", "io", ".", "ReadWriteCloser", ",", "config", "*", "Config", ")", "(", "*", "Session", ",", "error", ")", "{", "if", "config", "==", "nil", "{", "config", "=", "DefaultConfig", "(", ")", "\n", "}", "\n", "if", "err", ":=", "VerifyConfig", "(", "config", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "newSession", "(", "config", ",", "conn", ",", "false", ")", ",", "nil", "\n", "}" ]
// Server is used to initialize a new server-side connection. // There must be at most one server-side connection. If a nil config is // provided, the DefaultConfiguration will be used.
[ "Server", "is", "used", "to", "initialize", "a", "new", "server", "-", "side", "connection", ".", "There", "must", "be", "at", "most", "one", "server", "-", "side", "connection", ".", "If", "a", "nil", "config", "is", "provided", "the", "DefaultConfiguration", "will", "be", "used", "." ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/mux.go#L77-L85
train
hashicorp/yamux
mux.go
Client
func Client(conn io.ReadWriteCloser, config *Config) (*Session, error) { if config == nil { config = DefaultConfig() } if err := VerifyConfig(config); err != nil { return nil, err } return newSession(config, conn, true), nil }
go
func Client(conn io.ReadWriteCloser, config *Config) (*Session, error) { if config == nil { config = DefaultConfig() } if err := VerifyConfig(config); err != nil { return nil, err } return newSession(config, conn, true), nil }
[ "func", "Client", "(", "conn", "io", ".", "ReadWriteCloser", ",", "config", "*", "Config", ")", "(", "*", "Session", ",", "error", ")", "{", "if", "config", "==", "nil", "{", "config", "=", "DefaultConfig", "(", ")", "\n", "}", "\n", "if", "err", ":=", "VerifyConfig", "(", "config", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "newSession", "(", "config", ",", "conn", ",", "true", ")", ",", "nil", "\n", "}" ]
// Client is used to initialize a new client-side connection. // There must be at most one client-side connection.
[ "Client", "is", "used", "to", "initialize", "a", "new", "client", "-", "side", "connection", ".", "There", "must", "be", "at", "most", "one", "client", "-", "side", "connection", "." ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/mux.go#L89-L98
train
hashicorp/yamux
session.go
newSession
func newSession(config *Config, conn io.ReadWriteCloser, client bool) *Session { logger := config.Logger if logger == nil { logger = log.New(config.LogOutput, "", log.LstdFlags) } s := &Session{ config: config, logger: logger, conn: conn, bufRead: bufio.NewReader(conn), pings: make(map[uint32]chan struct{}), streams: make(map[uint32]*Stream), inflight: make(map[uint32]struct{}), synCh: make(chan struct{}, config.AcceptBacklog), acceptCh: make(chan *Stream, config.AcceptBacklog), sendCh: make(chan sendReady, 64), recvDoneCh: make(chan struct{}), shutdownCh: make(chan struct{}), } if client { s.nextStreamID = 1 } else { s.nextStreamID = 2 } go s.recv() go s.send() if config.EnableKeepAlive { go s.keepalive() } return s }
go
func newSession(config *Config, conn io.ReadWriteCloser, client bool) *Session { logger := config.Logger if logger == nil { logger = log.New(config.LogOutput, "", log.LstdFlags) } s := &Session{ config: config, logger: logger, conn: conn, bufRead: bufio.NewReader(conn), pings: make(map[uint32]chan struct{}), streams: make(map[uint32]*Stream), inflight: make(map[uint32]struct{}), synCh: make(chan struct{}, config.AcceptBacklog), acceptCh: make(chan *Stream, config.AcceptBacklog), sendCh: make(chan sendReady, 64), recvDoneCh: make(chan struct{}), shutdownCh: make(chan struct{}), } if client { s.nextStreamID = 1 } else { s.nextStreamID = 2 } go s.recv() go s.send() if config.EnableKeepAlive { go s.keepalive() } return s }
[ "func", "newSession", "(", "config", "*", "Config", ",", "conn", "io", ".", "ReadWriteCloser", ",", "client", "bool", ")", "*", "Session", "{", "logger", ":=", "config", ".", "Logger", "\n", "if", "logger", "==", "nil", "{", "logger", "=", "log", ".", "New", "(", "config", ".", "LogOutput", ",", "\"\"", ",", "log", ".", "LstdFlags", ")", "\n", "}", "\n", "s", ":=", "&", "Session", "{", "config", ":", "config", ",", "logger", ":", "logger", ",", "conn", ":", "conn", ",", "bufRead", ":", "bufio", ".", "NewReader", "(", "conn", ")", ",", "pings", ":", "make", "(", "map", "[", "uint32", "]", "chan", "struct", "{", "}", ")", ",", "streams", ":", "make", "(", "map", "[", "uint32", "]", "*", "Stream", ")", ",", "inflight", ":", "make", "(", "map", "[", "uint32", "]", "struct", "{", "}", ")", ",", "synCh", ":", "make", "(", "chan", "struct", "{", "}", ",", "config", ".", "AcceptBacklog", ")", ",", "acceptCh", ":", "make", "(", "chan", "*", "Stream", ",", "config", ".", "AcceptBacklog", ")", ",", "sendCh", ":", "make", "(", "chan", "sendReady", ",", "64", ")", ",", "recvDoneCh", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "shutdownCh", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "if", "client", "{", "s", ".", "nextStreamID", "=", "1", "\n", "}", "else", "{", "s", ".", "nextStreamID", "=", "2", "\n", "}", "\n", "go", "s", ".", "recv", "(", ")", "\n", "go", "s", ".", "send", "(", ")", "\n", "if", "config", ".", "EnableKeepAlive", "{", "go", "s", ".", "keepalive", "(", ")", "\n", "}", "\n", "return", "s", "\n", "}" ]
// newSession is used to construct a new session
[ "newSession", "is", "used", "to", "construct", "a", "new", "session" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L88-L119
train
hashicorp/yamux
session.go
NumStreams
func (s *Session) NumStreams() int { s.streamLock.Lock() num := len(s.streams) s.streamLock.Unlock() return num }
go
func (s *Session) NumStreams() int { s.streamLock.Lock() num := len(s.streams) s.streamLock.Unlock() return num }
[ "func", "(", "s", "*", "Session", ")", "NumStreams", "(", ")", "int", "{", "s", ".", "streamLock", ".", "Lock", "(", ")", "\n", "num", ":=", "len", "(", "s", ".", "streams", ")", "\n", "s", ".", "streamLock", ".", "Unlock", "(", ")", "\n", "return", "num", "\n", "}" ]
// NumStreams returns the number of currently open streams
[ "NumStreams", "returns", "the", "number", "of", "currently", "open", "streams" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L138-L143
train
hashicorp/yamux
session.go
Open
func (s *Session) Open() (net.Conn, error) { conn, err := s.OpenStream() if err != nil { return nil, err } return conn, nil }
go
func (s *Session) Open() (net.Conn, error) { conn, err := s.OpenStream() if err != nil { return nil, err } return conn, nil }
[ "func", "(", "s", "*", "Session", ")", "Open", "(", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "conn", ",", "err", ":=", "s", ".", "OpenStream", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "conn", ",", "nil", "\n", "}" ]
// Open is used to create a new stream as a net.Conn
[ "Open", "is", "used", "to", "create", "a", "new", "stream", "as", "a", "net", ".", "Conn" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L146-L152
train
hashicorp/yamux
session.go
Accept
func (s *Session) Accept() (net.Conn, error) { conn, err := s.AcceptStream() if err != nil { return nil, err } return conn, err }
go
func (s *Session) Accept() (net.Conn, error) { conn, err := s.AcceptStream() if err != nil { return nil, err } return conn, err }
[ "func", "(", "s", "*", "Session", ")", "Accept", "(", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "conn", ",", "err", ":=", "s", ".", "AcceptStream", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "conn", ",", "err", "\n", "}" ]
// Accept is used to block until the next available stream // is ready to be accepted.
[ "Accept", "is", "used", "to", "block", "until", "the", "next", "available", "stream", "is", "ready", "to", "be", "accepted", "." ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L201-L207
train
hashicorp/yamux
session.go
Close
func (s *Session) Close() error { s.shutdownLock.Lock() defer s.shutdownLock.Unlock() if s.shutdown { return nil } s.shutdown = true if s.shutdownErr == nil { s.shutdownErr = ErrSessionShutdown } close(s.shutdownCh) s.conn.Close() <-s.recvDoneCh s.streamLock.Lock() defer s.streamLock.Unlock() for _, stream := range s.streams { stream.forceClose() } return nil }
go
func (s *Session) Close() error { s.shutdownLock.Lock() defer s.shutdownLock.Unlock() if s.shutdown { return nil } s.shutdown = true if s.shutdownErr == nil { s.shutdownErr = ErrSessionShutdown } close(s.shutdownCh) s.conn.Close() <-s.recvDoneCh s.streamLock.Lock() defer s.streamLock.Unlock() for _, stream := range s.streams { stream.forceClose() } return nil }
[ "func", "(", "s", "*", "Session", ")", "Close", "(", ")", "error", "{", "s", ".", "shutdownLock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "shutdownLock", ".", "Unlock", "(", ")", "\n", "if", "s", ".", "shutdown", "{", "return", "nil", "\n", "}", "\n", "s", ".", "shutdown", "=", "true", "\n", "if", "s", ".", "shutdownErr", "==", "nil", "{", "s", ".", "shutdownErr", "=", "ErrSessionShutdown", "\n", "}", "\n", "close", "(", "s", ".", "shutdownCh", ")", "\n", "s", ".", "conn", ".", "Close", "(", ")", "\n", "<-", "s", ".", "recvDoneCh", "\n", "s", ".", "streamLock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "streamLock", ".", "Unlock", "(", ")", "\n", "for", "_", ",", "stream", ":=", "range", "s", ".", "streams", "{", "stream", ".", "forceClose", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close is used to close the session and all streams. // Attempts to send a GoAway before closing the connection.
[ "Close", "is", "used", "to", "close", "the", "session", "and", "all", "streams", ".", "Attempts", "to", "send", "a", "GoAway", "before", "closing", "the", "connection", "." ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L225-L246
train
hashicorp/yamux
session.go
exitErr
func (s *Session) exitErr(err error) { s.shutdownLock.Lock() if s.shutdownErr == nil { s.shutdownErr = err } s.shutdownLock.Unlock() s.Close() }
go
func (s *Session) exitErr(err error) { s.shutdownLock.Lock() if s.shutdownErr == nil { s.shutdownErr = err } s.shutdownLock.Unlock() s.Close() }
[ "func", "(", "s", "*", "Session", ")", "exitErr", "(", "err", "error", ")", "{", "s", ".", "shutdownLock", ".", "Lock", "(", ")", "\n", "if", "s", ".", "shutdownErr", "==", "nil", "{", "s", ".", "shutdownErr", "=", "err", "\n", "}", "\n", "s", ".", "shutdownLock", ".", "Unlock", "(", ")", "\n", "s", ".", "Close", "(", ")", "\n", "}" ]
// exitErr is used to handle an error that is causing the // session to terminate.
[ "exitErr", "is", "used", "to", "handle", "an", "error", "that", "is", "causing", "the", "session", "to", "terminate", "." ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L250-L257
train
hashicorp/yamux
session.go
GoAway
func (s *Session) GoAway() error { return s.waitForSend(s.goAway(goAwayNormal), nil) }
go
func (s *Session) GoAway() error { return s.waitForSend(s.goAway(goAwayNormal), nil) }
[ "func", "(", "s", "*", "Session", ")", "GoAway", "(", ")", "error", "{", "return", "s", ".", "waitForSend", "(", "s", ".", "goAway", "(", "goAwayNormal", ")", ",", "nil", ")", "\n", "}" ]
// GoAway can be used to prevent accepting further // connections. It does not close the underlying conn.
[ "GoAway", "can", "be", "used", "to", "prevent", "accepting", "further", "connections", ".", "It", "does", "not", "close", "the", "underlying", "conn", "." ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L261-L263
train
hashicorp/yamux
session.go
goAway
func (s *Session) goAway(reason uint32) header { atomic.SwapInt32(&s.localGoAway, 1) hdr := header(make([]byte, headerSize)) hdr.encode(typeGoAway, 0, 0, reason) return hdr }
go
func (s *Session) goAway(reason uint32) header { atomic.SwapInt32(&s.localGoAway, 1) hdr := header(make([]byte, headerSize)) hdr.encode(typeGoAway, 0, 0, reason) return hdr }
[ "func", "(", "s", "*", "Session", ")", "goAway", "(", "reason", "uint32", ")", "header", "{", "atomic", ".", "SwapInt32", "(", "&", "s", ".", "localGoAway", ",", "1", ")", "\n", "hdr", ":=", "header", "(", "make", "(", "[", "]", "byte", ",", "headerSize", ")", ")", "\n", "hdr", ".", "encode", "(", "typeGoAway", ",", "0", ",", "0", ",", "reason", ")", "\n", "return", "hdr", "\n", "}" ]
// goAway is used to send a goAway message
[ "goAway", "is", "used", "to", "send", "a", "goAway", "message" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L266-L271
train
hashicorp/yamux
session.go
Ping
func (s *Session) Ping() (time.Duration, error) { // Get a channel for the ping ch := make(chan struct{}) // Get a new ping id, mark as pending s.pingLock.Lock() id := s.pingID s.pingID++ s.pings[id] = ch s.pingLock.Unlock() // Send the ping request hdr := header(make([]byte, headerSize)) hdr.encode(typePing, flagSYN, 0, id) if err := s.waitForSend(hdr, nil); err != nil { return 0, err } // Wait for a response start := time.Now() select { case <-ch: case <-time.After(s.config.ConnectionWriteTimeout): s.pingLock.Lock() delete(s.pings, id) // Ignore it if a response comes later. s.pingLock.Unlock() return 0, ErrTimeout case <-s.shutdownCh: return 0, ErrSessionShutdown } // Compute the RTT return time.Now().Sub(start), nil }
go
func (s *Session) Ping() (time.Duration, error) { // Get a channel for the ping ch := make(chan struct{}) // Get a new ping id, mark as pending s.pingLock.Lock() id := s.pingID s.pingID++ s.pings[id] = ch s.pingLock.Unlock() // Send the ping request hdr := header(make([]byte, headerSize)) hdr.encode(typePing, flagSYN, 0, id) if err := s.waitForSend(hdr, nil); err != nil { return 0, err } // Wait for a response start := time.Now() select { case <-ch: case <-time.After(s.config.ConnectionWriteTimeout): s.pingLock.Lock() delete(s.pings, id) // Ignore it if a response comes later. s.pingLock.Unlock() return 0, ErrTimeout case <-s.shutdownCh: return 0, ErrSessionShutdown } // Compute the RTT return time.Now().Sub(start), nil }
[ "func", "(", "s", "*", "Session", ")", "Ping", "(", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "ch", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "s", ".", "pingLock", ".", "Lock", "(", ")", "\n", "id", ":=", "s", ".", "pingID", "\n", "s", ".", "pingID", "++", "\n", "s", ".", "pings", "[", "id", "]", "=", "ch", "\n", "s", ".", "pingLock", ".", "Unlock", "(", ")", "\n", "hdr", ":=", "header", "(", "make", "(", "[", "]", "byte", ",", "headerSize", ")", ")", "\n", "hdr", ".", "encode", "(", "typePing", ",", "flagSYN", ",", "0", ",", "id", ")", "\n", "if", "err", ":=", "s", ".", "waitForSend", "(", "hdr", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "start", ":=", "time", ".", "Now", "(", ")", "\n", "select", "{", "case", "<-", "ch", ":", "case", "<-", "time", ".", "After", "(", "s", ".", "config", ".", "ConnectionWriteTimeout", ")", ":", "s", ".", "pingLock", ".", "Lock", "(", ")", "\n", "delete", "(", "s", ".", "pings", ",", "id", ")", "\n", "s", ".", "pingLock", ".", "Unlock", "(", ")", "\n", "return", "0", ",", "ErrTimeout", "\n", "case", "<-", "s", ".", "shutdownCh", ":", "return", "0", ",", "ErrSessionShutdown", "\n", "}", "\n", "return", "time", ".", "Now", "(", ")", ".", "Sub", "(", "start", ")", ",", "nil", "\n", "}" ]
// Ping is used to measure the RTT response time
[ "Ping", "is", "used", "to", "measure", "the", "RTT", "response", "time" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L274-L307
train
hashicorp/yamux
session.go
keepalive
func (s *Session) keepalive() { for { select { case <-time.After(s.config.KeepAliveInterval): _, err := s.Ping() if err != nil { if err != ErrSessionShutdown { s.logger.Printf("[ERR] yamux: keepalive failed: %v", err) s.exitErr(ErrKeepAliveTimeout) } return } case <-s.shutdownCh: return } } }
go
func (s *Session) keepalive() { for { select { case <-time.After(s.config.KeepAliveInterval): _, err := s.Ping() if err != nil { if err != ErrSessionShutdown { s.logger.Printf("[ERR] yamux: keepalive failed: %v", err) s.exitErr(ErrKeepAliveTimeout) } return } case <-s.shutdownCh: return } } }
[ "func", "(", "s", "*", "Session", ")", "keepalive", "(", ")", "{", "for", "{", "select", "{", "case", "<-", "time", ".", "After", "(", "s", ".", "config", ".", "KeepAliveInterval", ")", ":", "_", ",", "err", ":=", "s", ".", "Ping", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "!=", "ErrSessionShutdown", "{", "s", ".", "logger", ".", "Printf", "(", "\"[ERR] yamux: keepalive failed: %v\"", ",", "err", ")", "\n", "s", ".", "exitErr", "(", "ErrKeepAliveTimeout", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "case", "<-", "s", ".", "shutdownCh", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// keepalive is a long running goroutine that periodically does // a ping to keep the connection alive.
[ "keepalive", "is", "a", "long", "running", "goroutine", "that", "periodically", "does", "a", "ping", "to", "keep", "the", "connection", "alive", "." ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L311-L327
train
hashicorp/yamux
session.go
waitForSend
func (s *Session) waitForSend(hdr header, body io.Reader) error { errCh := make(chan error, 1) return s.waitForSendErr(hdr, body, errCh) }
go
func (s *Session) waitForSend(hdr header, body io.Reader) error { errCh := make(chan error, 1) return s.waitForSendErr(hdr, body, errCh) }
[ "func", "(", "s", "*", "Session", ")", "waitForSend", "(", "hdr", "header", ",", "body", "io", ".", "Reader", ")", "error", "{", "errCh", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "return", "s", ".", "waitForSendErr", "(", "hdr", ",", "body", ",", "errCh", ")", "\n", "}" ]
// waitForSendErr waits to send a header, checking for a potential shutdown
[ "waitForSendErr", "waits", "to", "send", "a", "header", "checking", "for", "a", "potential", "shutdown" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L330-L333
train
hashicorp/yamux
session.go
waitForSendErr
func (s *Session) waitForSendErr(hdr header, body io.Reader, errCh chan error) error { t := timerPool.Get() timer := t.(*time.Timer) timer.Reset(s.config.ConnectionWriteTimeout) defer func() { timer.Stop() select { case <-timer.C: default: } timerPool.Put(t) }() ready := sendReady{Hdr: hdr, Body: body, Err: errCh} select { case s.sendCh <- ready: case <-s.shutdownCh: return ErrSessionShutdown case <-timer.C: return ErrConnectionWriteTimeout } select { case err := <-errCh: return err case <-s.shutdownCh: return ErrSessionShutdown case <-timer.C: return ErrConnectionWriteTimeout } }
go
func (s *Session) waitForSendErr(hdr header, body io.Reader, errCh chan error) error { t := timerPool.Get() timer := t.(*time.Timer) timer.Reset(s.config.ConnectionWriteTimeout) defer func() { timer.Stop() select { case <-timer.C: default: } timerPool.Put(t) }() ready := sendReady{Hdr: hdr, Body: body, Err: errCh} select { case s.sendCh <- ready: case <-s.shutdownCh: return ErrSessionShutdown case <-timer.C: return ErrConnectionWriteTimeout } select { case err := <-errCh: return err case <-s.shutdownCh: return ErrSessionShutdown case <-timer.C: return ErrConnectionWriteTimeout } }
[ "func", "(", "s", "*", "Session", ")", "waitForSendErr", "(", "hdr", "header", ",", "body", "io", ".", "Reader", ",", "errCh", "chan", "error", ")", "error", "{", "t", ":=", "timerPool", ".", "Get", "(", ")", "\n", "timer", ":=", "t", ".", "(", "*", "time", ".", "Timer", ")", "\n", "timer", ".", "Reset", "(", "s", ".", "config", ".", "ConnectionWriteTimeout", ")", "\n", "defer", "func", "(", ")", "{", "timer", ".", "Stop", "(", ")", "\n", "select", "{", "case", "<-", "timer", ".", "C", ":", "default", ":", "}", "\n", "timerPool", ".", "Put", "(", "t", ")", "\n", "}", "(", ")", "\n", "ready", ":=", "sendReady", "{", "Hdr", ":", "hdr", ",", "Body", ":", "body", ",", "Err", ":", "errCh", "}", "\n", "select", "{", "case", "s", ".", "sendCh", "<-", "ready", ":", "case", "<-", "s", ".", "shutdownCh", ":", "return", "ErrSessionShutdown", "\n", "case", "<-", "timer", ".", "C", ":", "return", "ErrConnectionWriteTimeout", "\n", "}", "\n", "select", "{", "case", "err", ":=", "<-", "errCh", ":", "return", "err", "\n", "case", "<-", "s", ".", "shutdownCh", ":", "return", "ErrSessionShutdown", "\n", "case", "<-", "timer", ".", "C", ":", "return", "ErrConnectionWriteTimeout", "\n", "}", "\n", "}" ]
// waitForSendErr waits to send a header with optional data, checking for a // potential shutdown. Since there's the expectation that sends can happen // in a timely manner, we enforce the connection write timeout here.
[ "waitForSendErr", "waits", "to", "send", "a", "header", "with", "optional", "data", "checking", "for", "a", "potential", "shutdown", ".", "Since", "there", "s", "the", "expectation", "that", "sends", "can", "happen", "in", "a", "timely", "manner", "we", "enforce", "the", "connection", "write", "timeout", "here", "." ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L338-L368
train
hashicorp/yamux
session.go
sendNoWait
func (s *Session) sendNoWait(hdr header) error { t := timerPool.Get() timer := t.(*time.Timer) timer.Reset(s.config.ConnectionWriteTimeout) defer func() { timer.Stop() select { case <-timer.C: default: } timerPool.Put(t) }() select { case s.sendCh <- sendReady{Hdr: hdr}: return nil case <-s.shutdownCh: return ErrSessionShutdown case <-timer.C: return ErrConnectionWriteTimeout } }
go
func (s *Session) sendNoWait(hdr header) error { t := timerPool.Get() timer := t.(*time.Timer) timer.Reset(s.config.ConnectionWriteTimeout) defer func() { timer.Stop() select { case <-timer.C: default: } timerPool.Put(t) }() select { case s.sendCh <- sendReady{Hdr: hdr}: return nil case <-s.shutdownCh: return ErrSessionShutdown case <-timer.C: return ErrConnectionWriteTimeout } }
[ "func", "(", "s", "*", "Session", ")", "sendNoWait", "(", "hdr", "header", ")", "error", "{", "t", ":=", "timerPool", ".", "Get", "(", ")", "\n", "timer", ":=", "t", ".", "(", "*", "time", ".", "Timer", ")", "\n", "timer", ".", "Reset", "(", "s", ".", "config", ".", "ConnectionWriteTimeout", ")", "\n", "defer", "func", "(", ")", "{", "timer", ".", "Stop", "(", ")", "\n", "select", "{", "case", "<-", "timer", ".", "C", ":", "default", ":", "}", "\n", "timerPool", ".", "Put", "(", "t", ")", "\n", "}", "(", ")", "\n", "select", "{", "case", "s", ".", "sendCh", "<-", "sendReady", "{", "Hdr", ":", "hdr", "}", ":", "return", "nil", "\n", "case", "<-", "s", ".", "shutdownCh", ":", "return", "ErrSessionShutdown", "\n", "case", "<-", "timer", ".", "C", ":", "return", "ErrConnectionWriteTimeout", "\n", "}", "\n", "}" ]
// sendNoWait does a send without waiting. Since there's the expectation that // the send happens right here, we enforce the connection write timeout if we // can't queue the header to be sent.
[ "sendNoWait", "does", "a", "send", "without", "waiting", ".", "Since", "there", "s", "the", "expectation", "that", "the", "send", "happens", "right", "here", "we", "enforce", "the", "connection", "write", "timeout", "if", "we", "can", "t", "queue", "the", "header", "to", "be", "sent", "." ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L373-L394
train
hashicorp/yamux
session.go
send
func (s *Session) send() { for { select { case ready := <-s.sendCh: // Send a header if ready if ready.Hdr != nil { sent := 0 for sent < len(ready.Hdr) { n, err := s.conn.Write(ready.Hdr[sent:]) if err != nil { s.logger.Printf("[ERR] yamux: Failed to write header: %v", err) asyncSendErr(ready.Err, err) s.exitErr(err) return } sent += n } } // Send data from a body if given if ready.Body != nil { _, err := io.Copy(s.conn, ready.Body) if err != nil { s.logger.Printf("[ERR] yamux: Failed to write body: %v", err) asyncSendErr(ready.Err, err) s.exitErr(err) return } } // No error, successful send asyncSendErr(ready.Err, nil) case <-s.shutdownCh: return } } }
go
func (s *Session) send() { for { select { case ready := <-s.sendCh: // Send a header if ready if ready.Hdr != nil { sent := 0 for sent < len(ready.Hdr) { n, err := s.conn.Write(ready.Hdr[sent:]) if err != nil { s.logger.Printf("[ERR] yamux: Failed to write header: %v", err) asyncSendErr(ready.Err, err) s.exitErr(err) return } sent += n } } // Send data from a body if given if ready.Body != nil { _, err := io.Copy(s.conn, ready.Body) if err != nil { s.logger.Printf("[ERR] yamux: Failed to write body: %v", err) asyncSendErr(ready.Err, err) s.exitErr(err) return } } // No error, successful send asyncSendErr(ready.Err, nil) case <-s.shutdownCh: return } } }
[ "func", "(", "s", "*", "Session", ")", "send", "(", ")", "{", "for", "{", "select", "{", "case", "ready", ":=", "<-", "s", ".", "sendCh", ":", "if", "ready", ".", "Hdr", "!=", "nil", "{", "sent", ":=", "0", "\n", "for", "sent", "<", "len", "(", "ready", ".", "Hdr", ")", "{", "n", ",", "err", ":=", "s", ".", "conn", ".", "Write", "(", "ready", ".", "Hdr", "[", "sent", ":", "]", ")", "\n", "if", "err", "!=", "nil", "{", "s", ".", "logger", ".", "Printf", "(", "\"[ERR] yamux: Failed to write header: %v\"", ",", "err", ")", "\n", "asyncSendErr", "(", "ready", ".", "Err", ",", "err", ")", "\n", "s", ".", "exitErr", "(", "err", ")", "\n", "return", "\n", "}", "\n", "sent", "+=", "n", "\n", "}", "\n", "}", "\n", "if", "ready", ".", "Body", "!=", "nil", "{", "_", ",", "err", ":=", "io", ".", "Copy", "(", "s", ".", "conn", ",", "ready", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "s", ".", "logger", ".", "Printf", "(", "\"[ERR] yamux: Failed to write body: %v\"", ",", "err", ")", "\n", "asyncSendErr", "(", "ready", ".", "Err", ",", "err", ")", "\n", "s", ".", "exitErr", "(", "err", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "asyncSendErr", "(", "ready", ".", "Err", ",", "nil", ")", "\n", "case", "<-", "s", ".", "shutdownCh", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// send is a long running goroutine that sends data
[ "send", "is", "a", "long", "running", "goroutine", "that", "sends", "data" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L397-L433
train
hashicorp/yamux
session.go
recv
func (s *Session) recv() { if err := s.recvLoop(); err != nil { s.exitErr(err) } }
go
func (s *Session) recv() { if err := s.recvLoop(); err != nil { s.exitErr(err) } }
[ "func", "(", "s", "*", "Session", ")", "recv", "(", ")", "{", "if", "err", ":=", "s", ".", "recvLoop", "(", ")", ";", "err", "!=", "nil", "{", "s", ".", "exitErr", "(", "err", ")", "\n", "}", "\n", "}" ]
// recv is a long running goroutine that accepts new data
[ "recv", "is", "a", "long", "running", "goroutine", "that", "accepts", "new", "data" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L436-L440
train
hashicorp/yamux
session.go
recvLoop
func (s *Session) recvLoop() error { defer close(s.recvDoneCh) hdr := header(make([]byte, headerSize)) for { // Read the header if _, err := io.ReadFull(s.bufRead, hdr); err != nil { if err != io.EOF && !strings.Contains(err.Error(), "closed") && !strings.Contains(err.Error(), "reset by peer") { s.logger.Printf("[ERR] yamux: Failed to read header: %v", err) } return err } // Verify the version if hdr.Version() != protoVersion { s.logger.Printf("[ERR] yamux: Invalid protocol version: %d", hdr.Version()) return ErrInvalidVersion } mt := hdr.MsgType() if mt < typeData || mt > typeGoAway { return ErrInvalidMsgType } if err := handlers[mt](s, hdr); err != nil { return err } } }
go
func (s *Session) recvLoop() error { defer close(s.recvDoneCh) hdr := header(make([]byte, headerSize)) for { // Read the header if _, err := io.ReadFull(s.bufRead, hdr); err != nil { if err != io.EOF && !strings.Contains(err.Error(), "closed") && !strings.Contains(err.Error(), "reset by peer") { s.logger.Printf("[ERR] yamux: Failed to read header: %v", err) } return err } // Verify the version if hdr.Version() != protoVersion { s.logger.Printf("[ERR] yamux: Invalid protocol version: %d", hdr.Version()) return ErrInvalidVersion } mt := hdr.MsgType() if mt < typeData || mt > typeGoAway { return ErrInvalidMsgType } if err := handlers[mt](s, hdr); err != nil { return err } } }
[ "func", "(", "s", "*", "Session", ")", "recvLoop", "(", ")", "error", "{", "defer", "close", "(", "s", ".", "recvDoneCh", ")", "\n", "hdr", ":=", "header", "(", "make", "(", "[", "]", "byte", ",", "headerSize", ")", ")", "\n", "for", "{", "if", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "s", ".", "bufRead", ",", "hdr", ")", ";", "err", "!=", "nil", "{", "if", "err", "!=", "io", ".", "EOF", "&&", "!", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"closed\"", ")", "&&", "!", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"reset by peer\"", ")", "{", "s", ".", "logger", ".", "Printf", "(", "\"[ERR] yamux: Failed to read header: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "if", "hdr", ".", "Version", "(", ")", "!=", "protoVersion", "{", "s", ".", "logger", ".", "Printf", "(", "\"[ERR] yamux: Invalid protocol version: %d\"", ",", "hdr", ".", "Version", "(", ")", ")", "\n", "return", "ErrInvalidVersion", "\n", "}", "\n", "mt", ":=", "hdr", ".", "MsgType", "(", ")", "\n", "if", "mt", "<", "typeData", "||", "mt", ">", "typeGoAway", "{", "return", "ErrInvalidMsgType", "\n", "}", "\n", "if", "err", ":=", "handlers", "[", "mt", "]", "(", "s", ",", "hdr", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}" ]
// recvLoop continues to receive data until a fatal error is encountered
[ "recvLoop", "continues", "to", "receive", "data", "until", "a", "fatal", "error", "is", "encountered" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L453-L480
train
hashicorp/yamux
session.go
handleStreamMessage
func (s *Session) handleStreamMessage(hdr header) error { // Check for a new stream creation id := hdr.StreamID() flags := hdr.Flags() if flags&flagSYN == flagSYN { if err := s.incomingStream(id); err != nil { return err } } // Get the stream s.streamLock.Lock() stream := s.streams[id] s.streamLock.Unlock() // If we do not have a stream, likely we sent a RST if stream == nil { // Drain any data on the wire if hdr.MsgType() == typeData && hdr.Length() > 0 { s.logger.Printf("[WARN] yamux: Discarding data for stream: %d", id) if _, err := io.CopyN(ioutil.Discard, s.bufRead, int64(hdr.Length())); err != nil { s.logger.Printf("[ERR] yamux: Failed to discard data: %v", err) return nil } } else { s.logger.Printf("[WARN] yamux: frame for missing stream: %v", hdr) } return nil } // Check if this is a window update if hdr.MsgType() == typeWindowUpdate { if err := stream.incrSendWindow(hdr, flags); err != nil { if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil { s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr) } return err } return nil } // Read the new data if err := stream.readData(hdr, flags, s.bufRead); err != nil { if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil { s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr) } return err } return nil }
go
func (s *Session) handleStreamMessage(hdr header) error { // Check for a new stream creation id := hdr.StreamID() flags := hdr.Flags() if flags&flagSYN == flagSYN { if err := s.incomingStream(id); err != nil { return err } } // Get the stream s.streamLock.Lock() stream := s.streams[id] s.streamLock.Unlock() // If we do not have a stream, likely we sent a RST if stream == nil { // Drain any data on the wire if hdr.MsgType() == typeData && hdr.Length() > 0 { s.logger.Printf("[WARN] yamux: Discarding data for stream: %d", id) if _, err := io.CopyN(ioutil.Discard, s.bufRead, int64(hdr.Length())); err != nil { s.logger.Printf("[ERR] yamux: Failed to discard data: %v", err) return nil } } else { s.logger.Printf("[WARN] yamux: frame for missing stream: %v", hdr) } return nil } // Check if this is a window update if hdr.MsgType() == typeWindowUpdate { if err := stream.incrSendWindow(hdr, flags); err != nil { if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil { s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr) } return err } return nil } // Read the new data if err := stream.readData(hdr, flags, s.bufRead); err != nil { if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil { s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr) } return err } return nil }
[ "func", "(", "s", "*", "Session", ")", "handleStreamMessage", "(", "hdr", "header", ")", "error", "{", "id", ":=", "hdr", ".", "StreamID", "(", ")", "\n", "flags", ":=", "hdr", ".", "Flags", "(", ")", "\n", "if", "flags", "&", "flagSYN", "==", "flagSYN", "{", "if", "err", ":=", "s", ".", "incomingStream", "(", "id", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "s", ".", "streamLock", ".", "Lock", "(", ")", "\n", "stream", ":=", "s", ".", "streams", "[", "id", "]", "\n", "s", ".", "streamLock", ".", "Unlock", "(", ")", "\n", "if", "stream", "==", "nil", "{", "if", "hdr", ".", "MsgType", "(", ")", "==", "typeData", "&&", "hdr", ".", "Length", "(", ")", ">", "0", "{", "s", ".", "logger", ".", "Printf", "(", "\"[WARN] yamux: Discarding data for stream: %d\"", ",", "id", ")", "\n", "if", "_", ",", "err", ":=", "io", ".", "CopyN", "(", "ioutil", ".", "Discard", ",", "s", ".", "bufRead", ",", "int64", "(", "hdr", ".", "Length", "(", ")", ")", ")", ";", "err", "!=", "nil", "{", "s", ".", "logger", ".", "Printf", "(", "\"[ERR] yamux: Failed to discard data: %v\"", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n", "}", "else", "{", "s", ".", "logger", ".", "Printf", "(", "\"[WARN] yamux: frame for missing stream: %v\"", ",", "hdr", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "if", "hdr", ".", "MsgType", "(", ")", "==", "typeWindowUpdate", "{", "if", "err", ":=", "stream", ".", "incrSendWindow", "(", "hdr", ",", "flags", ")", ";", "err", "!=", "nil", "{", "if", "sendErr", ":=", "s", ".", "sendNoWait", "(", "s", ".", "goAway", "(", "goAwayProtoErr", ")", ")", ";", "sendErr", "!=", "nil", "{", "s", ".", "logger", ".", "Printf", "(", "\"[WARN] yamux: failed to send go away: %v\"", ",", "sendErr", ")", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "if", "err", ":=", "stream", ".", "readData", "(", "hdr", ",", "flags", ",", "s", ".", "bufRead", ")", ";", "err", "!=", "nil", "{", "if", "sendErr", ":=", "s", ".", "sendNoWait", "(", "s", ".", "goAway", "(", "goAwayProtoErr", ")", ")", ";", "sendErr", "!=", "nil", "{", "s", ".", "logger", ".", "Printf", "(", "\"[WARN] yamux: failed to send go away: %v\"", ",", "sendErr", ")", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// handleStreamMessage handles either a data or window update frame
[ "handleStreamMessage", "handles", "either", "a", "data", "or", "window", "update", "frame" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L483-L532
train
hashicorp/yamux
session.go
handlePing
func (s *Session) handlePing(hdr header) error { flags := hdr.Flags() pingID := hdr.Length() // Check if this is a query, respond back in a separate context so we // don't interfere with the receiving thread blocking for the write. if flags&flagSYN == flagSYN { go func() { hdr := header(make([]byte, headerSize)) hdr.encode(typePing, flagACK, 0, pingID) if err := s.sendNoWait(hdr); err != nil { s.logger.Printf("[WARN] yamux: failed to send ping reply: %v", err) } }() return nil } // Handle a response s.pingLock.Lock() ch := s.pings[pingID] if ch != nil { delete(s.pings, pingID) close(ch) } s.pingLock.Unlock() return nil }
go
func (s *Session) handlePing(hdr header) error { flags := hdr.Flags() pingID := hdr.Length() // Check if this is a query, respond back in a separate context so we // don't interfere with the receiving thread blocking for the write. if flags&flagSYN == flagSYN { go func() { hdr := header(make([]byte, headerSize)) hdr.encode(typePing, flagACK, 0, pingID) if err := s.sendNoWait(hdr); err != nil { s.logger.Printf("[WARN] yamux: failed to send ping reply: %v", err) } }() return nil } // Handle a response s.pingLock.Lock() ch := s.pings[pingID] if ch != nil { delete(s.pings, pingID) close(ch) } s.pingLock.Unlock() return nil }
[ "func", "(", "s", "*", "Session", ")", "handlePing", "(", "hdr", "header", ")", "error", "{", "flags", ":=", "hdr", ".", "Flags", "(", ")", "\n", "pingID", ":=", "hdr", ".", "Length", "(", ")", "\n", "if", "flags", "&", "flagSYN", "==", "flagSYN", "{", "go", "func", "(", ")", "{", "hdr", ":=", "header", "(", "make", "(", "[", "]", "byte", ",", "headerSize", ")", ")", "\n", "hdr", ".", "encode", "(", "typePing", ",", "flagACK", ",", "0", ",", "pingID", ")", "\n", "if", "err", ":=", "s", ".", "sendNoWait", "(", "hdr", ")", ";", "err", "!=", "nil", "{", "s", ".", "logger", ".", "Printf", "(", "\"[WARN] yamux: failed to send ping reply: %v\"", ",", "err", ")", "\n", "}", "\n", "}", "(", ")", "\n", "return", "nil", "\n", "}", "\n", "s", ".", "pingLock", ".", "Lock", "(", ")", "\n", "ch", ":=", "s", ".", "pings", "[", "pingID", "]", "\n", "if", "ch", "!=", "nil", "{", "delete", "(", "s", ".", "pings", ",", "pingID", ")", "\n", "close", "(", "ch", ")", "\n", "}", "\n", "s", ".", "pingLock", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}" ]
// handlePing is invokde for a typePing frame
[ "handlePing", "is", "invokde", "for", "a", "typePing", "frame" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L535-L561
train
hashicorp/yamux
session.go
handleGoAway
func (s *Session) handleGoAway(hdr header) error { code := hdr.Length() switch code { case goAwayNormal: atomic.SwapInt32(&s.remoteGoAway, 1) case goAwayProtoErr: s.logger.Printf("[ERR] yamux: received protocol error go away") return fmt.Errorf("yamux protocol error") case goAwayInternalErr: s.logger.Printf("[ERR] yamux: received internal error go away") return fmt.Errorf("remote yamux internal error") default: s.logger.Printf("[ERR] yamux: received unexpected go away") return fmt.Errorf("unexpected go away received") } return nil }
go
func (s *Session) handleGoAway(hdr header) error { code := hdr.Length() switch code { case goAwayNormal: atomic.SwapInt32(&s.remoteGoAway, 1) case goAwayProtoErr: s.logger.Printf("[ERR] yamux: received protocol error go away") return fmt.Errorf("yamux protocol error") case goAwayInternalErr: s.logger.Printf("[ERR] yamux: received internal error go away") return fmt.Errorf("remote yamux internal error") default: s.logger.Printf("[ERR] yamux: received unexpected go away") return fmt.Errorf("unexpected go away received") } return nil }
[ "func", "(", "s", "*", "Session", ")", "handleGoAway", "(", "hdr", "header", ")", "error", "{", "code", ":=", "hdr", ".", "Length", "(", ")", "\n", "switch", "code", "{", "case", "goAwayNormal", ":", "atomic", ".", "SwapInt32", "(", "&", "s", ".", "remoteGoAway", ",", "1", ")", "\n", "case", "goAwayProtoErr", ":", "s", ".", "logger", ".", "Printf", "(", "\"[ERR] yamux: received protocol error go away\"", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"yamux protocol error\"", ")", "\n", "case", "goAwayInternalErr", ":", "s", ".", "logger", ".", "Printf", "(", "\"[ERR] yamux: received internal error go away\"", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"remote yamux internal error\"", ")", "\n", "default", ":", "s", ".", "logger", ".", "Printf", "(", "\"[ERR] yamux: received unexpected go away\"", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"unexpected go away received\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// handleGoAway is invokde for a typeGoAway frame
[ "handleGoAway", "is", "invokde", "for", "a", "typeGoAway", "frame" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L564-L580
train
hashicorp/yamux
session.go
incomingStream
func (s *Session) incomingStream(id uint32) error { // Reject immediately if we are doing a go away if atomic.LoadInt32(&s.localGoAway) == 1 { hdr := header(make([]byte, headerSize)) hdr.encode(typeWindowUpdate, flagRST, id, 0) return s.sendNoWait(hdr) } // Allocate a new stream stream := newStream(s, id, streamSYNReceived) s.streamLock.Lock() defer s.streamLock.Unlock() // Check if stream already exists if _, ok := s.streams[id]; ok { s.logger.Printf("[ERR] yamux: duplicate stream declared") if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil { s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr) } return ErrDuplicateStream } // Register the stream s.streams[id] = stream // Check if we've exceeded the backlog select { case s.acceptCh <- stream: return nil default: // Backlog exceeded! RST the stream s.logger.Printf("[WARN] yamux: backlog exceeded, forcing connection reset") delete(s.streams, id) stream.sendHdr.encode(typeWindowUpdate, flagRST, id, 0) return s.sendNoWait(stream.sendHdr) } }
go
func (s *Session) incomingStream(id uint32) error { // Reject immediately if we are doing a go away if atomic.LoadInt32(&s.localGoAway) == 1 { hdr := header(make([]byte, headerSize)) hdr.encode(typeWindowUpdate, flagRST, id, 0) return s.sendNoWait(hdr) } // Allocate a new stream stream := newStream(s, id, streamSYNReceived) s.streamLock.Lock() defer s.streamLock.Unlock() // Check if stream already exists if _, ok := s.streams[id]; ok { s.logger.Printf("[ERR] yamux: duplicate stream declared") if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil { s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr) } return ErrDuplicateStream } // Register the stream s.streams[id] = stream // Check if we've exceeded the backlog select { case s.acceptCh <- stream: return nil default: // Backlog exceeded! RST the stream s.logger.Printf("[WARN] yamux: backlog exceeded, forcing connection reset") delete(s.streams, id) stream.sendHdr.encode(typeWindowUpdate, flagRST, id, 0) return s.sendNoWait(stream.sendHdr) } }
[ "func", "(", "s", "*", "Session", ")", "incomingStream", "(", "id", "uint32", ")", "error", "{", "if", "atomic", ".", "LoadInt32", "(", "&", "s", ".", "localGoAway", ")", "==", "1", "{", "hdr", ":=", "header", "(", "make", "(", "[", "]", "byte", ",", "headerSize", ")", ")", "\n", "hdr", ".", "encode", "(", "typeWindowUpdate", ",", "flagRST", ",", "id", ",", "0", ")", "\n", "return", "s", ".", "sendNoWait", "(", "hdr", ")", "\n", "}", "\n", "stream", ":=", "newStream", "(", "s", ",", "id", ",", "streamSYNReceived", ")", "\n", "s", ".", "streamLock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "streamLock", ".", "Unlock", "(", ")", "\n", "if", "_", ",", "ok", ":=", "s", ".", "streams", "[", "id", "]", ";", "ok", "{", "s", ".", "logger", ".", "Printf", "(", "\"[ERR] yamux: duplicate stream declared\"", ")", "\n", "if", "sendErr", ":=", "s", ".", "sendNoWait", "(", "s", ".", "goAway", "(", "goAwayProtoErr", ")", ")", ";", "sendErr", "!=", "nil", "{", "s", ".", "logger", ".", "Printf", "(", "\"[WARN] yamux: failed to send go away: %v\"", ",", "sendErr", ")", "\n", "}", "\n", "return", "ErrDuplicateStream", "\n", "}", "\n", "s", ".", "streams", "[", "id", "]", "=", "stream", "\n", "select", "{", "case", "s", ".", "acceptCh", "<-", "stream", ":", "return", "nil", "\n", "default", ":", "s", ".", "logger", ".", "Printf", "(", "\"[WARN] yamux: backlog exceeded, forcing connection reset\"", ")", "\n", "delete", "(", "s", ".", "streams", ",", "id", ")", "\n", "stream", ".", "sendHdr", ".", "encode", "(", "typeWindowUpdate", ",", "flagRST", ",", "id", ",", "0", ")", "\n", "return", "s", ".", "sendNoWait", "(", "stream", ".", "sendHdr", ")", "\n", "}", "\n", "}" ]
// incomingStream is used to create a new incoming stream
[ "incomingStream", "is", "used", "to", "create", "a", "new", "incoming", "stream" ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L583-L620
train
hashicorp/yamux
session.go
closeStream
func (s *Session) closeStream(id uint32) { s.streamLock.Lock() if _, ok := s.inflight[id]; ok { select { case <-s.synCh: default: s.logger.Printf("[ERR] yamux: SYN tracking out of sync") } } delete(s.streams, id) s.streamLock.Unlock() }
go
func (s *Session) closeStream(id uint32) { s.streamLock.Lock() if _, ok := s.inflight[id]; ok { select { case <-s.synCh: default: s.logger.Printf("[ERR] yamux: SYN tracking out of sync") } } delete(s.streams, id) s.streamLock.Unlock() }
[ "func", "(", "s", "*", "Session", ")", "closeStream", "(", "id", "uint32", ")", "{", "s", ".", "streamLock", ".", "Lock", "(", ")", "\n", "if", "_", ",", "ok", ":=", "s", ".", "inflight", "[", "id", "]", ";", "ok", "{", "select", "{", "case", "<-", "s", ".", "synCh", ":", "default", ":", "s", ".", "logger", ".", "Printf", "(", "\"[ERR] yamux: SYN tracking out of sync\"", ")", "\n", "}", "\n", "}", "\n", "delete", "(", "s", ".", "streams", ",", "id", ")", "\n", "s", ".", "streamLock", ".", "Unlock", "(", ")", "\n", "}" ]
// closeStream is used to close a stream once both sides have // issued a close. If there was an in-flight SYN and the stream // was not yet established, then this will give the credit back.
[ "closeStream", "is", "used", "to", "close", "a", "stream", "once", "both", "sides", "have", "issued", "a", "close", ".", "If", "there", "was", "an", "in", "-", "flight", "SYN", "and", "the", "stream", "was", "not", "yet", "established", "then", "this", "will", "give", "the", "credit", "back", "." ]
2f1d1f20f75d5404f53b9edf6b53ed5505508675
https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L625-L636
train
afex/hystrix-go
plugins/graphite_aggregator.go
InitializeGraphiteCollector
func InitializeGraphiteCollector(config *GraphiteCollectorConfig) { go metrics.Graphite(metrics.DefaultRegistry, config.TickInterval, config.Prefix, config.GraphiteAddr) }
go
func InitializeGraphiteCollector(config *GraphiteCollectorConfig) { go metrics.Graphite(metrics.DefaultRegistry, config.TickInterval, config.Prefix, config.GraphiteAddr) }
[ "func", "InitializeGraphiteCollector", "(", "config", "*", "GraphiteCollectorConfig", ")", "{", "go", "metrics", ".", "Graphite", "(", "metrics", ".", "DefaultRegistry", ",", "config", ".", "TickInterval", ",", "config", ".", "Prefix", ",", "config", ".", "GraphiteAddr", ")", "\n", "}" ]
// InitializeGraphiteCollector creates the connection to the graphite server // and should be called before any metrics are recorded.
[ "InitializeGraphiteCollector", "creates", "the", "connection", "to", "the", "graphite", "server", "and", "should", "be", "called", "before", "any", "metrics", "are", "recorded", "." ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/plugins/graphite_aggregator.go#L49-L51
train
afex/hystrix-go
hystrix/circuit.go
GetCircuit
func GetCircuit(name string) (*CircuitBreaker, bool, error) { circuitBreakersMutex.RLock() _, ok := circuitBreakers[name] if !ok { circuitBreakersMutex.RUnlock() circuitBreakersMutex.Lock() defer circuitBreakersMutex.Unlock() // because we released the rlock before we obtained the exclusive lock, // we need to double check that some other thread didn't beat us to // creation. if cb, ok := circuitBreakers[name]; ok { return cb, false, nil } circuitBreakers[name] = newCircuitBreaker(name) } else { defer circuitBreakersMutex.RUnlock() } return circuitBreakers[name], !ok, nil }
go
func GetCircuit(name string) (*CircuitBreaker, bool, error) { circuitBreakersMutex.RLock() _, ok := circuitBreakers[name] if !ok { circuitBreakersMutex.RUnlock() circuitBreakersMutex.Lock() defer circuitBreakersMutex.Unlock() // because we released the rlock before we obtained the exclusive lock, // we need to double check that some other thread didn't beat us to // creation. if cb, ok := circuitBreakers[name]; ok { return cb, false, nil } circuitBreakers[name] = newCircuitBreaker(name) } else { defer circuitBreakersMutex.RUnlock() } return circuitBreakers[name], !ok, nil }
[ "func", "GetCircuit", "(", "name", "string", ")", "(", "*", "CircuitBreaker", ",", "bool", ",", "error", ")", "{", "circuitBreakersMutex", ".", "RLock", "(", ")", "\n", "_", ",", "ok", ":=", "circuitBreakers", "[", "name", "]", "\n", "if", "!", "ok", "{", "circuitBreakersMutex", ".", "RUnlock", "(", ")", "\n", "circuitBreakersMutex", ".", "Lock", "(", ")", "\n", "defer", "circuitBreakersMutex", ".", "Unlock", "(", ")", "\n", "if", "cb", ",", "ok", ":=", "circuitBreakers", "[", "name", "]", ";", "ok", "{", "return", "cb", ",", "false", ",", "nil", "\n", "}", "\n", "circuitBreakers", "[", "name", "]", "=", "newCircuitBreaker", "(", "name", ")", "\n", "}", "else", "{", "defer", "circuitBreakersMutex", ".", "RUnlock", "(", ")", "\n", "}", "\n", "return", "circuitBreakers", "[", "name", "]", ",", "!", "ok", ",", "nil", "\n", "}" ]
// GetCircuit returns the circuit for the given command and whether this call created it.
[ "GetCircuit", "returns", "the", "circuit", "for", "the", "given", "command", "and", "whether", "this", "call", "created", "it", "." ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/circuit.go#L34-L53
train
afex/hystrix-go
hystrix/circuit.go
Flush
func Flush() { circuitBreakersMutex.Lock() defer circuitBreakersMutex.Unlock() for name, cb := range circuitBreakers { cb.metrics.Reset() cb.executorPool.Metrics.Reset() delete(circuitBreakers, name) } }
go
func Flush() { circuitBreakersMutex.Lock() defer circuitBreakersMutex.Unlock() for name, cb := range circuitBreakers { cb.metrics.Reset() cb.executorPool.Metrics.Reset() delete(circuitBreakers, name) } }
[ "func", "Flush", "(", ")", "{", "circuitBreakersMutex", ".", "Lock", "(", ")", "\n", "defer", "circuitBreakersMutex", ".", "Unlock", "(", ")", "\n", "for", "name", ",", "cb", ":=", "range", "circuitBreakers", "{", "cb", ".", "metrics", ".", "Reset", "(", ")", "\n", "cb", ".", "executorPool", ".", "Metrics", ".", "Reset", "(", ")", "\n", "delete", "(", "circuitBreakers", ",", "name", ")", "\n", "}", "\n", "}" ]
// Flush purges all circuit and metric information from memory.
[ "Flush", "purges", "all", "circuit", "and", "metric", "information", "from", "memory", "." ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/circuit.go#L56-L65
train
afex/hystrix-go
hystrix/circuit.go
newCircuitBreaker
func newCircuitBreaker(name string) *CircuitBreaker { c := &CircuitBreaker{} c.Name = name c.metrics = newMetricExchange(name) c.executorPool = newExecutorPool(name) c.mutex = &sync.RWMutex{} return c }
go
func newCircuitBreaker(name string) *CircuitBreaker { c := &CircuitBreaker{} c.Name = name c.metrics = newMetricExchange(name) c.executorPool = newExecutorPool(name) c.mutex = &sync.RWMutex{} return c }
[ "func", "newCircuitBreaker", "(", "name", "string", ")", "*", "CircuitBreaker", "{", "c", ":=", "&", "CircuitBreaker", "{", "}", "\n", "c", ".", "Name", "=", "name", "\n", "c", ".", "metrics", "=", "newMetricExchange", "(", "name", ")", "\n", "c", ".", "executorPool", "=", "newExecutorPool", "(", "name", ")", "\n", "c", ".", "mutex", "=", "&", "sync", ".", "RWMutex", "{", "}", "\n", "return", "c", "\n", "}" ]
// newCircuitBreaker creates a CircuitBreaker with associated Health
[ "newCircuitBreaker", "creates", "a", "CircuitBreaker", "with", "associated", "Health" ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/circuit.go#L68-L76
train
afex/hystrix-go
hystrix/circuit.go
toggleForceOpen
func (circuit *CircuitBreaker) toggleForceOpen(toggle bool) error { circuit, _, err := GetCircuit(circuit.Name) if err != nil { return err } circuit.forceOpen = toggle return nil }
go
func (circuit *CircuitBreaker) toggleForceOpen(toggle bool) error { circuit, _, err := GetCircuit(circuit.Name) if err != nil { return err } circuit.forceOpen = toggle return nil }
[ "func", "(", "circuit", "*", "CircuitBreaker", ")", "toggleForceOpen", "(", "toggle", "bool", ")", "error", "{", "circuit", ",", "_", ",", "err", ":=", "GetCircuit", "(", "circuit", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "circuit", ".", "forceOpen", "=", "toggle", "\n", "return", "nil", "\n", "}" ]
// toggleForceOpen allows manually causing the fallback logic for all instances // of a given command.
[ "toggleForceOpen", "allows", "manually", "causing", "the", "fallback", "logic", "for", "all", "instances", "of", "a", "given", "command", "." ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/circuit.go#L80-L88
train
afex/hystrix-go
hystrix/circuit.go
IsOpen
func (circuit *CircuitBreaker) IsOpen() bool { circuit.mutex.RLock() o := circuit.forceOpen || circuit.open circuit.mutex.RUnlock() if o { return true } if uint64(circuit.metrics.Requests().Sum(time.Now())) < getSettings(circuit.Name).RequestVolumeThreshold { return false } if !circuit.metrics.IsHealthy(time.Now()) { // too many failures, open the circuit circuit.setOpen() return true } return false }
go
func (circuit *CircuitBreaker) IsOpen() bool { circuit.mutex.RLock() o := circuit.forceOpen || circuit.open circuit.mutex.RUnlock() if o { return true } if uint64(circuit.metrics.Requests().Sum(time.Now())) < getSettings(circuit.Name).RequestVolumeThreshold { return false } if !circuit.metrics.IsHealthy(time.Now()) { // too many failures, open the circuit circuit.setOpen() return true } return false }
[ "func", "(", "circuit", "*", "CircuitBreaker", ")", "IsOpen", "(", ")", "bool", "{", "circuit", ".", "mutex", ".", "RLock", "(", ")", "\n", "o", ":=", "circuit", ".", "forceOpen", "||", "circuit", ".", "open", "\n", "circuit", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "if", "o", "{", "return", "true", "\n", "}", "\n", "if", "uint64", "(", "circuit", ".", "metrics", ".", "Requests", "(", ")", ".", "Sum", "(", "time", ".", "Now", "(", ")", ")", ")", "<", "getSettings", "(", "circuit", ".", "Name", ")", ".", "RequestVolumeThreshold", "{", "return", "false", "\n", "}", "\n", "if", "!", "circuit", ".", "metrics", ".", "IsHealthy", "(", "time", ".", "Now", "(", ")", ")", "{", "circuit", ".", "setOpen", "(", ")", "\n", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsOpen is called before any Command execution to check whether or // not it should be attempted. An "open" circuit means it is disabled.
[ "IsOpen", "is", "called", "before", "any", "Command", "execution", "to", "check", "whether", "or", "not", "it", "should", "be", "attempted", ".", "An", "open", "circuit", "means", "it", "is", "disabled", "." ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/circuit.go#L92-L112
train
afex/hystrix-go
hystrix/circuit.go
ReportEvent
func (circuit *CircuitBreaker) ReportEvent(eventTypes []string, start time.Time, runDuration time.Duration) error { if len(eventTypes) == 0 { return fmt.Errorf("no event types sent for metrics") } circuit.mutex.RLock() o := circuit.open circuit.mutex.RUnlock() if eventTypes[0] == "success" && o { circuit.setClose() } var concurrencyInUse float64 if circuit.executorPool.Max > 0 { concurrencyInUse = float64(circuit.executorPool.ActiveCount()) / float64(circuit.executorPool.Max) } select { case circuit.metrics.Updates <- &commandExecution{ Types: eventTypes, Start: start, RunDuration: runDuration, ConcurrencyInUse: concurrencyInUse, }: default: return CircuitError{Message: fmt.Sprintf("metrics channel (%v) is at capacity", circuit.Name)} } return nil }
go
func (circuit *CircuitBreaker) ReportEvent(eventTypes []string, start time.Time, runDuration time.Duration) error { if len(eventTypes) == 0 { return fmt.Errorf("no event types sent for metrics") } circuit.mutex.RLock() o := circuit.open circuit.mutex.RUnlock() if eventTypes[0] == "success" && o { circuit.setClose() } var concurrencyInUse float64 if circuit.executorPool.Max > 0 { concurrencyInUse = float64(circuit.executorPool.ActiveCount()) / float64(circuit.executorPool.Max) } select { case circuit.metrics.Updates <- &commandExecution{ Types: eventTypes, Start: start, RunDuration: runDuration, ConcurrencyInUse: concurrencyInUse, }: default: return CircuitError{Message: fmt.Sprintf("metrics channel (%v) is at capacity", circuit.Name)} } return nil }
[ "func", "(", "circuit", "*", "CircuitBreaker", ")", "ReportEvent", "(", "eventTypes", "[", "]", "string", ",", "start", "time", ".", "Time", ",", "runDuration", "time", ".", "Duration", ")", "error", "{", "if", "len", "(", "eventTypes", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"no event types sent for metrics\"", ")", "\n", "}", "\n", "circuit", ".", "mutex", ".", "RLock", "(", ")", "\n", "o", ":=", "circuit", ".", "open", "\n", "circuit", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "if", "eventTypes", "[", "0", "]", "==", "\"success\"", "&&", "o", "{", "circuit", ".", "setClose", "(", ")", "\n", "}", "\n", "var", "concurrencyInUse", "float64", "\n", "if", "circuit", ".", "executorPool", ".", "Max", ">", "0", "{", "concurrencyInUse", "=", "float64", "(", "circuit", ".", "executorPool", ".", "ActiveCount", "(", ")", ")", "/", "float64", "(", "circuit", ".", "executorPool", ".", "Max", ")", "\n", "}", "\n", "select", "{", "case", "circuit", ".", "metrics", ".", "Updates", "<-", "&", "commandExecution", "{", "Types", ":", "eventTypes", ",", "Start", ":", "start", ",", "RunDuration", ":", "runDuration", ",", "ConcurrencyInUse", ":", "concurrencyInUse", ",", "}", ":", "default", ":", "return", "CircuitError", "{", "Message", ":", "fmt", ".", "Sprintf", "(", "\"metrics channel (%v) is at capacity\"", ",", "circuit", ".", "Name", ")", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ReportEvent records command metrics for tracking recent error rates and exposing data to the dashboard.
[ "ReportEvent", "records", "command", "metrics", "for", "tracking", "recent", "error", "rates", "and", "exposing", "data", "to", "the", "dashboard", "." ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/circuit.go#L167-L196
train
afex/hystrix-go
hystrix/rolling/rolling.go
NewNumber
func NewNumber() *Number { r := &Number{ Buckets: make(map[int64]*numberBucket), Mutex: &sync.RWMutex{}, } return r }
go
func NewNumber() *Number { r := &Number{ Buckets: make(map[int64]*numberBucket), Mutex: &sync.RWMutex{}, } return r }
[ "func", "NewNumber", "(", ")", "*", "Number", "{", "r", ":=", "&", "Number", "{", "Buckets", ":", "make", "(", "map", "[", "int64", "]", "*", "numberBucket", ")", ",", "Mutex", ":", "&", "sync", ".", "RWMutex", "{", "}", ",", "}", "\n", "return", "r", "\n", "}" ]
// NewNumber initializes a RollingNumber struct.
[ "NewNumber", "initializes", "a", "RollingNumber", "struct", "." ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling.go#L20-L26
train
afex/hystrix-go
hystrix/rolling/rolling.go
Increment
func (r *Number) Increment(i float64) { if i == 0 { return } r.Mutex.Lock() defer r.Mutex.Unlock() b := r.getCurrentBucket() b.Value += i r.removeOldBuckets() }
go
func (r *Number) Increment(i float64) { if i == 0 { return } r.Mutex.Lock() defer r.Mutex.Unlock() b := r.getCurrentBucket() b.Value += i r.removeOldBuckets() }
[ "func", "(", "r", "*", "Number", ")", "Increment", "(", "i", "float64", ")", "{", "if", "i", "==", "0", "{", "return", "\n", "}", "\n", "r", ".", "Mutex", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "Mutex", ".", "Unlock", "(", ")", "\n", "b", ":=", "r", ".", "getCurrentBucket", "(", ")", "\n", "b", ".", "Value", "+=", "i", "\n", "r", ".", "removeOldBuckets", "(", ")", "\n", "}" ]
// Increment increments the number in current timeBucket.
[ "Increment", "increments", "the", "number", "in", "current", "timeBucket", "." ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling.go#L53-L64
train
afex/hystrix-go
hystrix/rolling/rolling.go
UpdateMax
func (r *Number) UpdateMax(n float64) { r.Mutex.Lock() defer r.Mutex.Unlock() b := r.getCurrentBucket() if n > b.Value { b.Value = n } r.removeOldBuckets() }
go
func (r *Number) UpdateMax(n float64) { r.Mutex.Lock() defer r.Mutex.Unlock() b := r.getCurrentBucket() if n > b.Value { b.Value = n } r.removeOldBuckets() }
[ "func", "(", "r", "*", "Number", ")", "UpdateMax", "(", "n", "float64", ")", "{", "r", ".", "Mutex", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "Mutex", ".", "Unlock", "(", ")", "\n", "b", ":=", "r", ".", "getCurrentBucket", "(", ")", "\n", "if", "n", ">", "b", ".", "Value", "{", "b", ".", "Value", "=", "n", "\n", "}", "\n", "r", ".", "removeOldBuckets", "(", ")", "\n", "}" ]
// UpdateMax updates the maximum value in the current bucket.
[ "UpdateMax", "updates", "the", "maximum", "value", "in", "the", "current", "bucket", "." ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling.go#L67-L76
train
afex/hystrix-go
hystrix/rolling/rolling.go
Sum
func (r *Number) Sum(now time.Time) float64 { sum := float64(0) r.Mutex.RLock() defer r.Mutex.RUnlock() for timestamp, bucket := range r.Buckets { // TODO: configurable rolling window if timestamp >= now.Unix()-10 { sum += bucket.Value } } return sum }
go
func (r *Number) Sum(now time.Time) float64 { sum := float64(0) r.Mutex.RLock() defer r.Mutex.RUnlock() for timestamp, bucket := range r.Buckets { // TODO: configurable rolling window if timestamp >= now.Unix()-10 { sum += bucket.Value } } return sum }
[ "func", "(", "r", "*", "Number", ")", "Sum", "(", "now", "time", ".", "Time", ")", "float64", "{", "sum", ":=", "float64", "(", "0", ")", "\n", "r", ".", "Mutex", ".", "RLock", "(", ")", "\n", "defer", "r", ".", "Mutex", ".", "RUnlock", "(", ")", "\n", "for", "timestamp", ",", "bucket", ":=", "range", "r", ".", "Buckets", "{", "if", "timestamp", ">=", "now", ".", "Unix", "(", ")", "-", "10", "{", "sum", "+=", "bucket", ".", "Value", "\n", "}", "\n", "}", "\n", "return", "sum", "\n", "}" ]
// Sum sums the values over the buckets in the last 10 seconds.
[ "Sum", "sums", "the", "values", "over", "the", "buckets", "in", "the", "last", "10", "seconds", "." ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling.go#L79-L93
train
afex/hystrix-go
hystrix/rolling/rolling.go
Max
func (r *Number) Max(now time.Time) float64 { var max float64 r.Mutex.RLock() defer r.Mutex.RUnlock() for timestamp, bucket := range r.Buckets { // TODO: configurable rolling window if timestamp >= now.Unix()-10 { if bucket.Value > max { max = bucket.Value } } } return max }
go
func (r *Number) Max(now time.Time) float64 { var max float64 r.Mutex.RLock() defer r.Mutex.RUnlock() for timestamp, bucket := range r.Buckets { // TODO: configurable rolling window if timestamp >= now.Unix()-10 { if bucket.Value > max { max = bucket.Value } } } return max }
[ "func", "(", "r", "*", "Number", ")", "Max", "(", "now", "time", ".", "Time", ")", "float64", "{", "var", "max", "float64", "\n", "r", ".", "Mutex", ".", "RLock", "(", ")", "\n", "defer", "r", ".", "Mutex", ".", "RUnlock", "(", ")", "\n", "for", "timestamp", ",", "bucket", ":=", "range", "r", ".", "Buckets", "{", "if", "timestamp", ">=", "now", ".", "Unix", "(", ")", "-", "10", "{", "if", "bucket", ".", "Value", ">", "max", "{", "max", "=", "bucket", ".", "Value", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "max", "\n", "}" ]
// Max returns the maximum value seen in the last 10 seconds.
[ "Max", "returns", "the", "maximum", "value", "seen", "in", "the", "last", "10", "seconds", "." ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling.go#L96-L112
train
afex/hystrix-go
hystrix/hystrix.go
Go
func Go(name string, run runFunc, fallback fallbackFunc) chan error { runC := func(ctx context.Context) error { return run() } var fallbackC fallbackFuncC if fallback != nil { fallbackC = func(ctx context.Context, err error) error { return fallback(err) } } return GoC(context.Background(), name, runC, fallbackC) }
go
func Go(name string, run runFunc, fallback fallbackFunc) chan error { runC := func(ctx context.Context) error { return run() } var fallbackC fallbackFuncC if fallback != nil { fallbackC = func(ctx context.Context, err error) error { return fallback(err) } } return GoC(context.Background(), name, runC, fallbackC) }
[ "func", "Go", "(", "name", "string", ",", "run", "runFunc", ",", "fallback", "fallbackFunc", ")", "chan", "error", "{", "runC", ":=", "func", "(", "ctx", "context", ".", "Context", ")", "error", "{", "return", "run", "(", ")", "\n", "}", "\n", "var", "fallbackC", "fallbackFuncC", "\n", "if", "fallback", "!=", "nil", "{", "fallbackC", "=", "func", "(", "ctx", "context", ".", "Context", ",", "err", "error", ")", "error", "{", "return", "fallback", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "GoC", "(", "context", ".", "Background", "(", ")", ",", "name", ",", "runC", ",", "fallbackC", ")", "\n", "}" ]
// Go runs your function while tracking the health of previous calls to it. // If your function begins slowing down or failing repeatedly, we will block // new calls to it for you to give the dependent service time to repair. // // Define a fallback function if you want to define some code to execute during outages.
[ "Go", "runs", "your", "function", "while", "tracking", "the", "health", "of", "previous", "calls", "to", "it", ".", "If", "your", "function", "begins", "slowing", "down", "or", "failing", "repeatedly", "we", "will", "block", "new", "calls", "to", "it", "for", "you", "to", "give", "the", "dependent", "service", "time", "to", "repair", ".", "Define", "a", "fallback", "function", "if", "you", "want", "to", "define", "some", "code", "to", "execute", "during", "outages", "." ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/hystrix.go#L55-L66
train
afex/hystrix-go
hystrix/hystrix.go
DoC
func DoC(ctx context.Context, name string, run runFuncC, fallback fallbackFuncC) error { done := make(chan struct{}, 1) r := func(ctx context.Context) error { err := run(ctx) if err != nil { return err } done <- struct{}{} return nil } f := func(ctx context.Context, e error) error { err := fallback(ctx, e) if err != nil { return err } done <- struct{}{} return nil } var errChan chan error if fallback == nil { errChan = GoC(ctx, name, r, nil) } else { errChan = GoC(ctx, name, r, f) } select { case <-done: return nil case err := <-errChan: return err } }
go
func DoC(ctx context.Context, name string, run runFuncC, fallback fallbackFuncC) error { done := make(chan struct{}, 1) r := func(ctx context.Context) error { err := run(ctx) if err != nil { return err } done <- struct{}{} return nil } f := func(ctx context.Context, e error) error { err := fallback(ctx, e) if err != nil { return err } done <- struct{}{} return nil } var errChan chan error if fallback == nil { errChan = GoC(ctx, name, r, nil) } else { errChan = GoC(ctx, name, r, f) } select { case <-done: return nil case err := <-errChan: return err } }
[ "func", "DoC", "(", "ctx", "context", ".", "Context", ",", "name", "string", ",", "run", "runFuncC", ",", "fallback", "fallbackFuncC", ")", "error", "{", "done", ":=", "make", "(", "chan", "struct", "{", "}", ",", "1", ")", "\n", "r", ":=", "func", "(", "ctx", "context", ".", "Context", ")", "error", "{", "err", ":=", "run", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "done", "<-", "struct", "{", "}", "{", "}", "\n", "return", "nil", "\n", "}", "\n", "f", ":=", "func", "(", "ctx", "context", ".", "Context", ",", "e", "error", ")", "error", "{", "err", ":=", "fallback", "(", "ctx", ",", "e", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "done", "<-", "struct", "{", "}", "{", "}", "\n", "return", "nil", "\n", "}", "\n", "var", "errChan", "chan", "error", "\n", "if", "fallback", "==", "nil", "{", "errChan", "=", "GoC", "(", "ctx", ",", "name", ",", "r", ",", "nil", ")", "\n", "}", "else", "{", "errChan", "=", "GoC", "(", "ctx", ",", "name", ",", "r", ",", "f", ")", "\n", "}", "\n", "select", "{", "case", "<-", "done", ":", "return", "nil", "\n", "case", "err", ":=", "<-", "errChan", ":", "return", "err", "\n", "}", "\n", "}" ]
// DoC runs your function in a synchronous manner, blocking until either your function succeeds // or an error is returned, including hystrix circuit errors
[ "DoC", "runs", "your", "function", "in", "a", "synchronous", "manner", "blocking", "until", "either", "your", "function", "succeeds", "or", "an", "error", "is", "returned", "including", "hystrix", "circuit", "errors" ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/hystrix.go#L217-L253
train
afex/hystrix-go
hystrix/hystrix.go
errorWithFallback
func (c *command) errorWithFallback(ctx context.Context, err error) { eventType := "failure" if err == ErrCircuitOpen { eventType = "short-circuit" } else if err == ErrMaxConcurrency { eventType = "rejected" } else if err == ErrTimeout { eventType = "timeout" } else if err == context.Canceled { eventType = "context_canceled" } else if err == context.DeadlineExceeded { eventType = "context_deadline_exceeded" } c.reportEvent(eventType) fallbackErr := c.tryFallback(ctx, err) if fallbackErr != nil { c.errChan <- fallbackErr } }
go
func (c *command) errorWithFallback(ctx context.Context, err error) { eventType := "failure" if err == ErrCircuitOpen { eventType = "short-circuit" } else if err == ErrMaxConcurrency { eventType = "rejected" } else if err == ErrTimeout { eventType = "timeout" } else if err == context.Canceled { eventType = "context_canceled" } else if err == context.DeadlineExceeded { eventType = "context_deadline_exceeded" } c.reportEvent(eventType) fallbackErr := c.tryFallback(ctx, err) if fallbackErr != nil { c.errChan <- fallbackErr } }
[ "func", "(", "c", "*", "command", ")", "errorWithFallback", "(", "ctx", "context", ".", "Context", ",", "err", "error", ")", "{", "eventType", ":=", "\"failure\"", "\n", "if", "err", "==", "ErrCircuitOpen", "{", "eventType", "=", "\"short-circuit\"", "\n", "}", "else", "if", "err", "==", "ErrMaxConcurrency", "{", "eventType", "=", "\"rejected\"", "\n", "}", "else", "if", "err", "==", "ErrTimeout", "{", "eventType", "=", "\"timeout\"", "\n", "}", "else", "if", "err", "==", "context", ".", "Canceled", "{", "eventType", "=", "\"context_canceled\"", "\n", "}", "else", "if", "err", "==", "context", ".", "DeadlineExceeded", "{", "eventType", "=", "\"context_deadline_exceeded\"", "\n", "}", "\n", "c", ".", "reportEvent", "(", "eventType", ")", "\n", "fallbackErr", ":=", "c", ".", "tryFallback", "(", "ctx", ",", "err", ")", "\n", "if", "fallbackErr", "!=", "nil", "{", "c", ".", "errChan", "<-", "fallbackErr", "\n", "}", "\n", "}" ]
// errorWithFallback triggers the fallback while reporting the appropriate metric events.
[ "errorWithFallback", "triggers", "the", "fallback", "while", "reporting", "the", "appropriate", "metric", "events", "." ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/hystrix.go#L263-L282
train
afex/hystrix-go
hystrix/settings.go
Configure
func Configure(cmds map[string]CommandConfig) { for k, v := range cmds { ConfigureCommand(k, v) } }
go
func Configure(cmds map[string]CommandConfig) { for k, v := range cmds { ConfigureCommand(k, v) } }
[ "func", "Configure", "(", "cmds", "map", "[", "string", "]", "CommandConfig", ")", "{", "for", "k", ",", "v", ":=", "range", "cmds", "{", "ConfigureCommand", "(", "k", ",", "v", ")", "\n", "}", "\n", "}" ]
// Configure applies settings for a set of circuits
[ "Configure", "applies", "settings", "for", "a", "set", "of", "circuits" ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/settings.go#L51-L55
train
afex/hystrix-go
hystrix/settings.go
ConfigureCommand
func ConfigureCommand(name string, config CommandConfig) { settingsMutex.Lock() defer settingsMutex.Unlock() timeout := DefaultTimeout if config.Timeout != 0 { timeout = config.Timeout } max := DefaultMaxConcurrent if config.MaxConcurrentRequests != 0 { max = config.MaxConcurrentRequests } volume := DefaultVolumeThreshold if config.RequestVolumeThreshold != 0 { volume = config.RequestVolumeThreshold } sleep := DefaultSleepWindow if config.SleepWindow != 0 { sleep = config.SleepWindow } errorPercent := DefaultErrorPercentThreshold if config.ErrorPercentThreshold != 0 { errorPercent = config.ErrorPercentThreshold } circuitSettings[name] = &Settings{ Timeout: time.Duration(timeout) * time.Millisecond, MaxConcurrentRequests: max, RequestVolumeThreshold: uint64(volume), SleepWindow: time.Duration(sleep) * time.Millisecond, ErrorPercentThreshold: errorPercent, } }
go
func ConfigureCommand(name string, config CommandConfig) { settingsMutex.Lock() defer settingsMutex.Unlock() timeout := DefaultTimeout if config.Timeout != 0 { timeout = config.Timeout } max := DefaultMaxConcurrent if config.MaxConcurrentRequests != 0 { max = config.MaxConcurrentRequests } volume := DefaultVolumeThreshold if config.RequestVolumeThreshold != 0 { volume = config.RequestVolumeThreshold } sleep := DefaultSleepWindow if config.SleepWindow != 0 { sleep = config.SleepWindow } errorPercent := DefaultErrorPercentThreshold if config.ErrorPercentThreshold != 0 { errorPercent = config.ErrorPercentThreshold } circuitSettings[name] = &Settings{ Timeout: time.Duration(timeout) * time.Millisecond, MaxConcurrentRequests: max, RequestVolumeThreshold: uint64(volume), SleepWindow: time.Duration(sleep) * time.Millisecond, ErrorPercentThreshold: errorPercent, } }
[ "func", "ConfigureCommand", "(", "name", "string", ",", "config", "CommandConfig", ")", "{", "settingsMutex", ".", "Lock", "(", ")", "\n", "defer", "settingsMutex", ".", "Unlock", "(", ")", "\n", "timeout", ":=", "DefaultTimeout", "\n", "if", "config", ".", "Timeout", "!=", "0", "{", "timeout", "=", "config", ".", "Timeout", "\n", "}", "\n", "max", ":=", "DefaultMaxConcurrent", "\n", "if", "config", ".", "MaxConcurrentRequests", "!=", "0", "{", "max", "=", "config", ".", "MaxConcurrentRequests", "\n", "}", "\n", "volume", ":=", "DefaultVolumeThreshold", "\n", "if", "config", ".", "RequestVolumeThreshold", "!=", "0", "{", "volume", "=", "config", ".", "RequestVolumeThreshold", "\n", "}", "\n", "sleep", ":=", "DefaultSleepWindow", "\n", "if", "config", ".", "SleepWindow", "!=", "0", "{", "sleep", "=", "config", ".", "SleepWindow", "\n", "}", "\n", "errorPercent", ":=", "DefaultErrorPercentThreshold", "\n", "if", "config", ".", "ErrorPercentThreshold", "!=", "0", "{", "errorPercent", "=", "config", ".", "ErrorPercentThreshold", "\n", "}", "\n", "circuitSettings", "[", "name", "]", "=", "&", "Settings", "{", "Timeout", ":", "time", ".", "Duration", "(", "timeout", ")", "*", "time", ".", "Millisecond", ",", "MaxConcurrentRequests", ":", "max", ",", "RequestVolumeThreshold", ":", "uint64", "(", "volume", ")", ",", "SleepWindow", ":", "time", ".", "Duration", "(", "sleep", ")", "*", "time", ".", "Millisecond", ",", "ErrorPercentThreshold", ":", "errorPercent", ",", "}", "\n", "}" ]
// ConfigureCommand applies settings for a circuit
[ "ConfigureCommand", "applies", "settings", "for", "a", "circuit" ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/settings.go#L58-L94
train
afex/hystrix-go
hystrix/metric_collector/default_metric_collector.go
NumRequests
func (d *DefaultMetricCollector) NumRequests() *rolling.Number { d.mutex.RLock() defer d.mutex.RUnlock() return d.numRequests }
go
func (d *DefaultMetricCollector) NumRequests() *rolling.Number { d.mutex.RLock() defer d.mutex.RUnlock() return d.numRequests }
[ "func", "(", "d", "*", "DefaultMetricCollector", ")", "NumRequests", "(", ")", "*", "rolling", ".", "Number", "{", "d", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "d", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "return", "d", ".", "numRequests", "\n", "}" ]
// NumRequests returns the rolling number of requests
[ "NumRequests", "returns", "the", "rolling", "number", "of", "requests" ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L43-L47
train
afex/hystrix-go
hystrix/metric_collector/default_metric_collector.go
Errors
func (d *DefaultMetricCollector) Errors() *rolling.Number { d.mutex.RLock() defer d.mutex.RUnlock() return d.errors }
go
func (d *DefaultMetricCollector) Errors() *rolling.Number { d.mutex.RLock() defer d.mutex.RUnlock() return d.errors }
[ "func", "(", "d", "*", "DefaultMetricCollector", ")", "Errors", "(", ")", "*", "rolling", ".", "Number", "{", "d", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "d", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "return", "d", ".", "errors", "\n", "}" ]
// Errors returns the rolling number of errors
[ "Errors", "returns", "the", "rolling", "number", "of", "errors" ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L50-L54
train
afex/hystrix-go
hystrix/metric_collector/default_metric_collector.go
Successes
func (d *DefaultMetricCollector) Successes() *rolling.Number { d.mutex.RLock() defer d.mutex.RUnlock() return d.successes }
go
func (d *DefaultMetricCollector) Successes() *rolling.Number { d.mutex.RLock() defer d.mutex.RUnlock() return d.successes }
[ "func", "(", "d", "*", "DefaultMetricCollector", ")", "Successes", "(", ")", "*", "rolling", ".", "Number", "{", "d", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "d", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "return", "d", ".", "successes", "\n", "}" ]
// Successes returns the rolling number of successes
[ "Successes", "returns", "the", "rolling", "number", "of", "successes" ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L57-L61
train
afex/hystrix-go
hystrix/metric_collector/default_metric_collector.go
Failures
func (d *DefaultMetricCollector) Failures() *rolling.Number { d.mutex.RLock() defer d.mutex.RUnlock() return d.failures }
go
func (d *DefaultMetricCollector) Failures() *rolling.Number { d.mutex.RLock() defer d.mutex.RUnlock() return d.failures }
[ "func", "(", "d", "*", "DefaultMetricCollector", ")", "Failures", "(", ")", "*", "rolling", ".", "Number", "{", "d", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "d", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "return", "d", ".", "failures", "\n", "}" ]
// Failures returns the rolling number of failures
[ "Failures", "returns", "the", "rolling", "number", "of", "failures" ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L64-L68
train
afex/hystrix-go
hystrix/metric_collector/default_metric_collector.go
Rejects
func (d *DefaultMetricCollector) Rejects() *rolling.Number { d.mutex.RLock() defer d.mutex.RUnlock() return d.rejects }
go
func (d *DefaultMetricCollector) Rejects() *rolling.Number { d.mutex.RLock() defer d.mutex.RUnlock() return d.rejects }
[ "func", "(", "d", "*", "DefaultMetricCollector", ")", "Rejects", "(", ")", "*", "rolling", ".", "Number", "{", "d", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "d", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "return", "d", ".", "rejects", "\n", "}" ]
// Rejects returns the rolling number of rejects
[ "Rejects", "returns", "the", "rolling", "number", "of", "rejects" ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L71-L75
train
afex/hystrix-go
hystrix/metric_collector/default_metric_collector.go
ShortCircuits
func (d *DefaultMetricCollector) ShortCircuits() *rolling.Number { d.mutex.RLock() defer d.mutex.RUnlock() return d.shortCircuits }
go
func (d *DefaultMetricCollector) ShortCircuits() *rolling.Number { d.mutex.RLock() defer d.mutex.RUnlock() return d.shortCircuits }
[ "func", "(", "d", "*", "DefaultMetricCollector", ")", "ShortCircuits", "(", ")", "*", "rolling", ".", "Number", "{", "d", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "d", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "return", "d", ".", "shortCircuits", "\n", "}" ]
// ShortCircuits returns the rolling number of short circuits
[ "ShortCircuits", "returns", "the", "rolling", "number", "of", "short", "circuits" ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L78-L82
train
afex/hystrix-go
hystrix/metric_collector/default_metric_collector.go
Timeouts
func (d *DefaultMetricCollector) Timeouts() *rolling.Number { d.mutex.RLock() defer d.mutex.RUnlock() return d.timeouts }
go
func (d *DefaultMetricCollector) Timeouts() *rolling.Number { d.mutex.RLock() defer d.mutex.RUnlock() return d.timeouts }
[ "func", "(", "d", "*", "DefaultMetricCollector", ")", "Timeouts", "(", ")", "*", "rolling", ".", "Number", "{", "d", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "d", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "return", "d", ".", "timeouts", "\n", "}" ]
// Timeouts returns the rolling number of timeouts
[ "Timeouts", "returns", "the", "rolling", "number", "of", "timeouts" ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L85-L89
train
afex/hystrix-go
hystrix/metric_collector/default_metric_collector.go
FallbackSuccesses
func (d *DefaultMetricCollector) FallbackSuccesses() *rolling.Number { d.mutex.RLock() defer d.mutex.RUnlock() return d.fallbackSuccesses }
go
func (d *DefaultMetricCollector) FallbackSuccesses() *rolling.Number { d.mutex.RLock() defer d.mutex.RUnlock() return d.fallbackSuccesses }
[ "func", "(", "d", "*", "DefaultMetricCollector", ")", "FallbackSuccesses", "(", ")", "*", "rolling", ".", "Number", "{", "d", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "d", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "return", "d", ".", "fallbackSuccesses", "\n", "}" ]
// FallbackSuccesses returns the rolling number of fallback successes
[ "FallbackSuccesses", "returns", "the", "rolling", "number", "of", "fallback", "successes" ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L92-L96
train
afex/hystrix-go
hystrix/metric_collector/default_metric_collector.go
FallbackFailures
func (d *DefaultMetricCollector) FallbackFailures() *rolling.Number { d.mutex.RLock() defer d.mutex.RUnlock() return d.fallbackFailures }
go
func (d *DefaultMetricCollector) FallbackFailures() *rolling.Number { d.mutex.RLock() defer d.mutex.RUnlock() return d.fallbackFailures }
[ "func", "(", "d", "*", "DefaultMetricCollector", ")", "FallbackFailures", "(", ")", "*", "rolling", ".", "Number", "{", "d", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "d", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "return", "d", ".", "fallbackFailures", "\n", "}" ]
// FallbackFailures returns the rolling number of fallback failures
[ "FallbackFailures", "returns", "the", "rolling", "number", "of", "fallback", "failures" ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L111-L115
train
afex/hystrix-go
hystrix/metric_collector/default_metric_collector.go
TotalDuration
func (d *DefaultMetricCollector) TotalDuration() *rolling.Timing { d.mutex.RLock() defer d.mutex.RUnlock() return d.totalDuration }
go
func (d *DefaultMetricCollector) TotalDuration() *rolling.Timing { d.mutex.RLock() defer d.mutex.RUnlock() return d.totalDuration }
[ "func", "(", "d", "*", "DefaultMetricCollector", ")", "TotalDuration", "(", ")", "*", "rolling", ".", "Timing", "{", "d", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "d", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "return", "d", ".", "totalDuration", "\n", "}" ]
// TotalDuration returns the rolling total duration
[ "TotalDuration", "returns", "the", "rolling", "total", "duration" ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L118-L122
train
afex/hystrix-go
hystrix/metric_collector/default_metric_collector.go
RunDuration
func (d *DefaultMetricCollector) RunDuration() *rolling.Timing { d.mutex.RLock() defer d.mutex.RUnlock() return d.runDuration }
go
func (d *DefaultMetricCollector) RunDuration() *rolling.Timing { d.mutex.RLock() defer d.mutex.RUnlock() return d.runDuration }
[ "func", "(", "d", "*", "DefaultMetricCollector", ")", "RunDuration", "(", ")", "*", "rolling", ".", "Timing", "{", "d", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "d", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "return", "d", ".", "runDuration", "\n", "}" ]
// RunDuration returns the rolling run duration
[ "RunDuration", "returns", "the", "rolling", "run", "duration" ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L125-L129
train
afex/hystrix-go
hystrix/metric_collector/default_metric_collector.go
Reset
func (d *DefaultMetricCollector) Reset() { d.mutex.Lock() defer d.mutex.Unlock() d.numRequests = rolling.NewNumber() d.errors = rolling.NewNumber() d.successes = rolling.NewNumber() d.rejects = rolling.NewNumber() d.shortCircuits = rolling.NewNumber() d.failures = rolling.NewNumber() d.timeouts = rolling.NewNumber() d.fallbackSuccesses = rolling.NewNumber() d.fallbackFailures = rolling.NewNumber() d.contextCanceled = rolling.NewNumber() d.contextDeadlineExceeded = rolling.NewNumber() d.totalDuration = rolling.NewTiming() d.runDuration = rolling.NewTiming() }
go
func (d *DefaultMetricCollector) Reset() { d.mutex.Lock() defer d.mutex.Unlock() d.numRequests = rolling.NewNumber() d.errors = rolling.NewNumber() d.successes = rolling.NewNumber() d.rejects = rolling.NewNumber() d.shortCircuits = rolling.NewNumber() d.failures = rolling.NewNumber() d.timeouts = rolling.NewNumber() d.fallbackSuccesses = rolling.NewNumber() d.fallbackFailures = rolling.NewNumber() d.contextCanceled = rolling.NewNumber() d.contextDeadlineExceeded = rolling.NewNumber() d.totalDuration = rolling.NewTiming() d.runDuration = rolling.NewTiming() }
[ "func", "(", "d", "*", "DefaultMetricCollector", ")", "Reset", "(", ")", "{", "d", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "d", ".", "mutex", ".", "Unlock", "(", ")", "\n", "d", ".", "numRequests", "=", "rolling", ".", "NewNumber", "(", ")", "\n", "d", ".", "errors", "=", "rolling", ".", "NewNumber", "(", ")", "\n", "d", ".", "successes", "=", "rolling", ".", "NewNumber", "(", ")", "\n", "d", ".", "rejects", "=", "rolling", ".", "NewNumber", "(", ")", "\n", "d", ".", "shortCircuits", "=", "rolling", ".", "NewNumber", "(", ")", "\n", "d", ".", "failures", "=", "rolling", ".", "NewNumber", "(", ")", "\n", "d", ".", "timeouts", "=", "rolling", ".", "NewNumber", "(", ")", "\n", "d", ".", "fallbackSuccesses", "=", "rolling", ".", "NewNumber", "(", ")", "\n", "d", ".", "fallbackFailures", "=", "rolling", ".", "NewNumber", "(", ")", "\n", "d", ".", "contextCanceled", "=", "rolling", ".", "NewNumber", "(", ")", "\n", "d", ".", "contextDeadlineExceeded", "=", "rolling", ".", "NewNumber", "(", ")", "\n", "d", ".", "totalDuration", "=", "rolling", ".", "NewTiming", "(", ")", "\n", "d", ".", "runDuration", "=", "rolling", ".", "NewTiming", "(", ")", "\n", "}" ]
// Reset resets all metrics in this collector to 0.
[ "Reset", "resets", "all", "metrics", "in", "this", "collector", "to", "0", "." ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L152-L169
train
afex/hystrix-go
hystrix/rolling/rolling_timing.go
NewTiming
func NewTiming() *Timing { r := &Timing{ Buckets: make(map[int64]*timingBucket), Mutex: &sync.RWMutex{}, } return r }
go
func NewTiming() *Timing { r := &Timing{ Buckets: make(map[int64]*timingBucket), Mutex: &sync.RWMutex{}, } return r }
[ "func", "NewTiming", "(", ")", "*", "Timing", "{", "r", ":=", "&", "Timing", "{", "Buckets", ":", "make", "(", "map", "[", "int64", "]", "*", "timingBucket", ")", ",", "Mutex", ":", "&", "sync", ".", "RWMutex", "{", "}", ",", "}", "\n", "return", "r", "\n", "}" ]
// NewTiming creates a RollingTiming struct.
[ "NewTiming", "creates", "a", "RollingTiming", "struct", "." ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling_timing.go#L26-L32
train
afex/hystrix-go
hystrix/rolling/rolling_timing.go
SortedDurations
func (r *Timing) SortedDurations() []time.Duration { r.Mutex.RLock() t := r.LastCachedTime r.Mutex.RUnlock() if t+time.Duration(1*time.Second).Nanoseconds() > time.Now().UnixNano() { // don't recalculate if current cache is still fresh return r.CachedSortedDurations } var durations byDuration now := time.Now() r.Mutex.Lock() defer r.Mutex.Unlock() for timestamp, b := range r.Buckets { // TODO: configurable rolling window if timestamp >= now.Unix()-60 { for _, d := range b.Durations { durations = append(durations, d) } } } sort.Sort(durations) r.CachedSortedDurations = durations r.LastCachedTime = time.Now().UnixNano() return r.CachedSortedDurations }
go
func (r *Timing) SortedDurations() []time.Duration { r.Mutex.RLock() t := r.LastCachedTime r.Mutex.RUnlock() if t+time.Duration(1*time.Second).Nanoseconds() > time.Now().UnixNano() { // don't recalculate if current cache is still fresh return r.CachedSortedDurations } var durations byDuration now := time.Now() r.Mutex.Lock() defer r.Mutex.Unlock() for timestamp, b := range r.Buckets { // TODO: configurable rolling window if timestamp >= now.Unix()-60 { for _, d := range b.Durations { durations = append(durations, d) } } } sort.Sort(durations) r.CachedSortedDurations = durations r.LastCachedTime = time.Now().UnixNano() return r.CachedSortedDurations }
[ "func", "(", "r", "*", "Timing", ")", "SortedDurations", "(", ")", "[", "]", "time", ".", "Duration", "{", "r", ".", "Mutex", ".", "RLock", "(", ")", "\n", "t", ":=", "r", ".", "LastCachedTime", "\n", "r", ".", "Mutex", ".", "RUnlock", "(", ")", "\n", "if", "t", "+", "time", ".", "Duration", "(", "1", "*", "time", ".", "Second", ")", ".", "Nanoseconds", "(", ")", ">", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", "{", "return", "r", ".", "CachedSortedDurations", "\n", "}", "\n", "var", "durations", "byDuration", "\n", "now", ":=", "time", ".", "Now", "(", ")", "\n", "r", ".", "Mutex", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "Mutex", ".", "Unlock", "(", ")", "\n", "for", "timestamp", ",", "b", ":=", "range", "r", ".", "Buckets", "{", "if", "timestamp", ">=", "now", ".", "Unix", "(", ")", "-", "60", "{", "for", "_", ",", "d", ":=", "range", "b", ".", "Durations", "{", "durations", "=", "append", "(", "durations", ",", "d", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "sort", ".", "Sort", "(", "durations", ")", "\n", "r", ".", "CachedSortedDurations", "=", "durations", "\n", "r", ".", "LastCachedTime", "=", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", "\n", "return", "r", ".", "CachedSortedDurations", "\n", "}" ]
// SortedDurations returns an array of time.Duration sorted from shortest // to longest that have occurred in the last 60 seconds.
[ "SortedDurations", "returns", "an", "array", "of", "time", ".", "Duration", "sorted", "from", "shortest", "to", "longest", "that", "have", "occurred", "in", "the", "last", "60", "seconds", "." ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling_timing.go#L42-L73
train
afex/hystrix-go
hystrix/rolling/rolling_timing.go
Add
func (r *Timing) Add(duration time.Duration) { b := r.getCurrentBucket() r.Mutex.Lock() defer r.Mutex.Unlock() b.Durations = append(b.Durations, duration) r.removeOldBuckets() }
go
func (r *Timing) Add(duration time.Duration) { b := r.getCurrentBucket() r.Mutex.Lock() defer r.Mutex.Unlock() b.Durations = append(b.Durations, duration) r.removeOldBuckets() }
[ "func", "(", "r", "*", "Timing", ")", "Add", "(", "duration", "time", ".", "Duration", ")", "{", "b", ":=", "r", ".", "getCurrentBucket", "(", ")", "\n", "r", ".", "Mutex", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "Mutex", ".", "Unlock", "(", ")", "\n", "b", ".", "Durations", "=", "append", "(", "b", ".", "Durations", ",", "duration", ")", "\n", "r", ".", "removeOldBuckets", "(", ")", "\n", "}" ]
// Add appends the time.Duration given to the current time bucket.
[ "Add", "appends", "the", "time", ".", "Duration", "given", "to", "the", "current", "time", "bucket", "." ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling_timing.go#L104-L112
train
afex/hystrix-go
hystrix/rolling/rolling_timing.go
Percentile
func (r *Timing) Percentile(p float64) uint32 { sortedDurations := r.SortedDurations() length := len(sortedDurations) if length <= 0 { return 0 } pos := r.ordinal(len(sortedDurations), p) - 1 return uint32(sortedDurations[pos].Nanoseconds() / 1000000) }
go
func (r *Timing) Percentile(p float64) uint32 { sortedDurations := r.SortedDurations() length := len(sortedDurations) if length <= 0 { return 0 } pos := r.ordinal(len(sortedDurations), p) - 1 return uint32(sortedDurations[pos].Nanoseconds() / 1000000) }
[ "func", "(", "r", "*", "Timing", ")", "Percentile", "(", "p", "float64", ")", "uint32", "{", "sortedDurations", ":=", "r", ".", "SortedDurations", "(", ")", "\n", "length", ":=", "len", "(", "sortedDurations", ")", "\n", "if", "length", "<=", "0", "{", "return", "0", "\n", "}", "\n", "pos", ":=", "r", ".", "ordinal", "(", "len", "(", "sortedDurations", ")", ",", "p", ")", "-", "1", "\n", "return", "uint32", "(", "sortedDurations", "[", "pos", "]", ".", "Nanoseconds", "(", ")", "/", "1000000", ")", "\n", "}" ]
// Percentile computes the percentile given with a linear interpolation.
[ "Percentile", "computes", "the", "percentile", "given", "with", "a", "linear", "interpolation", "." ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling_timing.go#L115-L124
train
afex/hystrix-go
hystrix/rolling/rolling_timing.go
Mean
func (r *Timing) Mean() uint32 { sortedDurations := r.SortedDurations() var sum time.Duration for _, d := range sortedDurations { sum += d } length := int64(len(sortedDurations)) if length == 0 { return 0 } return uint32(sum.Nanoseconds()/length) / 1000000 }
go
func (r *Timing) Mean() uint32 { sortedDurations := r.SortedDurations() var sum time.Duration for _, d := range sortedDurations { sum += d } length := int64(len(sortedDurations)) if length == 0 { return 0 } return uint32(sum.Nanoseconds()/length) / 1000000 }
[ "func", "(", "r", "*", "Timing", ")", "Mean", "(", ")", "uint32", "{", "sortedDurations", ":=", "r", ".", "SortedDurations", "(", ")", "\n", "var", "sum", "time", ".", "Duration", "\n", "for", "_", ",", "d", ":=", "range", "sortedDurations", "{", "sum", "+=", "d", "\n", "}", "\n", "length", ":=", "int64", "(", "len", "(", "sortedDurations", ")", ")", "\n", "if", "length", "==", "0", "{", "return", "0", "\n", "}", "\n", "return", "uint32", "(", "sum", ".", "Nanoseconds", "(", ")", "/", "length", ")", "/", "1000000", "\n", "}" ]
// Mean computes the average timing in the last 60 seconds.
[ "Mean", "computes", "the", "average", "timing", "in", "the", "last", "60", "seconds", "." ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling_timing.go#L135-L148
train
afex/hystrix-go
hystrix/metrics.go
DefaultCollector
func (m *metricExchange) DefaultCollector() *metricCollector.DefaultMetricCollector { if len(m.metricCollectors) < 1 { panic("No Metric Collectors Registered.") } collection, ok := m.metricCollectors[0].(*metricCollector.DefaultMetricCollector) if !ok { panic("Default metric collector is not registered correctly. The default metric collector must be registered first.") } return collection }
go
func (m *metricExchange) DefaultCollector() *metricCollector.DefaultMetricCollector { if len(m.metricCollectors) < 1 { panic("No Metric Collectors Registered.") } collection, ok := m.metricCollectors[0].(*metricCollector.DefaultMetricCollector) if !ok { panic("Default metric collector is not registered correctly. The default metric collector must be registered first.") } return collection }
[ "func", "(", "m", "*", "metricExchange", ")", "DefaultCollector", "(", ")", "*", "metricCollector", ".", "DefaultMetricCollector", "{", "if", "len", "(", "m", ".", "metricCollectors", ")", "<", "1", "{", "panic", "(", "\"No Metric Collectors Registered.\"", ")", "\n", "}", "\n", "collection", ",", "ok", ":=", "m", ".", "metricCollectors", "[", "0", "]", ".", "(", "*", "metricCollector", ".", "DefaultMetricCollector", ")", "\n", "if", "!", "ok", "{", "panic", "(", "\"Default metric collector is not registered correctly. The default metric collector must be registered first.\"", ")", "\n", "}", "\n", "return", "collection", "\n", "}" ]
// The Default Collector function will panic if collectors are not setup to specification.
[ "The", "Default", "Collector", "function", "will", "panic", "if", "collectors", "are", "not", "setup", "to", "specification", "." ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metrics.go#L41-L50
train
afex/hystrix-go
hystrix/eventstream.go
Start
func (sh *StreamHandler) Start() { sh.requests = make(map[*http.Request]chan []byte) sh.done = make(chan struct{}) go sh.loop() }
go
func (sh *StreamHandler) Start() { sh.requests = make(map[*http.Request]chan []byte) sh.done = make(chan struct{}) go sh.loop() }
[ "func", "(", "sh", "*", "StreamHandler", ")", "Start", "(", ")", "{", "sh", ".", "requests", "=", "make", "(", "map", "[", "*", "http", ".", "Request", "]", "chan", "[", "]", "byte", ")", "\n", "sh", ".", "done", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "go", "sh", ".", "loop", "(", ")", "\n", "}" ]
// Start begins watching the in-memory circuit breakers for metrics
[ "Start", "begins", "watching", "the", "in", "-", "memory", "circuit", "breakers", "for", "metrics" ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/eventstream.go#L30-L34
train
afex/hystrix-go
hystrix/metric_collector/metric_collector.go
InitializeMetricCollectors
func (m *metricCollectorRegistry) InitializeMetricCollectors(name string) []MetricCollector { m.lock.RLock() defer m.lock.RUnlock() metrics := make([]MetricCollector, len(m.registry)) for i, metricCollectorInitializer := range m.registry { metrics[i] = metricCollectorInitializer(name) } return metrics }
go
func (m *metricCollectorRegistry) InitializeMetricCollectors(name string) []MetricCollector { m.lock.RLock() defer m.lock.RUnlock() metrics := make([]MetricCollector, len(m.registry)) for i, metricCollectorInitializer := range m.registry { metrics[i] = metricCollectorInitializer(name) } return metrics }
[ "func", "(", "m", "*", "metricCollectorRegistry", ")", "InitializeMetricCollectors", "(", "name", "string", ")", "[", "]", "MetricCollector", "{", "m", ".", "lock", ".", "RLock", "(", ")", "\n", "defer", "m", ".", "lock", ".", "RUnlock", "(", ")", "\n", "metrics", ":=", "make", "(", "[", "]", "MetricCollector", ",", "len", "(", "m", ".", "registry", ")", ")", "\n", "for", "i", ",", "metricCollectorInitializer", ":=", "range", "m", ".", "registry", "{", "metrics", "[", "i", "]", "=", "metricCollectorInitializer", "(", "name", ")", "\n", "}", "\n", "return", "metrics", "\n", "}" ]
// InitializeMetricCollectors runs the registried MetricCollector Initializers to create an array of MetricCollectors.
[ "InitializeMetricCollectors", "runs", "the", "registried", "MetricCollector", "Initializers", "to", "create", "an", "array", "of", "MetricCollectors", "." ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/metric_collector.go#L23-L32
train
afex/hystrix-go
hystrix/metric_collector/metric_collector.go
Register
func (m *metricCollectorRegistry) Register(initMetricCollector func(string) MetricCollector) { m.lock.Lock() defer m.lock.Unlock() m.registry = append(m.registry, initMetricCollector) }
go
func (m *metricCollectorRegistry) Register(initMetricCollector func(string) MetricCollector) { m.lock.Lock() defer m.lock.Unlock() m.registry = append(m.registry, initMetricCollector) }
[ "func", "(", "m", "*", "metricCollectorRegistry", ")", "Register", "(", "initMetricCollector", "func", "(", "string", ")", "MetricCollector", ")", "{", "m", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "lock", ".", "Unlock", "(", ")", "\n", "m", ".", "registry", "=", "append", "(", "m", ".", "registry", ",", "initMetricCollector", ")", "\n", "}" ]
// Register places a MetricCollector Initializer in the registry maintained by this metricCollectorRegistry.
[ "Register", "places", "a", "MetricCollector", "Initializer", "in", "the", "registry", "maintained", "by", "this", "metricCollectorRegistry", "." ]
fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a
https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/metric_collector.go#L35-L40
train