repo stringlengths 5 67 | sha stringlengths 40 40 | path stringlengths 4 234 | url stringlengths 85 339 | language stringclasses 6 values | split stringclasses 3 values | doc stringlengths 3 51.2k | sign stringlengths 5 8.01k | problem stringlengths 13 51.2k | output stringlengths 0 3.87M |
|---|---|---|---|---|---|---|---|---|---|
xtaci/kcp-go | 88b8a1475ba14b58f41457c9c89b5ccd919f1c24 | crypt.go | https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/crypt.go#L166-L174 | go | train | // NewAESBlockCrypt https://en.wikipedia.org/wiki/Advanced_Encryption_Standard | func NewAESBlockCrypt(key []byte) (BlockCrypt, error) | // NewAESBlockCrypt https://en.wikipedia.org/wiki/Advanced_Encryption_Standard
func NewAESBlockCrypt(key []byte) (BlockCrypt, error) | {
c := new(aesBlockCrypt)
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
c.block = block
return c, nil
} |
xtaci/kcp-go | 88b8a1475ba14b58f41457c9c89b5ccd919f1c24 | crypt.go | https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/crypt.go#L186-L194 | go | train | // NewTEABlockCrypt https://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm | func NewTEABlockCrypt(key []byte) (BlockCrypt, error) | // NewTEABlockCrypt https://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm
func NewTEABlockCrypt(key []byte) (BlockCrypt, error) | {
c := new(teaBlockCrypt)
block, err := tea.NewCipherWithRounds(key, 16)
if err != nil {
return nil, err
}
c.block = block
return c, nil
} |
xtaci/kcp-go | 88b8a1475ba14b58f41457c9c89b5ccd919f1c24 | crypt.go | https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/crypt.go#L206-L214 | go | train | // NewXTEABlockCrypt https://en.wikipedia.org/wiki/XTEA | func NewXTEABlockCrypt(key []byte) (BlockCrypt, error) | // NewXTEABlockCrypt https://en.wikipedia.org/wiki/XTEA
func NewXTEABlockCrypt(key []byte) (BlockCrypt, error) | {
c := new(xteaBlockCrypt)
block, err := xtea.NewCipher(key)
if err != nil {
return nil, err
}
c.block = block
return c, nil
} |
xtaci/kcp-go | 88b8a1475ba14b58f41457c9c89b5ccd919f1c24 | crypt.go | https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/crypt.go#L224-L228 | go | train | // NewSimpleXORBlockCrypt simple xor with key expanding | func NewSimpleXORBlockCrypt(key []byte) (BlockCrypt, error) | // NewSimpleXORBlockCrypt simple xor with key expanding
func NewSimpleXORBlockCrypt(key []byte) (BlockCrypt, error) | {
c := new(simpleXORBlockCrypt)
c.xortbl = pbkdf2.Key(key, []byte(saltxor), 32, mtuLimit, sha1.New)
return c, nil
} |
xtaci/kcp-go | 88b8a1475ba14b58f41457c9c89b5ccd919f1c24 | crypt.go | https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/crypt.go#L244-L253 | go | train | // packet encryption with local CFB mode | func encrypt(block cipher.Block, dst, src, buf []byte) | // packet encryption with local CFB mode
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)
}
} |
xtaci/kcp-go | 88b8a1475ba14b58f41457c9c89b5ccd919f1c24 | crypt.go | https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/crypt.go#L505-L514 | go | train | // decryption | func decrypt(block cipher.Block, dst, src, buf []byte) | // decryption
func decrypt(block cipher.Block, dst, src, buf []byte) | {
switch block.BlockSize() {
case 8:
decrypt8(block, dst, src, buf)
case 16:
decrypt16(block, dst, src, buf)
default:
decryptVariant(block, dst, src, buf)
}
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | addr.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/addr.go#L34-L40 | go | train | // LocalAddr is used to get the local address of the
// underlying connection. | func (s *Session) LocalAddr() net.Addr | // LocalAddr is used to get the local address of the
// underlying connection.
func (s *Session) LocalAddr() net.Addr | {
addr, ok := s.conn.(hasAddr)
if !ok {
return &yamuxAddr{"local"}
}
return addr.LocalAddr()
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | stream.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L56-L73 | go | train | // newStream is used to construct a new stream within
// a given session for an ID | func newStream(session *Session, id uint32, state streamState) *Stream | // newStream is used to construct a new stream within
// a given session for an ID
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
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | stream.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L86-L142 | go | train | // Read is used to read from the stream | func (s *Stream) Read(b []byte) (n int, err error) | // Read is used to read from the stream
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
}
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | stream.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L145-L157 | go | train | // Write is used to write to the stream | func (s *Stream) Write(b []byte) (n int, err error) | // Write is used to write to the stream
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
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | stream.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L161-L218 | go | train | // write is used to write to the stream, may return on
// a short write. | func (s *Stream) write(b []byte) (n int, err error) | // write is used to write to the stream, may return on
// a short 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
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | stream.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L222-L235 | go | train | // sendFlags determines any flags that are appropriate
// based on the current stream state | func (s *Stream) sendFlags() uint16 | // sendFlags determines any flags that are appropriate
// based on the current stream state
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
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | stream.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L239-L271 | go | train | // sendWindowUpdate potentially sends a window update enabling
// further writes to take place. Must be invoked with the lock. | func (s *Stream) sendWindowUpdate() error | // sendWindowUpdate potentially sends a window update enabling
// further writes to take place. Must be invoked with the lock.
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
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | stream.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L274-L285 | go | train | // sendClose is used to send a FIN | func (s *Stream) sendClose() error | // sendClose is used to send a FIN
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
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | stream.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L288-L322 | go | train | // Close is used to close the stream | func (s *Stream) Close() error | // Close is used to close the stream
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
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | stream.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L325-L330 | go | train | // forceClose is used for when the session is exiting | func (s *Stream) forceClose() | // forceClose is used for when the session is exiting
func (s *Stream) forceClose() | {
s.stateLock.Lock()
s.state = streamClosed
s.stateLock.Unlock()
s.notifyWaiting()
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | stream.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L334-L375 | go | train | // processFlags is used to update the state of the stream
// based on set flags, if any. Lock must be held | func (s *Stream) processFlags(flags uint16) error | // processFlags is used to update the state of the stream
// based on set flags, if any. Lock must be held
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
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | stream.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L384-L393 | go | train | // incrSendWindow updates the size of our send window | func (s *Stream) incrSendWindow(hdr header, flags uint16) error | // incrSendWindow updates the size of our send window
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
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | stream.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L396-L436 | go | train | // readData is used to handle a data frame | func (s *Stream) readData(hdr header, flags uint16, conn io.Reader) error | // readData is used to handle a data frame
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
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | stream.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L439-L447 | go | train | // SetDeadline sets the read and write deadlines | func (s *Stream) SetDeadline(t time.Time) error | // SetDeadline sets the read and write deadlines
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
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | stream.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L450-L453 | go | train | // SetReadDeadline sets the deadline for future Read calls. | func (s *Stream) SetReadDeadline(t time.Time) error | // SetReadDeadline sets the deadline for future Read calls.
func (s *Stream) SetReadDeadline(t time.Time) error | {
s.readDeadline.Store(t)
return nil
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | stream.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L456-L459 | go | train | // SetWriteDeadline sets the deadline for future Write calls | func (s *Stream) SetWriteDeadline(t time.Time) error | // SetWriteDeadline sets the deadline for future Write calls
func (s *Stream) SetWriteDeadline(t time.Time) error | {
s.writeDeadline.Store(t)
return nil
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | stream.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L464-L470 | go | train | // 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. | func (s *Stream) Shrink() | // 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.
func (s *Stream) Shrink() | {
s.recvLock.Lock()
if s.recvBuf != nil && s.recvBuf.Len() == 0 {
s.recvBuf = nil
}
s.recvLock.Unlock()
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | mux.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/mux.go#L44-L53 | go | train | // DefaultConfig is used to return a default configuration | func DefaultConfig() *Config | // DefaultConfig is used to return a default configuration
func DefaultConfig() *Config | {
return &Config{
AcceptBacklog: 256,
EnableKeepAlive: true,
KeepAliveInterval: 30 * time.Second,
ConnectionWriteTimeout: 10 * time.Second,
MaxStreamWindowSize: initialStreamWindow,
LogOutput: os.Stderr,
}
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | mux.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/mux.go#L56-L72 | go | train | // VerifyConfig is used to verify the sanity of configuration | func VerifyConfig(config *Config) error | // VerifyConfig is used to verify the sanity of configuration
func VerifyConfig(config *Config) error | {
if config.AcceptBacklog <= 0 {
return fmt.Errorf("backlog must be positive")
}
if config.KeepAliveInterval == 0 {
return fmt.Errorf("keep-alive interval must be positive")
}
if config.MaxStreamWindowSize < initialStreamWindow {
return fmt.Errorf("MaxStreamWindowSize must be larger than %d", initialStreamWindow)
}
if config.LogOutput != nil && config.Logger != nil {
return fmt.Errorf("both Logger and LogOutput may not be set, select one")
} else if config.LogOutput == nil && config.Logger == nil {
return fmt.Errorf("one of Logger or LogOutput must be set, select one")
}
return nil
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | mux.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/mux.go#L77-L85 | go | train | // 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. | func Server(conn io.ReadWriteCloser, config *Config) (*Session, error) | // 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.
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
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | mux.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/mux.go#L89-L98 | go | train | // Client is used to initialize a new client-side connection.
// There must be at most one client-side connection. | func Client(conn io.ReadWriteCloser, config *Config) (*Session, error) | // Client is used to initialize a new client-side connection.
// There must be at most one client-side connection.
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
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | session.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L88-L119 | go | train | // newSession is used to construct a new session | func newSession(config *Config, conn io.ReadWriteCloser, client bool) *Session | // newSession is used to construct a new session
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
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | session.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L138-L143 | go | train | // NumStreams returns the number of currently open streams | func (s *Session) NumStreams() int | // NumStreams returns the number of currently open streams
func (s *Session) NumStreams() int | {
s.streamLock.Lock()
num := len(s.streams)
s.streamLock.Unlock()
return num
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | session.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L146-L152 | go | train | // Open is used to create a new stream as a net.Conn | func (s *Session) Open() (net.Conn, error) | // Open is used to create a new stream as a net.Conn
func (s *Session) Open() (net.Conn, error) | {
conn, err := s.OpenStream()
if err != nil {
return nil, err
}
return conn, nil
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | session.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L155-L197 | go | train | // OpenStream is used to create a new stream | func (s *Session) OpenStream() (*Stream, error) | // OpenStream is used to create a new stream
func (s *Session) OpenStream() (*Stream, error) | {
if s.IsClosed() {
return nil, ErrSessionShutdown
}
if atomic.LoadInt32(&s.remoteGoAway) == 1 {
return nil, ErrRemoteGoAway
}
// Block if we have too many inflight SYNs
select {
case s.synCh <- struct{}{}:
case <-s.shutdownCh:
return nil, ErrSessionShutdown
}
GET_ID:
// Get an ID, and check for stream exhaustion
id := atomic.LoadUint32(&s.nextStreamID)
if id >= math.MaxUint32-1 {
return nil, ErrStreamsExhausted
}
if !atomic.CompareAndSwapUint32(&s.nextStreamID, id, id+2) {
goto GET_ID
}
// Register the stream
stream := newStream(s, id, streamInit)
s.streamLock.Lock()
s.streams[id] = stream
s.inflight[id] = struct{}{}
s.streamLock.Unlock()
// Send the window update to create
if err := stream.sendWindowUpdate(); err != nil {
select {
case <-s.synCh:
default:
s.logger.Printf("[ERR] yamux: aborted stream open without inflight syn semaphore")
}
return nil, err
}
return stream, nil
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | session.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L201-L207 | go | train | // Accept is used to block until the next available stream
// is ready to be accepted. | func (s *Session) Accept() (net.Conn, error) | // Accept is used to block until the next available stream
// is ready to be accepted.
func (s *Session) Accept() (net.Conn, error) | {
conn, err := s.AcceptStream()
if err != nil {
return nil, err
}
return conn, err
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | session.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L211-L221 | go | train | // AcceptStream is used to block until the next available stream
// is ready to be accepted. | func (s *Session) AcceptStream() (*Stream, error) | // AcceptStream is used to block until the next available stream
// is ready to be accepted.
func (s *Session) AcceptStream() (*Stream, error) | {
select {
case stream := <-s.acceptCh:
if err := stream.sendWindowUpdate(); err != nil {
return nil, err
}
return stream, nil
case <-s.shutdownCh:
return nil, s.shutdownErr
}
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | session.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L225-L246 | go | train | // Close is used to close the session and all streams.
// Attempts to send a GoAway before closing the connection. | func (s *Session) Close() error | // Close is used to close the session and all streams.
// Attempts to send a GoAway before closing the connection.
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
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | session.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L250-L257 | go | train | // exitErr is used to handle an error that is causing the
// session to terminate. | func (s *Session) exitErr(err error) | // exitErr is used to handle an error that is causing the
// session to terminate.
func (s *Session) exitErr(err error) | {
s.shutdownLock.Lock()
if s.shutdownErr == nil {
s.shutdownErr = err
}
s.shutdownLock.Unlock()
s.Close()
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | session.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L261-L263 | go | train | // GoAway can be used to prevent accepting further
// connections. It does not close the underlying conn. | func (s *Session) GoAway() error | // GoAway can be used to prevent accepting further
// connections. It does not close the underlying conn.
func (s *Session) GoAway() error | {
return s.waitForSend(s.goAway(goAwayNormal), nil)
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | session.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L266-L271 | go | train | // goAway is used to send a goAway message | func (s *Session) goAway(reason uint32) header | // goAway is used to send a goAway message
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
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | session.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L274-L307 | go | train | // Ping is used to measure the RTT response time | func (s *Session) Ping() (time.Duration, error) | // Ping is used to measure the RTT response time
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
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | session.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L311-L327 | go | train | // keepalive is a long running goroutine that periodically does
// a ping to keep the connection alive. | func (s *Session) keepalive() | // keepalive is a long running goroutine that periodically does
// a ping to keep the connection alive.
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
}
}
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | session.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L330-L333 | go | train | // waitForSendErr waits to send a header, checking for a potential shutdown | func (s *Session) waitForSend(hdr header, body io.Reader) error | // waitForSendErr waits to send a header, checking for a potential shutdown
func (s *Session) waitForSend(hdr header, body io.Reader) error | {
errCh := make(chan error, 1)
return s.waitForSendErr(hdr, body, errCh)
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | session.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L338-L368 | go | train | // 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. | func (s *Session) waitForSendErr(hdr header, body io.Reader, errCh chan error) error | // 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.
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
}
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | session.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L373-L394 | go | train | // 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. | func (s *Session) sendNoWait(hdr header) error | // 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.
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
}
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | session.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L397-L433 | go | train | // send is a long running goroutine that sends data | func (s *Session) send() | // send is a long running goroutine that sends data
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
}
}
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | session.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L436-L440 | go | train | // recv is a long running goroutine that accepts new data | func (s *Session) recv() | // recv is a long running goroutine that accepts new data
func (s *Session) recv() | {
if err := s.recvLoop(); err != nil {
s.exitErr(err)
}
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | session.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L453-L480 | go | train | // recvLoop continues to receive data until a fatal error is encountered | func (s *Session) recvLoop() error | // recvLoop continues to receive data until a fatal error is encountered
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
}
}
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | session.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L483-L532 | go | train | // handleStreamMessage handles either a data or window update frame | func (s *Session) handleStreamMessage(hdr header) error | // handleStreamMessage handles either a data or window update frame
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
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | session.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L535-L561 | go | train | // handlePing is invokde for a typePing frame | func (s *Session) handlePing(hdr header) error | // handlePing is invokde for a typePing frame
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
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | session.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L564-L580 | go | train | // handleGoAway is invokde for a typeGoAway frame | func (s *Session) handleGoAway(hdr header) error | // handleGoAway is invokde for a typeGoAway frame
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
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | session.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L583-L620 | go | train | // incomingStream is used to create a new incoming stream | func (s *Session) incomingStream(id uint32) error | // incomingStream is used to create a new incoming stream
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)
}
} |
hashicorp/yamux | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | session.go | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L625-L636 | go | train | // 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. | func (s *Session) closeStream(id uint32) | // 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.
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()
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | plugins/graphite_aggregator.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/plugins/graphite_aggregator.go#L49-L51 | go | train | // InitializeGraphiteCollector creates the connection to the graphite server
// and should be called before any metrics are recorded. | func InitializeGraphiteCollector(config *GraphiteCollectorConfig) | // InitializeGraphiteCollector creates the connection to the graphite server
// and should be called before any metrics are recorded.
func InitializeGraphiteCollector(config *GraphiteCollectorConfig) | {
go metrics.Graphite(metrics.DefaultRegistry, config.TickInterval, config.Prefix, config.GraphiteAddr)
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | plugins/graphite_aggregator.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/plugins/graphite_aggregator.go#L56-L73 | go | train | // NewGraphiteCollector creates a collector for a specific circuit. The
// prefix given to this circuit will be {config.Prefix}.{circuit_name}.{metric}.
// Circuits with "/" in their names will have them replaced with ".". | func NewGraphiteCollector(name string) metricCollector.MetricCollector | // NewGraphiteCollector creates a collector for a specific circuit. The
// prefix given to this circuit will be {config.Prefix}.{circuit_name}.{metric}.
// Circuits with "/" in their names will have them replaced with ".".
func NewGraphiteCollector(name string) metricCollector.MetricCollector | {
name = strings.Replace(name, "/", "-", -1)
name = strings.Replace(name, ":", "-", -1)
name = strings.Replace(name, ".", "-", -1)
return &GraphiteCollector{
attemptsPrefix: name + ".attempts",
errorsPrefix: name + ".errors",
successesPrefix: name + ".successes",
failuresPrefix: name + ".failures",
rejectsPrefix: name + ".rejects",
shortCircuitsPrefix: name + ".shortCircuits",
timeoutsPrefix: name + ".timeouts",
fallbackSuccessesPrefix: name + ".fallbackSuccesses",
fallbackFailuresPrefix: name + ".fallbackFailures",
totalDurationPrefix: name + ".totalDuration",
runDurationPrefix: name + ".runDuration",
}
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | plugins/datadog_collector.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/plugins/datadog_collector.go#L89-L100 | go | train | // NewDatadogCollector creates a collector for a specific circuit with a
// "github.com/DataDog/datadog-go/statsd".(*Client).
//
// addr is in the format "<host>:<port>" (e.g. "localhost:8125")
//
// prefix may be an empty string
//
// Example use
// package main
//
// import (
// "github.com/afex/hystrix-go/plugins"
// "github.com/afex/hystrix-go/hystrix/metric_collector"
// )
//
// func main() {
// collector, err := plugins.NewDatadogCollector("localhost:8125", "")
// if err != nil {
// panic(err)
// }
// metricCollector.Registry.Register(collector)
// } | func NewDatadogCollector(addr, prefix string) (func(string) metricCollector.MetricCollector, error) | // NewDatadogCollector creates a collector for a specific circuit with a
// "github.com/DataDog/datadog-go/statsd".(*Client).
//
// addr is in the format "<host>:<port>" (e.g. "localhost:8125")
//
// prefix may be an empty string
//
// Example use
// package main
//
// import (
// "github.com/afex/hystrix-go/plugins"
// "github.com/afex/hystrix-go/hystrix/metric_collector"
// )
//
// func main() {
// collector, err := plugins.NewDatadogCollector("localhost:8125", "")
// if err != nil {
// panic(err)
// }
// metricCollector.Registry.Register(collector)
// }
func NewDatadogCollector(addr, prefix string) (func(string) metricCollector.MetricCollector, error) | {
c, err := statsd.NewBuffered(addr, 100)
if err != nil {
return nil, err
}
// Prefix every metric with the app name
c.Namespace = prefix
return NewDatadogCollectorWithClient(c), nil
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | plugins/datadog_collector.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/plugins/datadog_collector.go#L106-L115 | go | train | // NewDatadogCollectorWithClient accepts an interface which allows you to
// provide your own implementation of a statsd client, alter configuration on
// "github.com/DataDog/datadog-go/statsd".(*Client), provide additional tags per
// circuit-metric tuple, and add logging if you need it. | func NewDatadogCollectorWithClient(client DatadogClient) func(string) metricCollector.MetricCollector | // NewDatadogCollectorWithClient accepts an interface which allows you to
// provide your own implementation of a statsd client, alter configuration on
// "github.com/DataDog/datadog-go/statsd".(*Client), provide additional tags per
// circuit-metric tuple, and add logging if you need it.
func NewDatadogCollectorWithClient(client DatadogClient) func(string) metricCollector.MetricCollector | {
return func(name string) metricCollector.MetricCollector {
return &DatadogCollector{
client: client,
tags: []string{"hystrixcircuit:" + name},
}
}
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/circuit.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/circuit.go#L34-L53 | go | train | // GetCircuit returns the circuit for the given command and whether this call created it. | func GetCircuit(name string) (*CircuitBreaker, bool, error) | // GetCircuit returns the circuit for the given command and whether this call created it.
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
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/circuit.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/circuit.go#L56-L65 | go | train | // Flush purges all circuit and metric information from memory. | func Flush() | // Flush purges all circuit and metric information from memory.
func Flush() | {
circuitBreakersMutex.Lock()
defer circuitBreakersMutex.Unlock()
for name, cb := range circuitBreakers {
cb.metrics.Reset()
cb.executorPool.Metrics.Reset()
delete(circuitBreakers, name)
}
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/circuit.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/circuit.go#L68-L76 | go | train | // newCircuitBreaker creates a CircuitBreaker with associated Health | func newCircuitBreaker(name string) *CircuitBreaker | // newCircuitBreaker creates a CircuitBreaker with associated Health
func newCircuitBreaker(name string) *CircuitBreaker | {
c := &CircuitBreaker{}
c.Name = name
c.metrics = newMetricExchange(name)
c.executorPool = newExecutorPool(name)
c.mutex = &sync.RWMutex{}
return c
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/circuit.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/circuit.go#L80-L88 | go | train | // toggleForceOpen allows manually causing the fallback logic for all instances
// of a given command. | func (circuit *CircuitBreaker) toggleForceOpen(toggle bool) error | // toggleForceOpen allows manually causing the fallback logic for all instances
// of a given command.
func (circuit *CircuitBreaker) toggleForceOpen(toggle bool) error | {
circuit, _, err := GetCircuit(circuit.Name)
if err != nil {
return err
}
circuit.forceOpen = toggle
return nil
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/circuit.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/circuit.go#L92-L112 | go | train | // IsOpen is called before any Command execution to check whether or
// not it should be attempted. An "open" circuit means it is disabled. | func (circuit *CircuitBreaker) IsOpen() bool | // IsOpen is called before any Command execution to check whether or
// not it should be attempted. An "open" circuit means it is disabled.
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
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/circuit.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/circuit.go#L167-L196 | go | train | // ReportEvent records command metrics for tracking recent error rates and exposing data to the dashboard. | func (circuit *CircuitBreaker) ReportEvent(eventTypes []string, start time.Time, runDuration time.Duration) error | // ReportEvent records command metrics for tracking recent error rates and exposing data to the dashboard.
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
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | plugins/statsd_collector.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/plugins/statsd_collector.go#L65-L85 | go | train | // InitializeStatsdCollector creates the connection to the Statsd server
// and should be called before any metrics are recorded.
//
// Users should ensure to call Close() on the client. | func InitializeStatsdCollector(config *StatsdCollectorConfig) (*StatsdCollectorClient, error) | // InitializeStatsdCollector creates the connection to the Statsd server
// and should be called before any metrics are recorded.
//
// Users should ensure to call Close() on the client.
func InitializeStatsdCollector(config *StatsdCollectorConfig) (*StatsdCollectorClient, error) | {
flushBytes := config.FlushBytes
if flushBytes == 0 {
flushBytes = LANStatsdFlushBytes
}
sampleRate := config.SampleRate
if sampleRate == 0 {
sampleRate = 1
}
c, err := statsd.NewBufferedClient(config.StatsdAddr, config.Prefix, 1*time.Second, flushBytes)
if err != nil {
log.Printf("Could not initiale buffered client: %s. Falling back to a Noop Statsd client", err)
c, _ = statsd.NewNoopClient()
}
return &StatsdCollectorClient{
client: c,
sampleRate: sampleRate,
}, err
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | plugins/statsd_collector.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/plugins/statsd_collector.go#L90-L116 | go | train | // NewStatsdCollector creates a collector for a specific circuit. The
// prefix given to this circuit will be {config.Prefix}.{circuit_name}.{metric}.
// Circuits with "/" in their names will have them replaced with ".". | func (s *StatsdCollectorClient) NewStatsdCollector(name string) metricCollector.MetricCollector | // NewStatsdCollector creates a collector for a specific circuit. The
// prefix given to this circuit will be {config.Prefix}.{circuit_name}.{metric}.
// Circuits with "/" in their names will have them replaced with ".".
func (s *StatsdCollectorClient) NewStatsdCollector(name string) metricCollector.MetricCollector | {
if s.client == nil {
log.Fatalf("Statsd client must be initialized before circuits are created.")
}
name = strings.Replace(name, "/", "-", -1)
name = strings.Replace(name, ":", "-", -1)
name = strings.Replace(name, ".", "-", -1)
return &StatsdCollector{
client: s.client,
circuitOpenPrefix: name + ".circuitOpen",
attemptsPrefix: name + ".attempts",
errorsPrefix: name + ".errors",
successesPrefix: name + ".successes",
failuresPrefix: name + ".failures",
rejectsPrefix: name + ".rejects",
shortCircuitsPrefix: name + ".shortCircuits",
timeoutsPrefix: name + ".timeouts",
fallbackSuccessesPrefix: name + ".fallbackSuccesses",
fallbackFailuresPrefix: name + ".fallbackFailures",
canceledPrefix: name + ".contextCanceled",
deadlinePrefix: name + ".contextDeadlineExceeded",
totalDurationPrefix: name + ".totalDuration",
runDurationPrefix: name + ".runDuration",
concurrencyInUsePrefix: name + ".concurrencyInUse",
sampleRate: s.sampleRate,
}
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/rolling/rolling.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling.go#L20-L26 | go | train | // NewNumber initializes a RollingNumber struct. | func NewNumber() *Number | // NewNumber initializes a RollingNumber struct.
func NewNumber() *Number | {
r := &Number{
Buckets: make(map[int64]*numberBucket),
Mutex: &sync.RWMutex{},
}
return r
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/rolling/rolling.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling.go#L53-L64 | go | train | // Increment increments the number in current timeBucket. | func (r *Number) Increment(i float64) | // Increment increments the number in current timeBucket.
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()
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/rolling/rolling.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling.go#L67-L76 | go | train | // UpdateMax updates the maximum value in the current bucket. | func (r *Number) UpdateMax(n float64) | // UpdateMax updates the maximum value in the current bucket.
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()
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/rolling/rolling.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling.go#L79-L93 | go | train | // Sum sums the values over the buckets in the last 10 seconds. | func (r *Number) Sum(now time.Time) float64 | // Sum sums the values over the buckets in the last 10 seconds.
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
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/rolling/rolling.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling.go#L96-L112 | go | train | // Max returns the maximum value seen in the last 10 seconds. | func (r *Number) Max(now time.Time) float64 | // Max returns the maximum value seen in the last 10 seconds.
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
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/hystrix.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/hystrix.go#L55-L66 | go | train | // 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. | func Go(name string, run runFunc, fallback fallbackFunc) chan error | // 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.
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)
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/hystrix.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/hystrix.go#L73-L198 | go | train | // GoC 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. | func GoC(ctx context.Context, name string, run runFuncC, fallback fallbackFuncC) chan error | // GoC 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.
func GoC(ctx context.Context, name string, run runFuncC, fallback fallbackFuncC) chan error | {
cmd := &command{
run: run,
fallback: fallback,
start: time.Now(),
errChan: make(chan error, 1),
finished: make(chan bool, 1),
}
// dont have methods with explicit params and returns
// let data come in and out naturally, like with any closure
// explicit error return to give place for us to kill switch the operation (fallback)
circuit, _, err := GetCircuit(name)
if err != nil {
cmd.errChan <- err
return cmd.errChan
}
cmd.circuit = circuit
ticketCond := sync.NewCond(cmd)
ticketChecked := false
// When the caller extracts error from returned errChan, it's assumed that
// the ticket's been returned to executorPool. Therefore, returnTicket() can
// not run after cmd.errorWithFallback().
returnTicket := func() {
cmd.Lock()
// Avoid releasing before a ticket is acquired.
for !ticketChecked {
ticketCond.Wait()
}
cmd.circuit.executorPool.Return(cmd.ticket)
cmd.Unlock()
}
// Shared by the following two goroutines. It ensures only the faster
// goroutine runs errWithFallback() and reportAllEvent().
returnOnce := &sync.Once{}
reportAllEvent := func() {
err := cmd.circuit.ReportEvent(cmd.events, cmd.start, cmd.runDuration)
if err != nil {
log.Printf(err.Error())
}
}
go func() {
defer func() { cmd.finished <- true }()
// Circuits get opened when recent executions have shown to have a high error rate.
// Rejecting new executions allows backends to recover, and the circuit will allow
// new traffic when it feels a healthly state has returned.
if !cmd.circuit.AllowRequest() {
cmd.Lock()
// It's safe for another goroutine to go ahead releasing a nil ticket.
ticketChecked = true
ticketCond.Signal()
cmd.Unlock()
returnOnce.Do(func() {
returnTicket()
cmd.errorWithFallback(ctx, ErrCircuitOpen)
reportAllEvent()
})
return
}
// As backends falter, requests take longer but don't always fail.
//
// When requests slow down but the incoming rate of requests stays the same, you have to
// run more at a time to keep up. By controlling concurrency during these situations, you can
// shed load which accumulates due to the increasing ratio of active commands to incoming requests.
cmd.Lock()
select {
case cmd.ticket = <-circuit.executorPool.Tickets:
ticketChecked = true
ticketCond.Signal()
cmd.Unlock()
default:
ticketChecked = true
ticketCond.Signal()
cmd.Unlock()
returnOnce.Do(func() {
returnTicket()
cmd.errorWithFallback(ctx, ErrMaxConcurrency)
reportAllEvent()
})
return
}
runStart := time.Now()
runErr := run(ctx)
returnOnce.Do(func() {
defer reportAllEvent()
cmd.runDuration = time.Since(runStart)
returnTicket()
if runErr != nil {
cmd.errorWithFallback(ctx, runErr)
return
}
cmd.reportEvent("success")
})
}()
go func() {
timer := time.NewTimer(getSettings(name).Timeout)
defer timer.Stop()
select {
case <-cmd.finished:
// returnOnce has been executed in another goroutine
case <-ctx.Done():
returnOnce.Do(func() {
returnTicket()
cmd.errorWithFallback(ctx, ctx.Err())
reportAllEvent()
})
return
case <-timer.C:
returnOnce.Do(func() {
returnTicket()
cmd.errorWithFallback(ctx, ErrTimeout)
reportAllEvent()
})
return
}
}()
return cmd.errChan
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/hystrix.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/hystrix.go#L217-L253 | go | train | // DoC runs your function in a synchronous manner, blocking until either your function succeeds
// or an error is returned, including hystrix circuit errors | func DoC(ctx context.Context, name string, run runFuncC, fallback fallbackFuncC) error | // DoC runs your function in a synchronous manner, blocking until either your function succeeds
// or an error is returned, including hystrix circuit errors
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
}
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/hystrix.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/hystrix.go#L263-L282 | go | train | // errorWithFallback triggers the fallback while reporting the appropriate metric events. | func (c *command) errorWithFallback(ctx context.Context, err error) | // errorWithFallback triggers the fallback while reporting the appropriate metric events.
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
}
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/settings.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/settings.go#L51-L55 | go | train | // Configure applies settings for a set of circuits | func Configure(cmds map[string]CommandConfig) | // Configure applies settings for a set of circuits
func Configure(cmds map[string]CommandConfig) | {
for k, v := range cmds {
ConfigureCommand(k, v)
}
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/settings.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/settings.go#L58-L94 | go | train | // ConfigureCommand applies settings for a circuit | func ConfigureCommand(name string, config CommandConfig) | // ConfigureCommand applies settings for a circuit
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,
}
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/metric_collector/default_metric_collector.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L43-L47 | go | train | // NumRequests returns the rolling number of requests | func (d *DefaultMetricCollector) NumRequests() *rolling.Number | // NumRequests returns the rolling number of requests
func (d *DefaultMetricCollector) NumRequests() *rolling.Number | {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.numRequests
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/metric_collector/default_metric_collector.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L50-L54 | go | train | // Errors returns the rolling number of errors | func (d *DefaultMetricCollector) Errors() *rolling.Number | // Errors returns the rolling number of errors
func (d *DefaultMetricCollector) Errors() *rolling.Number | {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.errors
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/metric_collector/default_metric_collector.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L57-L61 | go | train | // Successes returns the rolling number of successes | func (d *DefaultMetricCollector) Successes() *rolling.Number | // Successes returns the rolling number of successes
func (d *DefaultMetricCollector) Successes() *rolling.Number | {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.successes
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/metric_collector/default_metric_collector.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L64-L68 | go | train | // Failures returns the rolling number of failures | func (d *DefaultMetricCollector) Failures() *rolling.Number | // Failures returns the rolling number of failures
func (d *DefaultMetricCollector) Failures() *rolling.Number | {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.failures
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/metric_collector/default_metric_collector.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L71-L75 | go | train | // Rejects returns the rolling number of rejects | func (d *DefaultMetricCollector) Rejects() *rolling.Number | // Rejects returns the rolling number of rejects
func (d *DefaultMetricCollector) Rejects() *rolling.Number | {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.rejects
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/metric_collector/default_metric_collector.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L78-L82 | go | train | // ShortCircuits returns the rolling number of short circuits | func (d *DefaultMetricCollector) ShortCircuits() *rolling.Number | // ShortCircuits returns the rolling number of short circuits
func (d *DefaultMetricCollector) ShortCircuits() *rolling.Number | {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.shortCircuits
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/metric_collector/default_metric_collector.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L85-L89 | go | train | // Timeouts returns the rolling number of timeouts | func (d *DefaultMetricCollector) Timeouts() *rolling.Number | // Timeouts returns the rolling number of timeouts
func (d *DefaultMetricCollector) Timeouts() *rolling.Number | {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.timeouts
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/metric_collector/default_metric_collector.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L92-L96 | go | train | // FallbackSuccesses returns the rolling number of fallback successes | func (d *DefaultMetricCollector) FallbackSuccesses() *rolling.Number | // FallbackSuccesses returns the rolling number of fallback successes
func (d *DefaultMetricCollector) FallbackSuccesses() *rolling.Number | {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.fallbackSuccesses
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/metric_collector/default_metric_collector.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L111-L115 | go | train | // FallbackFailures returns the rolling number of fallback failures | func (d *DefaultMetricCollector) FallbackFailures() *rolling.Number | // FallbackFailures returns the rolling number of fallback failures
func (d *DefaultMetricCollector) FallbackFailures() *rolling.Number | {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.fallbackFailures
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/metric_collector/default_metric_collector.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L118-L122 | go | train | // TotalDuration returns the rolling total duration | func (d *DefaultMetricCollector) TotalDuration() *rolling.Timing | // TotalDuration returns the rolling total duration
func (d *DefaultMetricCollector) TotalDuration() *rolling.Timing | {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.totalDuration
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/metric_collector/default_metric_collector.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L125-L129 | go | train | // RunDuration returns the rolling run duration | func (d *DefaultMetricCollector) RunDuration() *rolling.Timing | // RunDuration returns the rolling run duration
func (d *DefaultMetricCollector) RunDuration() *rolling.Timing | {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.runDuration
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/metric_collector/default_metric_collector.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L152-L169 | go | train | // Reset resets all metrics in this collector to 0. | func (d *DefaultMetricCollector) Reset() | // Reset resets all metrics in this collector to 0.
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()
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/rolling/rolling_timing.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling_timing.go#L26-L32 | go | train | // NewTiming creates a RollingTiming struct. | func NewTiming() *Timing | // NewTiming creates a RollingTiming struct.
func NewTiming() *Timing | {
r := &Timing{
Buckets: make(map[int64]*timingBucket),
Mutex: &sync.RWMutex{},
}
return r
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/rolling/rolling_timing.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling_timing.go#L42-L73 | go | train | // SortedDurations returns an array of time.Duration sorted from shortest
// to longest that have occurred in the last 60 seconds. | func (r *Timing) SortedDurations() []time.Duration | // SortedDurations returns an array of time.Duration sorted from shortest
// to longest that have occurred in the last 60 seconds.
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
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/rolling/rolling_timing.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling_timing.go#L104-L112 | go | train | // Add appends the time.Duration given to the current time bucket. | func (r *Timing) Add(duration time.Duration) | // Add appends the time.Duration given to the current time bucket.
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()
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/rolling/rolling_timing.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling_timing.go#L115-L124 | go | train | // Percentile computes the percentile given with a linear interpolation. | func (r *Timing) Percentile(p float64) uint32 | // Percentile computes the percentile given with a linear interpolation.
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)
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/rolling/rolling_timing.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling_timing.go#L135-L148 | go | train | // Mean computes the average timing in the last 60 seconds. | func (r *Timing) Mean() uint32 | // Mean computes the average timing in the last 60 seconds.
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
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/metrics.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metrics.go#L41-L50 | go | train | // The Default Collector function will panic if collectors are not setup to specification. | func (m *metricExchange) DefaultCollector() *metricCollector.DefaultMetricCollector | // The Default Collector function will panic if collectors are not setup to specification.
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
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/eventstream.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/eventstream.go#L30-L34 | go | train | // Start begins watching the in-memory circuit breakers for metrics | func (sh *StreamHandler) Start() | // Start begins watching the in-memory circuit breakers for metrics
func (sh *StreamHandler) Start() | {
sh.requests = make(map[*http.Request]chan []byte)
sh.done = make(chan struct{})
go sh.loop()
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/metric_collector/metric_collector.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/metric_collector.go#L23-L32 | go | train | // InitializeMetricCollectors runs the registried MetricCollector Initializers to create an array of MetricCollectors. | func (m *metricCollectorRegistry) InitializeMetricCollectors(name string) []MetricCollector | // InitializeMetricCollectors runs the registried MetricCollector Initializers to create an array of MetricCollectors.
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
} |
afex/hystrix-go | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | hystrix/metric_collector/metric_collector.go | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/metric_collector.go#L35-L40 | go | train | // Register places a MetricCollector Initializer in the registry maintained by this metricCollectorRegistry. | func (m *metricCollectorRegistry) Register(initMetricCollector func(string) MetricCollector) | // Register places a MetricCollector Initializer in the registry maintained by this metricCollectorRegistry.
func (m *metricCollectorRegistry) Register(initMetricCollector func(string) MetricCollector) | {
m.lock.Lock()
defer m.lock.Unlock()
m.registry = append(m.registry, initMetricCollector)
} |
kardianos/service | 0e5bec1b9eec14f9070a6f49ad7e0242f1545d66 | version.go | https://github.com/kardianos/service/blob/0e5bec1b9eec14f9070a6f49ad7e0242f1545d66/version.go#L10-L17 | go | train | // versionAtMost will return true if the provided version is less than or equal to max | func versionAtMost(version, max []int) (bool, error) | // versionAtMost will return true if the provided version is less than or equal to max
func versionAtMost(version, max []int) (bool, error) | {
if comp, err := versionCompare(version, max); err != nil {
return false, err
} else if comp == 1 {
return false, nil
}
return true, nil
} |
kardianos/service | 0e5bec1b9eec14f9070a6f49ad7e0242f1545d66 | version.go | https://github.com/kardianos/service/blob/0e5bec1b9eec14f9070a6f49ad7e0242f1545d66/version.go#L25-L41 | go | train | // versionCompare take to versions split into integer arrays and attempts to compare them
// An error will be returned if there is an array length mismatch.
// Return values are as follows
// -1 - v1 is less than v2
// 0 - v1 is equal to v2
// 1 - v1 is greater than v2 | func versionCompare(v1, v2 []int) (int, error) | // versionCompare take to versions split into integer arrays and attempts to compare them
// An error will be returned if there is an array length mismatch.
// Return values are as follows
// -1 - v1 is less than v2
// 0 - v1 is equal to v2
// 1 - v1 is greater than v2
func versionCompare(v1, v2 []int) (int, error) | {
if len(v1) != len(v2) {
return 0, errors.New("version length mismatch")
}
for idx, v2S := range v2 {
v1S := v1[idx]
if v1S > v2S {
return 1, nil
}
if v1S < v2S {
return -1, nil
}
}
return 0, nil
} |
kardianos/service | 0e5bec1b9eec14f9070a6f49ad7e0242f1545d66 | version.go | https://github.com/kardianos/service/blob/0e5bec1b9eec14f9070a6f49ad7e0242f1545d66/version.go#L45-L57 | go | train | // parseVersion will parse any integer type version seperated by periods.
// This does not fully support semver style versions. | func parseVersion(v string) []int | // parseVersion will parse any integer type version seperated by periods.
// This does not fully support semver style versions.
func parseVersion(v string) []int | {
version := make([]int, 3)
for idx, vStr := range strings.Split(v, ".") {
vS, err := strconv.Atoi(vStr)
if err != nil {
return nil
}
version[idx] = vS
}
return version
} |
kardianos/service | 0e5bec1b9eec14f9070a6f49ad7e0242f1545d66 | service.go | https://github.com/kardianos/service/blob/0e5bec1b9eec14f9070a6f49ad7e0242f1545d66/service.go#L160-L168 | go | train | // New creates a new service based on a service interface and configuration. | func New(i Interface, c *Config) (Service, error) | // New creates a new service based on a service interface and configuration.
func New(i Interface, c *Config) (Service, error) | {
if len(c.Name) == 0 {
return nil, ErrNameFieldRequired
}
if system == nil {
return nil, ErrNoServiceSystemDetected
}
return system.New(i, c)
} |
kardianos/service | 0e5bec1b9eec14f9070a6f49ad7e0242f1545d66 | service.go | https://github.com/kardianos/service/blob/0e5bec1b9eec14f9070a6f49ad7e0242f1545d66/service.go#L176-L183 | go | train | // bool returns the value of the given name, assuming the value is a boolean.
// If the value isn't found or is not of the type, the defaultValue is returned. | func (kv KeyValue) bool(name string, defaultValue bool) bool | // bool returns the value of the given name, assuming the value is a boolean.
// If the value isn't found or is not of the type, the defaultValue is returned.
func (kv KeyValue) bool(name string, defaultValue bool) bool | {
if v, found := kv[name]; found {
if castValue, is := v.(bool); is {
return castValue
}
}
return defaultValue
} |
kardianos/service | 0e5bec1b9eec14f9070a6f49ad7e0242f1545d66 | service.go | https://github.com/kardianos/service/blob/0e5bec1b9eec14f9070a6f49ad7e0242f1545d66/service.go#L368-L388 | go | train | // Control issues control functions to the service from a given action string. | func Control(s Service, action string) error | // Control issues control functions to the service from a given action string.
func Control(s Service, action string) error | {
var err error
switch action {
case ControlAction[0]:
err = s.Start()
case ControlAction[1]:
err = s.Stop()
case ControlAction[2]:
err = s.Restart()
case ControlAction[3]:
err = s.Install()
case ControlAction[4]:
err = s.Uninstall()
default:
err = fmt.Errorf("Unknown action %s", action)
}
if err != nil {
return fmt.Errorf("Failed to %s %v: %v", action, s, err)
}
return nil
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.