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
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3150-L3153
go
train
// Queued returns the number of queued messages in the client for this subscription. // DEPRECATED: Use Pending()
func (s *Subscription) QueuedMsgs() (int, error)
// Queued returns the number of queued messages in the client for this subscription. // DEPRECATED: Use Pending() func (s *Subscription) QueuedMsgs() (int, error)
{ m, _, err := s.Pending() return int(m), err }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3156-L3169
go
train
// Pending returns the number of queued messages and queued bytes in the client for this subscription.
func (s *Subscription) Pending() (int, int, error)
// Pending returns the number of queued messages and queued bytes in the client for this subscription. func (s *Subscription) Pending() (int, int, error)
{ if s == nil { return -1, -1, ErrBadSubscription } s.mu.Lock() defer s.mu.Unlock() if s.conn == nil { return -1, -1, ErrBadSubscription } if s.typ == ChanSubscription { return -1, -1, ErrTypeSubscription } return s.pMsgs, s.pBytes, nil }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3188-L3202
go
train
// ClearMaxPending resets the maximums seen so far.
func (s *Subscription) ClearMaxPending() error
// ClearMaxPending resets the maximums seen so far. func (s *Subscription) ClearMaxPending() error
{ if s == nil { return ErrBadSubscription } s.mu.Lock() defer s.mu.Unlock() if s.conn == nil { return ErrBadSubscription } if s.typ == ChanSubscription { return ErrTypeSubscription } s.pMsgsMax, s.pBytesMax = 0, 0 return nil }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3213-L3226
go
train
// PendingLimits returns the current limits for this subscription. // If no error is returned, a negative value indicates that the // given metric is not limited.
func (s *Subscription) PendingLimits() (int, int, error)
// PendingLimits returns the current limits for this subscription. // If no error is returned, a negative value indicates that the // given metric is not limited. func (s *Subscription) PendingLimits() (int, int, error)
{ if s == nil { return -1, -1, ErrBadSubscription } s.mu.Lock() defer s.mu.Unlock() if s.conn == nil { return -1, -1, ErrBadSubscription } if s.typ == ChanSubscription { return -1, -1, ErrTypeSubscription } return s.pMsgsLimit, s.pBytesLimit, nil }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3230-L3247
go
train
// SetPendingLimits sets the limits for pending msgs and bytes for this subscription. // Zero is not allowed. Any negative value means that the given metric is not limited.
func (s *Subscription) SetPendingLimits(msgLimit, bytesLimit int) error
// SetPendingLimits sets the limits for pending msgs and bytes for this subscription. // Zero is not allowed. Any negative value means that the given metric is not limited. func (s *Subscription) SetPendingLimits(msgLimit, bytesLimit int) error
{ if s == nil { return ErrBadSubscription } s.mu.Lock() defer s.mu.Unlock() if s.conn == nil { return ErrBadSubscription } if s.typ == ChanSubscription { return ErrTypeSubscription } if msgLimit == 0 || bytesLimit == 0 { return ErrInvalidArg } s.pMsgsLimit, s.pBytesLimit = msgLimit, bytesLimit return nil }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3250-L3260
go
train
// Delivered returns the number of delivered messages for this subscription.
func (s *Subscription) Delivered() (int64, error)
// Delivered returns the number of delivered messages for this subscription. func (s *Subscription) Delivered() (int64, error)
{ if s == nil { return -1, ErrBadSubscription } s.mu.Lock() defer s.mu.Unlock() if s.conn == nil { return -1, ErrBadSubscription } return int64(s.delivered), nil }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3266-L3276
go
train
// Dropped returns the number of known dropped messages for this subscription. // This will correspond to messages dropped by violations of PendingLimits. If // the server declares the connection a SlowConsumer, this number may not be // valid.
func (s *Subscription) Dropped() (int, error)
// Dropped returns the number of known dropped messages for this subscription. // This will correspond to messages dropped by violations of PendingLimits. If // the server declares the connection a SlowConsumer, this number may not be // valid. func (s *Subscription) Dropped() (int, error)
{ if s == nil { return -1, ErrBadSubscription } s.mu.Lock() defer s.mu.Unlock() if s.conn == nil { return -1, ErrBadSubscription } return s.dropped, nil }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3282-L3295
go
train
// FIXME: This is a hack // removeFlushEntry is needed when we need to discard queued up responses // for our pings as part of a flush call. This happens when we have a flush // call outstanding and we call close.
func (nc *Conn) removeFlushEntry(ch chan struct{}) bool
// FIXME: This is a hack // removeFlushEntry is needed when we need to discard queued up responses // for our pings as part of a flush call. This happens when we have a flush // call outstanding and we call close. func (nc *Conn) removeFlushEntry(ch chan struct{}) bool
{ nc.mu.Lock() defer nc.mu.Unlock() if nc.pongs == nil { return false } for i, c := range nc.pongs { if c == ch { nc.pongs[i] = nil return true } } return false }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3298-L3303
go
train
// The lock must be held entering this function.
func (nc *Conn) sendPing(ch chan struct{})
// The lock must be held entering this function. func (nc *Conn) sendPing(ch chan struct{})
{ nc.pongs = append(nc.pongs, ch) nc.bw.WriteString(pingProto) // Flush in place. nc.bw.Flush() }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3308-L3327
go
train
// This will fire periodically and send a client origin // ping to the server. Will also check that we have received // responses from the server.
func (nc *Conn) processPingTimer()
// This will fire periodically and send a client origin // ping to the server. Will also check that we have received // responses from the server. func (nc *Conn) processPingTimer()
{ nc.mu.Lock() if nc.status != CONNECTED { nc.mu.Unlock() return } // Check for violation nc.pout++ if nc.pout > nc.Opts.MaxPingsOut { nc.mu.Unlock() nc.processOpErr(ErrStaleConnection) return } nc.sendPing(nil) nc.ptmr.Reset(nc.Opts.PingInterval) nc.mu.Unlock() }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3330-L3368
go
train
// FlushTimeout allows a Flush operation to have an associated timeout.
func (nc *Conn) FlushTimeout(timeout time.Duration) (err error)
// FlushTimeout allows a Flush operation to have an associated timeout. func (nc *Conn) FlushTimeout(timeout time.Duration) (err error)
{ if nc == nil { return ErrInvalidConnection } if timeout <= 0 { return ErrBadTimeout } nc.mu.Lock() if nc.isClosed() { nc.mu.Unlock() return ErrConnectionClosed } t := globalTimerPool.Get(timeout) defer globalTimerPool.Put(t) // Create a buffered channel to prevent chan send to block // in processPong() if this code here times out just when // PONG was received. ch := make(chan struct{}, 1) nc.sendPing(ch) nc.mu.Unlock() select { case _, ok := <-ch: if !ok { err = ErrConnectionClosed } else { close(ch) } case <-t.C: err = ErrTimeout } if err != nil { nc.removeFlushEntry(ch) } return }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3378-L3385
go
train
// Buffered will return the number of bytes buffered to be sent to the server. // FIXME(dlc) take into account disconnected state.
func (nc *Conn) Buffered() (int, error)
// Buffered will return the number of bytes buffered to be sent to the server. // FIXME(dlc) take into account disconnected state. func (nc *Conn) Buffered() (int, error)
{ nc.mu.RLock() defer nc.mu.RUnlock() if nc.isClosed() || nc.bw == nil { return -1, ErrConnectionClosed } return nc.bw.Buffered(), nil }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3389-L3422
go
train
// resendSubscriptions will send our subscription state back to the // server. Used in reconnects
func (nc *Conn) resendSubscriptions()
// resendSubscriptions will send our subscription state back to the // server. Used in reconnects func (nc *Conn) resendSubscriptions()
{ // Since we are going to send protocols to the server, we don't want to // be holding the subsMu lock (which is used in processMsg). So copy // the subscriptions in a temporary array. nc.subsMu.RLock() subs := make([]*Subscription, 0, len(nc.subs)) for _, s := range nc.subs { subs = append(subs, s) } nc.subsMu.RUnlock() for _, s := range subs { adjustedMax := uint64(0) s.mu.Lock() if s.max > 0 { if s.delivered < s.max { adjustedMax = s.max - s.delivered } // adjustedMax could be 0 here if the number of delivered msgs // reached the max, if so unsubscribe. if adjustedMax == 0 { s.mu.Unlock() fmt.Fprintf(nc.bw, unsubProto, s.sid, _EMPTY_) continue } } s.mu.Unlock() fmt.Fprintf(nc.bw, subProto, s.Subject, s.Queue, s.sid) if adjustedMax > 0 { maxStr := strconv.Itoa(int(adjustedMax)) fmt.Fprintf(nc.bw, unsubProto, s.sid, maxStr) } } }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3426-L3434
go
train
// This will clear any pending flush calls and release pending calls. // Lock is assumed to be held by the caller.
func (nc *Conn) clearPendingFlushCalls()
// This will clear any pending flush calls and release pending calls. // Lock is assumed to be held by the caller. func (nc *Conn) clearPendingFlushCalls()
{ // Clear any queued pongs, e.g. pending flush calls. for _, ch := range nc.pongs { if ch != nil { close(ch) } } nc.pongs = nil }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3438-L3448
go
train
// This will clear any pending Request calls. // Lock is assumed to be held by the caller.
func (nc *Conn) clearPendingRequestCalls()
// This will clear any pending Request calls. // Lock is assumed to be held by the caller. func (nc *Conn) clearPendingRequestCalls()
{ if nc.respMap == nil { return } for key, ch := range nc.respMap { if ch != nil { close(ch) delete(nc.respMap, key) } } }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3454-L3523
go
train
// Low level close call that will do correct cleanup and set // desired status. Also controls whether user defined callbacks // will be triggered. The lock should not be held entering this // function. This function will handle the locking manually.
func (nc *Conn) close(status Status, doCBs bool)
// Low level close call that will do correct cleanup and set // desired status. Also controls whether user defined callbacks // will be triggered. The lock should not be held entering this // function. This function will handle the locking manually. func (nc *Conn) close(status Status, doCBs bool)
{ nc.mu.Lock() if nc.isClosed() { nc.status = status nc.mu.Unlock() return } nc.status = CLOSED // Kick the Go routines so they fall out. nc.kickFlusher() nc.mu.Unlock() nc.mu.Lock() // Clear any queued pongs, e.g. pending flush calls. nc.clearPendingFlushCalls() // Clear any queued and blocking Requests. nc.clearPendingRequestCalls() // Stop ping timer if set. nc.stopPingTimer() nc.ptmr = nil // Go ahead and make sure we have flushed the outbound if nc.conn != nil { nc.bw.Flush() defer nc.conn.Close() } // Close sync subscriber channels and release any // pending NextMsg() calls. nc.subsMu.Lock() for _, s := range nc.subs { s.mu.Lock() // Release callers on NextMsg for SyncSubscription only if s.mch != nil && s.typ == SyncSubscription { close(s.mch) } s.mch = nil // Mark as invalid, for signaling to deliverMsgs s.closed = true // Mark connection closed in subscription s.connClosed = true // If we have an async subscription, signals it to exit if s.typ == AsyncSubscription && s.pCond != nil { s.pCond.Signal() } s.mu.Unlock() } nc.subs = nil nc.subsMu.Unlock() nc.status = status // Perform appropriate callback if needed for a disconnect. if doCBs { if nc.Opts.DisconnectedCB != nil && nc.conn != nil { nc.ach.push(func() { nc.Opts.DisconnectedCB(nc) }) } if nc.Opts.ClosedCB != nil { nc.ach.push(func() { nc.Opts.ClosedCB(nc) }) } nc.ach.close() } nc.mu.Unlock() }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3534-L3538
go
train
// IsClosed tests if a Conn has been closed.
func (nc *Conn) IsClosed() bool
// IsClosed tests if a Conn has been closed. func (nc *Conn) IsClosed() bool
{ nc.mu.RLock() defer nc.mu.RUnlock() return nc.isClosed() }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3541-L3545
go
train
// IsReconnecting tests if a Conn is reconnecting.
func (nc *Conn) IsReconnecting() bool
// IsReconnecting tests if a Conn is reconnecting. func (nc *Conn) IsReconnecting() bool
{ nc.mu.RLock() defer nc.mu.RUnlock() return nc.isReconnecting() }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3548-L3552
go
train
// IsConnected tests if a Conn is connected.
func (nc *Conn) IsConnected() bool
// IsConnected tests if a Conn is connected. func (nc *Conn) IsConnected() bool
{ nc.mu.RLock() defer nc.mu.RUnlock() return nc.isConnected() }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3556-L3614
go
train
// drainConnection will run in a separate Go routine and will // flush all publishes and drain all active subscriptions.
func (nc *Conn) drainConnection()
// drainConnection will run in a separate Go routine and will // flush all publishes and drain all active subscriptions. func (nc *Conn) drainConnection()
{ // Snapshot subs list. nc.mu.Lock() subs := make([]*Subscription, 0, len(nc.subs)) for _, s := range nc.subs { subs = append(subs, s) } errCB := nc.Opts.AsyncErrorCB drainWait := nc.Opts.DrainTimeout nc.mu.Unlock() // for pushing errors with context. pushErr := func(err error) { nc.mu.Lock() nc.err = err if errCB != nil { nc.ach.push(func() { errCB(nc, nil, err) }) } nc.mu.Unlock() } // Do subs first for _, s := range subs { if err := s.Drain(); err != nil { // We will notify about these but continue. pushErr(err) } } // Wait for the subscriptions to drop to zero. timeout := time.Now().Add(drainWait) for time.Now().Before(timeout) { if nc.NumSubscriptions() == 0 { break } time.Sleep(10 * time.Millisecond) } // Check if we timed out. if nc.NumSubscriptions() != 0 { pushErr(ErrDrainTimeout) } // Flip State nc.mu.Lock() nc.status = DRAINING_PUBS nc.mu.Unlock() // Do publish drain via Flush() call. err := nc.Flush() if err != nil { pushErr(err) nc.Close() return } // Move to closed state. nc.Close() }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3621-L3638
go
train
// Drain will put a connection into a drain state. All subscriptions will // immediately be put into a drain state. Upon completion, the publishers // will be drained and can not publish any additional messages. Upon draining // of the publishers, the connection will be closed. Use the ClosedCB() // option to know when the connection has moved from draining to closed.
func (nc *Conn) Drain() error
// Drain will put a connection into a drain state. All subscriptions will // immediately be put into a drain state. Upon completion, the publishers // will be drained and can not publish any additional messages. Upon draining // of the publishers, the connection will be closed. Use the ClosedCB() // option to know when the connection has moved from draining to closed. func (nc *Conn) Drain() error
{ nc.mu.Lock() defer nc.mu.Unlock() if nc.isClosed() { return ErrConnectionClosed } if nc.isConnecting() || nc.isReconnecting() { return ErrConnectionReconnecting } if nc.isDraining() { return nil } nc.status = DRAINING_SUBS go nc.drainConnection() return nil }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3641-L3645
go
train
// IsDraining tests if a Conn is in the draining state.
func (nc *Conn) IsDraining() bool
// IsDraining tests if a Conn is in the draining state. func (nc *Conn) IsDraining() bool
{ nc.mu.RLock() defer nc.mu.RUnlock() return nc.isDraining() }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3648-L3659
go
train
// caller must lock
func (nc *Conn) getServers(implicitOnly bool) []string
// caller must lock func (nc *Conn) getServers(implicitOnly bool) []string
{ poolSize := len(nc.srvPool) var servers = make([]string, 0) for i := 0; i < poolSize; i++ { if implicitOnly && !nc.srvPool[i].isImplicit { continue } url := nc.srvPool[i].url servers = append(servers, fmt.Sprintf("%s://%s", url.Scheme, url.Host)) } return servers }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3665-L3669
go
train
// Servers returns the list of known server urls, including additional // servers discovered after a connection has been established. If // authentication is enabled, use UserInfo or Token when connecting with // these urls.
func (nc *Conn) Servers() []string
// Servers returns the list of known server urls, including additional // servers discovered after a connection has been established. If // authentication is enabled, use UserInfo or Token when connecting with // these urls. func (nc *Conn) Servers() []string
{ nc.mu.RLock() defer nc.mu.RUnlock() return nc.getServers(false) }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3674-L3678
go
train
// DiscoveredServers returns only the server urls that have been discovered // after a connection has been established. If authentication is enabled, // use UserInfo or Token when connecting with these urls.
func (nc *Conn) DiscoveredServers() []string
// DiscoveredServers returns only the server urls that have been discovered // after a connection has been established. If authentication is enabled, // use UserInfo or Token when connecting with these urls. func (nc *Conn) DiscoveredServers() []string
{ nc.mu.RLock() defer nc.mu.RUnlock() return nc.getServers(true) }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3681-L3685
go
train
// Status returns the current state of the connection.
func (nc *Conn) Status() Status
// Status returns the current state of the connection. func (nc *Conn) Status() Status
{ nc.mu.RLock() defer nc.mu.RUnlock() return nc.status }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3708-L3710
go
train
// Test if Conn is in the draining state.
func (nc *Conn) isDraining() bool
// Test if Conn is in the draining state. func (nc *Conn) isDraining() bool
{ return nc.status == DRAINING_SUBS || nc.status == DRAINING_PUBS }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3718-L3733
go
train
// Stats will return a race safe copy of the Statistics section for the connection.
func (nc *Conn) Stats() Statistics
// Stats will return a race safe copy of the Statistics section for the connection. func (nc *Conn) Stats() Statistics
{ // Stats are updated either under connection's mu or subsMu mutexes. // Lock both to safely get them. nc.mu.Lock() nc.subsMu.RLock() stats := Statistics{ InMsgs: nc.InMsgs, InBytes: nc.InBytes, OutMsgs: nc.OutMsgs, OutBytes: nc.OutBytes, Reconnects: nc.Reconnects, } nc.subsMu.RUnlock() nc.mu.Unlock() return stats }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3738-L3742
go
train
// MaxPayload returns the size limit that a message payload can have. // This is set by the server configuration and delivered to the client // upon connect.
func (nc *Conn) MaxPayload() int64
// MaxPayload returns the size limit that a message payload can have. // This is set by the server configuration and delivered to the client // upon connect. func (nc *Conn) MaxPayload() int64
{ nc.mu.RLock() defer nc.mu.RUnlock() return nc.info.MaxPayload }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3745-L3749
go
train
// AuthRequired will return if the connected server requires authorization.
func (nc *Conn) AuthRequired() bool
// AuthRequired will return if the connected server requires authorization. func (nc *Conn) AuthRequired() bool
{ nc.mu.RLock() defer nc.mu.RUnlock() return nc.info.AuthRequired }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3752-L3756
go
train
// TLSRequired will return if the connected server requires TLS connections.
func (nc *Conn) TLSRequired() bool
// TLSRequired will return if the connected server requires TLS connections. func (nc *Conn) TLSRequired() bool
{ nc.mu.RLock() defer nc.mu.RUnlock() return nc.info.TLSRequired }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3765-L3804
go
train
// Barrier schedules the given function `f` to all registered asynchronous // subscriptions. // Only the last subscription to see this barrier will invoke the function. // If no subscription is registered at the time of this call, `f()` is invoked // right away. // ErrConnectionClosed is returned if the connection is closed prior to // the call.
func (nc *Conn) Barrier(f func()) error
// Barrier schedules the given function `f` to all registered asynchronous // subscriptions. // Only the last subscription to see this barrier will invoke the function. // If no subscription is registered at the time of this call, `f()` is invoked // right away. // ErrConnectionClosed is returned if the connection is closed prior to // the call. func (nc *Conn) Barrier(f func()) error
{ nc.mu.Lock() if nc.isClosed() { nc.mu.Unlock() return ErrConnectionClosed } nc.subsMu.Lock() // Need to figure out how many non chan subscriptions there are numSubs := 0 for _, sub := range nc.subs { if sub.typ == AsyncSubscription { numSubs++ } } if numSubs == 0 { nc.subsMu.Unlock() nc.mu.Unlock() f() return nil } barrier := &barrierInfo{refs: int64(numSubs), f: f} for _, sub := range nc.subs { sub.mu.Lock() if sub.mch == nil { msg := &Msg{barrier: barrier} // Push onto the async pList if sub.pTail != nil { sub.pTail.next = msg } else { sub.pHead = msg sub.pCond.Signal() } sub.pTail = msg } sub.mu.Unlock() } nc.subsMu.Unlock() nc.mu.Unlock() return nil }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3811-L3821
go
train
// GetClientID returns the client ID assigned by the server to which // the client is currently connected to. Note that the value may change if // the client reconnects. // This function returns ErrNoClientIDReturned if the server is of a // version prior to 1.2.0.
func (nc *Conn) GetClientID() (uint64, error)
// GetClientID returns the client ID assigned by the server to which // the client is currently connected to. Note that the value may change if // the client reconnects. // This function returns ErrNoClientIDReturned if the server is of a // version prior to 1.2.0. func (nc *Conn) GetClientID() (uint64, error)
{ nc.mu.RLock() defer nc.mu.RUnlock() if nc.isClosed() { return 0, ErrConnectionClosed } if nc.info.CID == 0 { return 0, ErrClientIDNotSupported } return nc.info.CID, nil }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3827-L3846
go
train
// NkeyOptionFromSeed will load an nkey pair from a seed file. // It will return the NKey Option and will handle // signing of nonce challenges from the server. It will take // care to not hold keys in memory and to wipe memory.
func NkeyOptionFromSeed(seedFile string) (Option, error)
// NkeyOptionFromSeed will load an nkey pair from a seed file. // It will return the NKey Option and will handle // signing of nonce challenges from the server. It will take // care to not hold keys in memory and to wipe memory. func NkeyOptionFromSeed(seedFile string) (Option, error)
{ kp, err := nkeyPairFromSeedFile(seedFile) if err != nil { return nil, err } // Wipe our key on exit. defer kp.Wipe() pub, err := kp.PublicKey() if err != nil { return nil, err } if !nkeys.IsValidPublicUserKey(pub) { return nil, fmt.Errorf("nats: Not a valid nkey user seed") } sigCB := func(nonce []byte) ([]byte, error) { return sigHandler(nonce, seedFile) } return Nkey(string(pub), sigCB), nil }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3916-L3926
go
train
// Sign authentication challenges from the server. // Do not keep private seed in memory.
func sigHandler(nonce []byte, seedFile string) ([]byte, error)
// Sign authentication challenges from the server. // Do not keep private seed in memory. func sigHandler(nonce []byte, seedFile string) ([]byte, error)
{ kp, err := nkeyPairFromSeedFile(seedFile) if err != nil { return nil, err } // Wipe our key on exit. defer kp.Wipe() sig, _ := kp.Sign(nonce) return sig, nil }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3942-L3952
go
train
// Write implements the io.Writer interface.
func (tw *timeoutWriter) Write(p []byte) (int, error)
// Write implements the io.Writer interface. func (tw *timeoutWriter) Write(p []byte) (int, error)
{ if tw.err != nil { return 0, tw.err } var n int tw.conn.SetWriteDeadline(time.Now().Add(tw.timeout)) n, tw.err = tw.conn.Write(p) tw.conn.SetWriteDeadline(time.Time{}) return n, tw.err }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
encoders/protobuf/protobuf_enc.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/encoders/protobuf/protobuf_enc.go#L46-L60
go
train
// Encode
func (pb *ProtobufEncoder) Encode(subject string, v interface{}) ([]byte, error)
// Encode func (pb *ProtobufEncoder) Encode(subject string, v interface{}) ([]byte, error)
{ if v == nil { return nil, nil } i, found := v.(proto.Message) if !found { return nil, ErrInvalidProtoMsgEncode } b, err := proto.Marshal(i) if err != nil { return nil, err } return b, nil }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
encoders/protobuf/protobuf_enc.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/encoders/protobuf/protobuf_enc.go#L63-L73
go
train
// Decode
func (pb *ProtobufEncoder) Decode(subject string, data []byte, vPtr interface{}) error
// Decode func (pb *ProtobufEncoder) Decode(subject string, data []byte, vPtr interface{}) error
{ if _, ok := vPtr.(*interface{}); ok { return nil } i, found := vPtr.(proto.Message) if !found { return ErrInvalidProtoMsgDecode } return proto.Unmarshal(data, i) }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
util/tls.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/util/tls.go#L21-L27
go
train
// CloneTLSConfig returns a copy of c.
func CloneTLSConfig(c *tls.Config) *tls.Config
// CloneTLSConfig returns a copy of c. func CloneTLSConfig(c *tls.Config) *tls.Config
{ if c == nil { return &tls.Config{} } return c.Clone() }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
encoders/builtin/json_enc.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/encoders/builtin/json_enc.go#L29-L35
go
train
// Encode
func (je *JsonEncoder) Encode(subject string, v interface{}) ([]byte, error)
// Encode func (je *JsonEncoder) Encode(subject string, v interface{}) ([]byte, error)
{ b, err := json.Marshal(v) if err != nil { return nil, err } return b, nil }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
encoders/builtin/json_enc.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/encoders/builtin/json_enc.go#L38-L56
go
train
// Decode
func (je *JsonEncoder) Decode(subject string, data []byte, vPtr interface{}) (err error)
// Decode func (je *JsonEncoder) Decode(subject string, data []byte, vPtr interface{}) (err error)
{ switch arg := vPtr.(type) { case *string: // If they want a string and it is a JSON string, strip quotes // This allows someone to send a struct but receive as a plain string // This cast should be efficient for Go 1.3 and beyond. str := string(data) if strings.HasPrefix(str, `"`) && strings.HasSuffix(str, `"`) { *arg = str[1 : len(str)-1] } else { *arg = str } case *[]byte: *arg = data default: err = json.Unmarshal(data, arg) } return }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
context.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/context.go#L26-L89
go
train
// RequestWithContext takes a context, a subject and payload // in bytes and request expecting a single response.
func (nc *Conn) RequestWithContext(ctx context.Context, subj string, data []byte) (*Msg, error)
// RequestWithContext takes a context, a subject and payload // in bytes and request expecting a single response. func (nc *Conn) RequestWithContext(ctx context.Context, subj string, data []byte) (*Msg, error)
{ if ctx == nil { return nil, ErrInvalidContext } if nc == nil { return nil, ErrInvalidConnection } // Check whether the context is done already before making // the request. if ctx.Err() != nil { return nil, ctx.Err() } nc.mu.Lock() // If user wants the old style. if nc.Opts.UseOldRequestStyle { nc.mu.Unlock() return nc.oldRequestWithContext(ctx, subj, data) } // Do setup for the new style. if nc.respMap == nil { nc.initNewResp() } // Create literal Inbox and map to a chan msg. mch := make(chan *Msg, RequestChanLen) respInbox := nc.newRespInbox() token := respToken(respInbox) nc.respMap[token] = mch createSub := nc.respMux == nil ginbox := nc.respSub nc.mu.Unlock() if createSub { // Make sure scoped subscription is setup only once. var err error nc.respSetup.Do(func() { err = nc.createRespMux(ginbox) }) if err != nil { return nil, err } } err := nc.PublishRequest(subj, respInbox, data) if err != nil { return nil, err } var ok bool var msg *Msg select { case msg, ok = <-mch: if !ok { return nil, ErrConnectionClosed } case <-ctx.Done(): nc.mu.Lock() delete(nc.respMap, token) nc.mu.Unlock() return nil, ctx.Err() } return msg, nil }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
context.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/context.go#L92-L109
go
train
// oldRequestWithContext utilizes inbox and subscription per request.
func (nc *Conn) oldRequestWithContext(ctx context.Context, subj string, data []byte) (*Msg, error)
// oldRequestWithContext utilizes inbox and subscription per request. func (nc *Conn) oldRequestWithContext(ctx context.Context, subj string, data []byte) (*Msg, error)
{ inbox := NewInbox() ch := make(chan *Msg, RequestChanLen) s, err := nc.subscribe(inbox, _EMPTY_, nil, ch, true) if err != nil { return nil, err } s.AutoUnsubscribe(1) defer s.Unsubscribe() err = nc.PublishRequest(subj, inbox, data) if err != nil { return nil, err } return s.NextMsgWithContext(ctx) }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
context.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/context.go#L114-L166
go
train
// NextMsgWithContext takes a context and returns the next message // available to a synchronous subscriber, blocking until it is delivered // or context gets canceled.
func (s *Subscription) NextMsgWithContext(ctx context.Context) (*Msg, error)
// NextMsgWithContext takes a context and returns the next message // available to a synchronous subscriber, blocking until it is delivered // or context gets canceled. func (s *Subscription) NextMsgWithContext(ctx context.Context) (*Msg, error)
{ if ctx == nil { return nil, ErrInvalidContext } if s == nil { return nil, ErrBadSubscription } if ctx.Err() != nil { return nil, ctx.Err() } s.mu.Lock() err := s.validateNextMsgState() if err != nil { s.mu.Unlock() return nil, err } // snapshot mch := s.mch s.mu.Unlock() var ok bool var msg *Msg // If something is available right away, let's optimize that case. select { case msg, ok = <-mch: if !ok { return nil, ErrConnectionClosed } if err := s.processNextMsgDelivered(msg); err != nil { return nil, err } else { return msg, nil } default: } select { case msg, ok = <-mch: if !ok { return nil, ErrConnectionClosed } if err := s.processNextMsgDelivered(msg); err != nil { return nil, err } case <-ctx.Done(): return nil, ctx.Err() } return msg, nil }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
context.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/context.go#L171-L212
go
train
// FlushWithContext will allow a context to control the duration // of a Flush() call. This context should be non-nil and should // have a deadline set. We will return an error if none is present.
func (nc *Conn) FlushWithContext(ctx context.Context) error
// FlushWithContext will allow a context to control the duration // of a Flush() call. This context should be non-nil and should // have a deadline set. We will return an error if none is present. func (nc *Conn) FlushWithContext(ctx context.Context) error
{ if nc == nil { return ErrInvalidConnection } if ctx == nil { return ErrInvalidContext } _, ok := ctx.Deadline() if !ok { return ErrNoDeadlineContext } nc.mu.Lock() if nc.isClosed() { nc.mu.Unlock() return ErrConnectionClosed } // Create a buffered channel to prevent chan send to block // in processPong() ch := make(chan struct{}, 1) nc.sendPing(ch) nc.mu.Unlock() var err error select { case _, ok := <-ch: if !ok { err = ErrConnectionClosed } else { close(ch) } case <-ctx.Done(): err = ctx.Err() } if err != nil { nc.removeFlushEntry(ch) } return err }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
context.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/context.go#L217-L241
go
train
// RequestWithContext will create an Inbox and perform a Request // using the provided cancellation context with the Inbox reply // for the data v. A response will be decoded into the vPtrResponse.
func (c *EncodedConn) RequestWithContext(ctx context.Context, subject string, v interface{}, vPtr interface{}) error
// RequestWithContext will create an Inbox and perform a Request // using the provided cancellation context with the Inbox reply // for the data v. A response will be decoded into the vPtrResponse. func (c *EncodedConn) RequestWithContext(ctx context.Context, subject string, v interface{}, vPtr interface{}) error
{ if ctx == nil { return ErrInvalidContext } b, err := c.Enc.Encode(subject, v) if err != nil { return err } m, err := c.Conn.RequestWithContext(ctx, subject, b) if err != nil { return err } if reflect.TypeOf(vPtr) == emptyMsgType { mPtr := vPtr.(*Msg) *mPtr = *m } else { err := c.Enc.Decode(m.Subject, m.Data, vPtr) if err != nil { return err } } return nil }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
netchan.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/netchan.go#L26-L33
go
train
// This allows the functionality for network channels by binding send and receive Go chans // to subjects and optionally queue groups. // Data will be encoded and decoded via the EncodedConn and its associated encoders. // BindSendChan binds a channel for send operations to NATS.
func (c *EncodedConn) BindSendChan(subject string, channel interface{}) error
// This allows the functionality for network channels by binding send and receive Go chans // to subjects and optionally queue groups. // Data will be encoded and decoded via the EncodedConn and its associated encoders. // BindSendChan binds a channel for send operations to NATS. func (c *EncodedConn) BindSendChan(subject string, channel interface{}) error
{ chVal := reflect.ValueOf(channel) if chVal.Kind() != reflect.Chan { return ErrChanArg } go chPublish(c, chVal, subject) return nil }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
netchan.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/netchan.go#L37-L61
go
train
// Publish all values that arrive on the channel until it is closed or we // encounter an error.
func chPublish(c *EncodedConn, chVal reflect.Value, subject string)
// Publish all values that arrive on the channel until it is closed or we // encounter an error. func chPublish(c *EncodedConn, chVal reflect.Value, subject string)
{ for { val, ok := chVal.Recv() if !ok { // Channel has most likely been closed. return } if e := c.Publish(subject, val.Interface()); e != nil { // Do this under lock. c.Conn.mu.Lock() defer c.Conn.mu.Unlock() if c.Conn.Opts.AsyncErrorCB != nil { // FIXME(dlc) - Not sure this is the right thing to do. // FIXME(ivan) - If the connection is not yet closed, try to schedule the callback if c.Conn.isClosed() { go c.Conn.Opts.AsyncErrorCB(c.Conn, nil, e) } else { c.Conn.ach.push(func() { c.Conn.Opts.AsyncErrorCB(c.Conn, nil, e) }) } } return } } }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
netchan.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/netchan.go#L64-L66
go
train
// BindRecvChan binds a channel for receive operations from NATS.
func (c *EncodedConn) BindRecvChan(subject string, channel interface{}) (*Subscription, error)
// BindRecvChan binds a channel for receive operations from NATS. func (c *EncodedConn) BindRecvChan(subject string, channel interface{}) (*Subscription, error)
{ return c.bindRecvChan(subject, _EMPTY_, channel) }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
netchan.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/netchan.go#L69-L71
go
train
// BindRecvQueueChan binds a channel for queue-based receive operations from NATS.
func (c *EncodedConn) BindRecvQueueChan(subject, queue string, channel interface{}) (*Subscription, error)
// BindRecvQueueChan binds a channel for queue-based receive operations from NATS. func (c *EncodedConn) BindRecvQueueChan(subject, queue string, channel interface{}) (*Subscription, error)
{ return c.bindRecvChan(subject, queue, channel) }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
netchan.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/netchan.go#L74-L111
go
train
// Internal function to bind receive operations for a channel.
func (c *EncodedConn) bindRecvChan(subject, queue string, channel interface{}) (*Subscription, error)
// Internal function to bind receive operations for a channel. func (c *EncodedConn) bindRecvChan(subject, queue string, channel interface{}) (*Subscription, error)
{ chVal := reflect.ValueOf(channel) if chVal.Kind() != reflect.Chan { return nil, ErrChanArg } argType := chVal.Type().Elem() cb := func(m *Msg) { var oPtr reflect.Value if argType.Kind() != reflect.Ptr { oPtr = reflect.New(argType) } else { oPtr = reflect.New(argType.Elem()) } if err := c.Enc.Decode(m.Subject, m.Data, oPtr.Interface()); err != nil { c.Conn.err = errors.New("nats: Got an error trying to unmarshal: " + err.Error()) if c.Conn.Opts.AsyncErrorCB != nil { c.Conn.ach.push(func() { c.Conn.Opts.AsyncErrorCB(c.Conn, m.Sub, c.Conn.err) }) } return } if argType.Kind() != reflect.Ptr { oPtr = reflect.Indirect(oPtr) } // This is a bit hacky, but in this instance we may be trying to send to a closed channel. // and the user does not know when it is safe to close the channel. defer func() { // If we have panicked, recover and close the subscription. if r := recover(); r != nil { m.Sub.Unsubscribe() } }() // Actually do the send to the channel. chVal.Send(oPtr) } return c.Conn.subscribe(subject, queue, cb, nil, false) }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
examples/nats-echo/main.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/examples/nats-echo/main.go#L153-L166
go
train
// lookup our current region and country..
func lookupGeo() string
// lookup our current region and country.. func lookupGeo() string
{ c := &http.Client{Timeout: 2 * time.Second} resp, err := c.Get("https://ipinfo.io") if err != nil || resp == nil { log.Fatalf("Could not retrive geo location data: %v", err) } defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) g := geo{} if err := json.Unmarshal(body, &g); err != nil { log.Fatalf("Error unmarshalling geo: %v", err) } return g.Region + ", " + g.Country }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
bench/bench.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L58-L65
go
train
// NewBenchmark initializes a Benchmark. After creating a bench call AddSubSample/AddPubSample. // When done collecting samples, call EndBenchmark
func NewBenchmark(name string, subCnt, pubCnt int) *Benchmark
// NewBenchmark initializes a Benchmark. After creating a bench call AddSubSample/AddPubSample. // When done collecting samples, call EndBenchmark func NewBenchmark(name string, subCnt, pubCnt int) *Benchmark
{ bm := Benchmark{Name: name, RunID: nuid.Next()} bm.Subs = NewSampleGroup() bm.Pubs = NewSampleGroup() bm.subChannel = make(chan *Sample, subCnt) bm.pubChannel = make(chan *Sample, pubCnt) return &bm }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
bench/bench.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L68-L107
go
train
// Close organizes collected Samples and calculates aggregates. After Close(), no more samples can be added.
func (bm *Benchmark) Close()
// Close organizes collected Samples and calculates aggregates. After Close(), no more samples can be added. func (bm *Benchmark) Close()
{ close(bm.subChannel) close(bm.pubChannel) for s := range bm.subChannel { bm.Subs.AddSample(s) } for s := range bm.pubChannel { bm.Pubs.AddSample(s) } if bm.Subs.HasSamples() { bm.Start = bm.Subs.Start bm.End = bm.Subs.End } else { bm.Start = bm.Pubs.Start bm.End = bm.Pubs.End } if bm.Subs.HasSamples() && bm.Pubs.HasSamples() { if bm.Start.After(bm.Subs.Start) { bm.Start = bm.Subs.Start } if bm.Start.After(bm.Pubs.Start) { bm.Start = bm.Pubs.Start } if bm.End.Before(bm.Subs.End) { bm.End = bm.Subs.End } if bm.End.Before(bm.Pubs.End) { bm.End = bm.Pubs.End } } bm.MsgBytes = bm.Pubs.MsgBytes + bm.Subs.MsgBytes bm.IOBytes = bm.Pubs.IOBytes + bm.Subs.IOBytes bm.MsgCnt = bm.Pubs.MsgCnt + bm.Subs.MsgCnt bm.JobMsgCnt = bm.Pubs.JobMsgCnt + bm.Subs.JobMsgCnt }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
bench/bench.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L120-L143
go
train
// CSV generates a csv report of all the samples collected
func (bm *Benchmark) CSV() string
// CSV generates a csv report of all the samples collected func (bm *Benchmark) CSV() string
{ var buffer bytes.Buffer writer := csv.NewWriter(&buffer) headers := []string{"#RunID", "ClientID", "MsgCount", "MsgBytes", "MsgsPerSec", "BytesPerSec", "DurationSecs"} if err := writer.Write(headers); err != nil { log.Fatalf("Error while serializing headers %q: %v", headers, err) } groups := []*SampleGroup{bm.Subs, bm.Pubs} pre := "S" for i, g := range groups { if i == 1 { pre = "P" } for j, c := range g.Samples { r := []string{bm.RunID, fmt.Sprintf("%s%d", pre, j), fmt.Sprintf("%d", c.MsgCnt), fmt.Sprintf("%d", c.MsgBytes), fmt.Sprintf("%d", c.Rate()), fmt.Sprintf("%f", c.Throughput()), fmt.Sprintf("%f", c.Duration().Seconds())} if err := writer.Write(r); err != nil { log.Fatalf("Error while serializing %v: %v", c, err) } } } writer.Flush() return buffer.String() }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
bench/bench.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L146-L152
go
train
// NewSample creates a new Sample initialized to the provided values. The nats.Conn information captured
func NewSample(jobCount int, msgSize int, start, end time.Time, nc *nats.Conn) *Sample
// NewSample creates a new Sample initialized to the provided values. The nats.Conn information captured func NewSample(jobCount int, msgSize int, start, end time.Time, nc *nats.Conn) *Sample
{ s := Sample{JobMsgCnt: jobCount, Start: start, End: end} s.MsgBytes = uint64(msgSize * jobCount) s.MsgCnt = nc.OutMsgs + nc.InMsgs s.IOBytes = nc.OutBytes + nc.InBytes return &s }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
bench/bench.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L155-L157
go
train
// Throughput of bytes per second
func (s *Sample) Throughput() float64
// Throughput of bytes per second func (s *Sample) Throughput() float64
{ return float64(s.MsgBytes) / s.Duration().Seconds() }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
bench/bench.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L160-L162
go
train
// Rate of meessages in the job per second
func (s *Sample) Rate() int64
// Rate of meessages in the job per second func (s *Sample) Rate() int64
{ return int64(float64(s.JobMsgCnt) / s.Duration().Seconds()) }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
bench/bench.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L171-L173
go
train
// Duration that the sample was active
func (s *Sample) Duration() time.Duration
// Duration that the sample was active func (s *Sample) Duration() time.Duration
{ return s.End.Sub(s.Start) }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
bench/bench.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L181-L185
go
train
// NewSampleGroup initializer
func NewSampleGroup() *SampleGroup
// NewSampleGroup initializer func NewSampleGroup() *SampleGroup
{ s := new(SampleGroup) s.Samples = make([]*Sample, 0) return s }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
bench/bench.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L188-L190
go
train
// Statistics information of the sample group (min, average, max and standard deviation)
func (sg *SampleGroup) Statistics() string
// Statistics information of the sample group (min, average, max and standard deviation) func (sg *SampleGroup) Statistics() string
{ return fmt.Sprintf("min %s | avg %s | max %s | stddev %s msgs", commaFormat(sg.MinRate()), commaFormat(sg.AvgRate()), commaFormat(sg.MaxRate()), commaFormat(int64(sg.StdDev()))) }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
bench/bench.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L193-L202
go
train
// MinRate returns the smallest message rate in the SampleGroup
func (sg *SampleGroup) MinRate() int64
// MinRate returns the smallest message rate in the SampleGroup func (sg *SampleGroup) MinRate() int64
{ m := int64(0) for i, s := range sg.Samples { if i == 0 { m = s.Rate() } m = min(m, s.Rate()) } return m }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
bench/bench.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L205-L214
go
train
// MaxRate returns the largest message rate in the SampleGroup
func (sg *SampleGroup) MaxRate() int64
// MaxRate returns the largest message rate in the SampleGroup func (sg *SampleGroup) MaxRate() int64
{ m := int64(0) for i, s := range sg.Samples { if i == 0 { m = s.Rate() } m = max(m, s.Rate()) } return m }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
bench/bench.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L217-L223
go
train
// AvgRate returns the average of all the message rates in the SampleGroup
func (sg *SampleGroup) AvgRate() int64
// AvgRate returns the average of all the message rates in the SampleGroup func (sg *SampleGroup) AvgRate() int64
{ sum := uint64(0) for _, s := range sg.Samples { sum += uint64(s.Rate()) } return int64(sum / uint64(len(sg.Samples))) }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
bench/bench.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L226-L234
go
train
// StdDev returns the standard deviation the message rates in the SampleGroup
func (sg *SampleGroup) StdDev() float64
// StdDev returns the standard deviation the message rates in the SampleGroup func (sg *SampleGroup) StdDev() float64
{ avg := float64(sg.AvgRate()) sum := float64(0) for _, c := range sg.Samples { sum += math.Pow(float64(c.Rate())-avg, 2) } variance := sum / float64(len(sg.Samples)) return math.Sqrt(variance) }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
bench/bench.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L237-L256
go
train
// AddSample adds a Sample to the SampleGroup. After adding a Sample it shouldn't be modified.
func (sg *SampleGroup) AddSample(e *Sample)
// AddSample adds a Sample to the SampleGroup. After adding a Sample it shouldn't be modified. func (sg *SampleGroup) AddSample(e *Sample)
{ sg.Samples = append(sg.Samples, e) if len(sg.Samples) == 1 { sg.Start = e.Start sg.End = e.End } sg.IOBytes += e.IOBytes sg.JobMsgCnt += e.JobMsgCnt sg.MsgCnt += e.MsgCnt sg.MsgBytes += e.MsgBytes if e.Start.Before(sg.Start) { sg.Start = e.Start } if e.End.After(sg.End) { sg.End = e.End } }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
bench/bench.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L264-L296
go
train
// Report returns a human readable report of the samples taken in the Benchmark
func (bm *Benchmark) Report() string
// Report returns a human readable report of the samples taken in the Benchmark func (bm *Benchmark) Report() string
{ var buffer bytes.Buffer indent := "" if !bm.Pubs.HasSamples() && !bm.Subs.HasSamples() { return "No publisher or subscribers. Nothing to report." } if bm.Pubs.HasSamples() && bm.Subs.HasSamples() { buffer.WriteString(fmt.Sprintf("%s Pub/Sub stats: %s\n", bm.Name, bm)) indent += " " } if bm.Pubs.HasSamples() { buffer.WriteString(fmt.Sprintf("%sPub stats: %s\n", indent, bm.Pubs)) if len(bm.Pubs.Samples) > 1 { for i, stat := range bm.Pubs.Samples { buffer.WriteString(fmt.Sprintf("%s [%d] %v (%d msgs)\n", indent, i+1, stat, stat.JobMsgCnt)) } buffer.WriteString(fmt.Sprintf("%s %s\n", indent, bm.Pubs.Statistics())) } } if bm.Subs.HasSamples() { buffer.WriteString(fmt.Sprintf("%sSub stats: %s\n", indent, bm.Subs)) if len(bm.Subs.Samples) > 1 { for i, stat := range bm.Subs.Samples { buffer.WriteString(fmt.Sprintf("%s [%d] %v (%d msgs)\n", indent, i+1, stat, stat.JobMsgCnt)) } buffer.WriteString(fmt.Sprintf("%s %s\n", indent, bm.Subs.Statistics())) } } return buffer.String() }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
bench/bench.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L317-L333
go
train
// HumanBytes formats bytes as a human readable string
func HumanBytes(bytes float64, si bool) string
// HumanBytes formats bytes as a human readable string func HumanBytes(bytes float64, si bool) string
{ var base = 1024 pre := []string{"K", "M", "G", "T", "P", "E"} var post = "B" if si { base = 1000 pre = []string{"k", "M", "G", "T", "P", "E"} post = "iB" } if bytes < float64(base) { return fmt.Sprintf("%.2f B", bytes) } exp := int(math.Log(bytes) / math.Log(float64(base))) index := exp - 1 units := pre[index] + post return fmt.Sprintf("%.2f %s", bytes/math.Pow(float64(base), float64(exp)), units) }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
bench/bench.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L350-L365
go
train
// MsgsPerClient divides the number of messages by the number of clients and tries to distribute them as evenly as possible
func MsgsPerClient(numMsgs, numClients int) []int
// MsgsPerClient divides the number of messages by the number of clients and tries to distribute them as evenly as possible func MsgsPerClient(numMsgs, numClients int) []int
{ var counts []int if numClients == 0 || numMsgs == 0 { return counts } counts = make([]int, numClients) mc := numMsgs / numClients for i := 0; i < numClients; i++ { counts[i] = mc } extra := numMsgs % numClients for i := 0; i < extra; i++ { counts[i]++ } return counts }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
timer.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/timer.go#L31-L38
go
train
// Get returns a timer that completes after the given duration.
func (tp *timerPool) Get(d time.Duration) *time.Timer
// Get returns a timer that completes after the given duration. func (tp *timerPool) Get(d time.Duration) *time.Timer
{ if t, _ := tp.p.Get().(*time.Timer); t != nil { t.Reset(d) return t } return time.NewTimer(d) }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
timer.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/timer.go#L47-L56
go
train
// Put pools the given timer. // // There is no need to call t.Stop() before calling Put. // // Put will try to stop the timer before pooling. If the // given timer already expired, Put will read the unreceived // value if there is one.
func (tp *timerPool) Put(t *time.Timer)
// Put pools the given timer. // // There is no need to call t.Stop() before calling Put. // // Put will try to stop the timer before pooling. If the // given timer already expired, Put will read the unreceived // value if there is one. func (tp *timerPool) Put(t *time.Timer)
{ if !t.Stop() { select { case <-t.C: default: } } tp.p.Put(t) }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
encoders/builtin/gob_enc.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/encoders/builtin/gob_enc.go#L31-L38
go
train
// FIXME(dlc) - This could probably be more efficient. // Encode
func (ge *GobEncoder) Encode(subject string, v interface{}) ([]byte, error)
// FIXME(dlc) - This could probably be more efficient. // Encode func (ge *GobEncoder) Encode(subject string, v interface{}) ([]byte, error)
{ b := new(bytes.Buffer) enc := gob.NewEncoder(b) if err := enc.Encode(v); err != nil { return nil, err } return b.Bytes(), nil }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
encoders/builtin/gob_enc.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/encoders/builtin/gob_enc.go#L41-L45
go
train
// Decode
func (ge *GobEncoder) Decode(subject string, data []byte, vPtr interface{}) (err error)
// Decode func (ge *GobEncoder) Decode(subject string, data []byte, vPtr interface{}) (err error)
{ dec := gob.NewDecoder(bytes.NewBuffer(data)) err = dec.Decode(vPtr) return }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/blacklist.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/blacklist.go#L50-L59
go
train
// NewBlacklistedImports reports when a blacklisted import is being used. // Typically when a deprecated technology is being used.
func NewBlacklistedImports(id string, conf gosec.Config, blacklist map[string]string) (gosec.Rule, []ast.Node)
// NewBlacklistedImports reports when a blacklisted import is being used. // Typically when a deprecated technology is being used. func NewBlacklistedImports(id string, conf gosec.Config, blacklist map[string]string) (gosec.Rule, []ast.Node)
{ return &blacklistedImport{ MetaData: gosec.MetaData{ ID: id, Severity: gosec.Medium, Confidence: gosec.High, }, Blacklisted: blacklist, }, []ast.Node{(*ast.ImportSpec)(nil)} }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/blacklist.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/blacklist.go#L76-L80
go
train
// NewBlacklistedImportRC4 fails if DES is imported
func NewBlacklistedImportRC4(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
// NewBlacklistedImportRC4 fails if DES is imported func NewBlacklistedImportRC4(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
{ return NewBlacklistedImports(id, conf, map[string]string{ "crypto/rc4": "Blacklisted import crypto/rc4: weak cryptographic primitive", }) }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/hardcoded_credentials.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/hardcoded_credentials.go#L101-L147
go
train
// NewHardcodedCredentials attempts to find high entropy string constants being // assigned to variables that appear to be related to credentials.
func NewHardcodedCredentials(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
// NewHardcodedCredentials attempts to find high entropy string constants being // assigned to variables that appear to be related to credentials. func NewHardcodedCredentials(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
{ pattern := `(?i)passwd|pass|password|pwd|secret|token` entropyThreshold := 80.0 perCharThreshold := 3.0 ignoreEntropy := false var truncateString = 16 if val, ok := conf["G101"]; ok { conf := val.(map[string]string) if configPattern, ok := conf["pattern"]; ok { pattern = configPattern } if configIgnoreEntropy, ok := conf["ignore_entropy"]; ok { if parsedBool, err := strconv.ParseBool(configIgnoreEntropy); err == nil { ignoreEntropy = parsedBool } } if configEntropyThreshold, ok := conf["entropy_threshold"]; ok { if parsedNum, err := strconv.ParseFloat(configEntropyThreshold, 64); err == nil { entropyThreshold = parsedNum } } if configCharThreshold, ok := conf["per_char_threshold"]; ok { if parsedNum, err := strconv.ParseFloat(configCharThreshold, 64); err == nil { perCharThreshold = parsedNum } } if configTruncate, ok := conf["truncate"]; ok { if parsedInt, err := strconv.Atoi(configTruncate); err == nil { truncateString = parsedInt } } } return &credentials{ pattern: regexp.MustCompile(pattern), entropyThreshold: entropyThreshold, perCharThreshold: perCharThreshold, ignoreEntropy: ignoreEntropy, truncate: truncateString, MetaData: gosec.MetaData{ ID: id, What: "Potential hardcoded credentials", Confidence: gosec.Low, Severity: gosec.High, }, }, []ast.Node{(*ast.AssignStmt)(nil), (*ast.ValueSpec)(nil)} }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/bind.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/bind.go#L69-L83
go
train
// NewBindsToAllNetworkInterfaces detects socket connections that are setup to // listen on all network interfaces.
func NewBindsToAllNetworkInterfaces(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
// NewBindsToAllNetworkInterfaces detects socket connections that are setup to // listen on all network interfaces. func NewBindsToAllNetworkInterfaces(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
{ calls := gosec.NewCallList() calls.Add("net", "Listen") calls.Add("crypto/tls", "Listen") return &bindsToAllNetworkInterfaces{ calls: calls, pattern: regexp.MustCompile(`^(0.0.0.0|:).*$`), MetaData: gosec.MetaData{ ID: id, Severity: gosec.Medium, Confidence: gosec.High, What: "Binds to all network interfaces", }, }, []ast.Node{(*ast.CallExpr)(nil)} }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/fileperms.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/fileperms.go#L65-L78
go
train
// NewFilePerms creates a rule to detect file creation with a more permissive than configured // permission mask.
func NewFilePerms(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
// NewFilePerms creates a rule to detect file creation with a more permissive than configured // permission mask. func NewFilePerms(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
{ mode := getConfiguredMode(conf, "G302", 0600) return &filePermissions{ mode: mode, pkg: "os", calls: []string{"OpenFile", "Chmod"}, MetaData: gosec.MetaData{ ID: id, Severity: gosec.Medium, Confidence: gosec.High, What: fmt.Sprintf("Expect file permissions to be %#o or less", mode), }, }, []ast.Node{(*ast.CallExpr)(nil)} }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/rsa.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/rsa.go#L44-L58
go
train
// NewWeakKeyStrength builds a rule that detects RSA keys < 2048 bits
func NewWeakKeyStrength(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
// NewWeakKeyStrength builds a rule that detects RSA keys < 2048 bits func NewWeakKeyStrength(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
{ calls := gosec.NewCallList() calls.Add("crypto/rsa", "GenerateKey") bits := 2048 return &weakKeyStrength{ calls: calls, bits: bits, MetaData: gosec.MetaData{ ID: id, Severity: gosec.Medium, Confidence: gosec.High, What: fmt.Sprintf("RSA keys should be at least %d bits", bits), }, }, []ast.Node{(*ast.CallExpr)(nil)} }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/subproc.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/subproc.go#L42-L55
go
train
// TODO(gm) The only real potential for command injection with a Go project // is something like this: // // syscall.Exec("/bin/sh", []string{"-c", tainted}) // // E.g. Input is correctly escaped but the execution context being used // is unsafe. For example: // // syscall.Exec("echo", "foobar" + tainted)
func (r *subprocess) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error)
// TODO(gm) The only real potential for command injection with a Go project // is something like this: // // syscall.Exec("/bin/sh", []string{"-c", tainted}) // // E.g. Input is correctly escaped but the execution context being used // is unsafe. For example: // // syscall.Exec("echo", "foobar" + tainted) func (r *subprocess) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error)
{ if node := r.ContainsCallExpr(n, c, false); node != nil { for _, arg := range node.Args { if ident, ok := arg.(*ast.Ident); ok { obj := c.Info.ObjectOf(ident) if _, ok := obj.(*types.Var); ok && !gosec.TryResolve(ident, c) { return gosec.NewIssue(c, n, r.ID(), "Subprocess launched with variable", gosec.Medium, gosec.High), nil } } } return gosec.NewIssue(c, n, r.ID(), "Subprocess launching should be audited", gosec.Low, gosec.High), nil } return nil, nil }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/subproc.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/subproc.go#L58-L64
go
train
// NewSubproc detects cases where we are forking out to an external process
func NewSubproc(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
// NewSubproc detects cases where we are forking out to an external process func NewSubproc(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
{ rule := &subprocess{gosec.MetaData{ID: id}, gosec.NewCallList()} rule.Add("os/exec", "Command") rule.Add("os/exec", "CommandContext") rule.Add("syscall", "Exec") return rule, []ast.Node{(*ast.CallExpr)(nil)} }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
cmd/gosecutil/tools.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/cmd/gosecutil/tools.go#L36-L46
go
train
// Custom commands / utilities to run instead of default analyzer
func newUtils() *utilities
// Custom commands / utilities to run instead of default analyzer func newUtils() *utilities
{ utils := make(map[string]command) utils["ast"] = dumpAst utils["callobj"] = dumpCallObj utils["uses"] = dumpUses utils["types"] = dumpTypes utils["defs"] = dumpDefs utils["comments"] = dumpComments utils["imports"] = dumpImports return &utilities{utils, make([]string, 0)} }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/archive.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/archive.go#L21-L44
go
train
// Match inspects AST nodes to determine if the filepath.Joins uses any argument derived from type zip.File
func (a *archive) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error)
// Match inspects AST nodes to determine if the filepath.Joins uses any argument derived from type zip.File func (a *archive) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error)
{ if node := a.calls.ContainsCallExpr(n, c, false); node != nil { for _, arg := range node.Args { var argType types.Type if selector, ok := arg.(*ast.SelectorExpr); ok { argType = c.Info.TypeOf(selector.X) } else if ident, ok := arg.(*ast.Ident); ok { if ident.Obj != nil && ident.Obj.Kind == ast.Var { decl := ident.Obj.Decl if assign, ok := decl.(*ast.AssignStmt); ok { if selector, ok := assign.Rhs[0].(*ast.SelectorExpr); ok { argType = c.Info.TypeOf(selector.X) } } } } if argType != nil && argType.String() == a.argType { return gosec.NewIssue(c, n, a.ID(), a.What, a.Severity, a.Confidence), nil } } } return nil, nil }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/archive.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/archive.go#L47-L60
go
train
// NewArchive creates a new rule which detects the file traversal when extracting zip archives
func NewArchive(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
// NewArchive creates a new rule which detects the file traversal when extracting zip archives func NewArchive(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
{ calls := gosec.NewCallList() calls.Add("path/filepath", "Join") return &archive{ calls: calls, argType: "*archive/zip.File", MetaData: gosec.MetaData{ ID: id, Severity: gosec.Medium, Confidence: gosec.High, What: "File traversal when extracting zip archive", }, }, []ast.Node{(*ast.CallExpr)(nil)} }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
call_list.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/call_list.go#L35-L39
go
train
// AddAll will add several calls to the call list at once
func (c CallList) AddAll(selector string, idents ...string)
// AddAll will add several calls to the call list at once func (c CallList) AddAll(selector string, idents ...string)
{ for _, ident := range idents { c.Add(selector, ident) } }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
call_list.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/call_list.go#L42-L47
go
train
// Add a selector and call to the call list
func (c CallList) Add(selector, ident string)
// Add a selector and call to the call list func (c CallList) Add(selector, ident string)
{ if _, ok := c[selector]; !ok { c[selector] = make(set) } c[selector][ident] = true }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
call_list.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/call_list.go#L51-L57
go
train
// Contains returns true if the package and function are /// members of this call list.
func (c CallList) Contains(selector, ident string) bool
// Contains returns true if the package and function are /// members of this call list. func (c CallList) Contains(selector, ident string) bool
{ if idents, ok := c[selector]; ok { _, found := idents[ident] return found } return false }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
call_list.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/call_list.go#L61-L90
go
train
// ContainsCallExpr resolves the call expression name and type /// or package and determines if it exists within the CallList
func (c CallList) ContainsCallExpr(n ast.Node, ctx *Context, stripVendor bool) *ast.CallExpr
// ContainsCallExpr resolves the call expression name and type /// or package and determines if it exists within the CallList func (c CallList) ContainsCallExpr(n ast.Node, ctx *Context, stripVendor bool) *ast.CallExpr
{ selector, ident, err := GetCallInfo(n, ctx) if err != nil { return nil } // Use only explicit path (optionally strip vendor path prefix) to reduce conflicts path, ok := GetImportPath(selector, ctx) if !ok { return nil } if stripVendor { if vendorIdx := strings.Index(path, vendorPath); vendorIdx >= 0 { path = path[vendorIdx+len(vendorPath):] } } if !c.Contains(path, ident) { return nil } return n.(*ast.CallExpr) /* // Try direct resolution if c.Contains(selector, ident) { log.Printf("c.Contains == true, %s, %s.", selector, ident) return n.(*ast.CallExpr) } */ }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
helpers.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L39-L60
go
train
// MatchCallByPackage ensures that the specified package is imported, // adjusts the name for any aliases and ignores cases that are // initialization only imports. // // Usage: // node, matched := MatchCallByPackage(n, ctx, "math/rand", "Read") //
func MatchCallByPackage(n ast.Node, c *Context, pkg string, names ...string) (*ast.CallExpr, bool)
// MatchCallByPackage ensures that the specified package is imported, // adjusts the name for any aliases and ignores cases that are // initialization only imports. // // Usage: // node, matched := MatchCallByPackage(n, ctx, "math/rand", "Read") // func MatchCallByPackage(n ast.Node, c *Context, pkg string, names ...string) (*ast.CallExpr, bool)
{ importedName, found := GetImportedName(pkg, c) if !found { return nil, false } if callExpr, ok := n.(*ast.CallExpr); ok { packageName, callName, err := GetCallInfo(callExpr, c) if err != nil { return nil, false } if packageName == importedName { for _, name := range names { if callName == name { return callExpr, true } } } } return nil, false }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
helpers.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L68-L83
go
train
// MatchCallByType ensures that the node is a call expression to a // specific object type. // // Usage: // node, matched := MatchCallByType(n, ctx, "bytes.Buffer", "WriteTo", "Write") //
func MatchCallByType(n ast.Node, ctx *Context, requiredType string, calls ...string) (*ast.CallExpr, bool)
// MatchCallByType ensures that the node is a call expression to a // specific object type. // // Usage: // node, matched := MatchCallByType(n, ctx, "bytes.Buffer", "WriteTo", "Write") // func MatchCallByType(n ast.Node, ctx *Context, requiredType string, calls ...string) (*ast.CallExpr, bool)
{ if callExpr, ok := n.(*ast.CallExpr); ok { typeName, callName, err := GetCallInfo(callExpr, ctx) if err != nil { return nil, false } if typeName == requiredType { for _, call := range calls { if call == callName { return callExpr, true } } } } return nil, false }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
helpers.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L86-L94
go
train
// MatchCompLit will match an ast.CompositeLit based on the supplied type
func MatchCompLit(n ast.Node, ctx *Context, required string) *ast.CompositeLit
// MatchCompLit will match an ast.CompositeLit based on the supplied type func MatchCompLit(n ast.Node, ctx *Context, required string) *ast.CompositeLit
{ if complit, ok := n.(*ast.CompositeLit); ok { typeOf := ctx.Info.TypeOf(complit) if typeOf.String() == required { return complit } } return nil }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
helpers.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L97-L102
go
train
// GetInt will read and return an integer value from an ast.BasicLit
func GetInt(n ast.Node) (int64, error)
// GetInt will read and return an integer value from an ast.BasicLit func GetInt(n ast.Node) (int64, error)
{ if node, ok := n.(*ast.BasicLit); ok && node.Kind == token.INT { return strconv.ParseInt(node.Value, 0, 64) } return 0, fmt.Errorf("Unexpected AST node type: %T", n) }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
helpers.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L105-L110
go
train
// GetFloat will read and return a float value from an ast.BasicLit
func GetFloat(n ast.Node) (float64, error)
// GetFloat will read and return a float value from an ast.BasicLit func GetFloat(n ast.Node) (float64, error)
{ if node, ok := n.(*ast.BasicLit); ok && node.Kind == token.FLOAT { return strconv.ParseFloat(node.Value, 64) } return 0.0, fmt.Errorf("Unexpected AST node type: %T", n) }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
helpers.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L113-L118
go
train
// GetChar will read and return a char value from an ast.BasicLit
func GetChar(n ast.Node) (byte, error)
// GetChar will read and return a char value from an ast.BasicLit func GetChar(n ast.Node) (byte, error)
{ if node, ok := n.(*ast.BasicLit); ok && node.Kind == token.CHAR { return node.Value[0], nil } return 0, fmt.Errorf("Unexpected AST node type: %T", n) }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
helpers.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L121-L126
go
train
// GetString will read and return a string value from an ast.BasicLit
func GetString(n ast.Node) (string, error)
// GetString will read and return a string value from an ast.BasicLit func GetString(n ast.Node) (string, error)
{ if node, ok := n.(*ast.BasicLit); ok && node.Kind == token.STRING { return strconv.Unquote(node.Value) } return "", fmt.Errorf("Unexpected AST node type: %T", n) }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
helpers.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L131-L142
go
train
// GetCallObject returns the object and call expression and associated // object for a given AST node. nil, nil will be returned if the // object cannot be resolved.
func GetCallObject(n ast.Node, ctx *Context) (*ast.CallExpr, types.Object)
// GetCallObject returns the object and call expression and associated // object for a given AST node. nil, nil will be returned if the // object cannot be resolved. func GetCallObject(n ast.Node, ctx *Context) (*ast.CallExpr, types.Object)
{ switch node := n.(type) { case *ast.CallExpr: switch fn := node.Fun.(type) { case *ast.Ident: return node, ctx.Info.Uses[fn] case *ast.SelectorExpr: return node, ctx.Info.Uses[fn.Sel] } } return nil, nil }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
helpers.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L146-L167
go
train
// GetCallInfo returns the package or type and name associated with a // call expression.
func GetCallInfo(n ast.Node, ctx *Context) (string, string, error)
// GetCallInfo returns the package or type and name associated with a // call expression. func GetCallInfo(n ast.Node, ctx *Context) (string, string, error)
{ switch node := n.(type) { case *ast.CallExpr: switch fn := node.Fun.(type) { case *ast.SelectorExpr: switch expr := fn.X.(type) { case *ast.Ident: if expr.Obj != nil && expr.Obj.Kind == ast.Var { t := ctx.Info.TypeOf(expr) if t != nil { return t.String(), fn.Sel.Name, nil } return "undefined", fn.Sel.Name, fmt.Errorf("missing type info") } return expr.Name, fn.Sel.Name, nil } case *ast.Ident: return ctx.Pkg.Name(), fn.Name, nil } } return "", "", fmt.Errorf("unable to determine call info") }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
helpers.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L170-L187
go
train
// GetCallStringArgsValues returns the values of strings arguments if they can be resolved
func GetCallStringArgsValues(n ast.Node, ctx *Context) []string
// GetCallStringArgsValues returns the values of strings arguments if they can be resolved func GetCallStringArgsValues(n ast.Node, ctx *Context) []string
{ values := []string{} switch node := n.(type) { case *ast.CallExpr: for _, arg := range node.Args { switch param := arg.(type) { case *ast.BasicLit: value, err := GetString(param) if err == nil { values = append(values, value) } case *ast.Ident: values = append(values, GetIdentStringValues(param)...) } } } return values }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
helpers.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L190-L213
go
train
// GetIdentStringValues return the string values of an Ident if they can be resolved
func GetIdentStringValues(ident *ast.Ident) []string
// GetIdentStringValues return the string values of an Ident if they can be resolved func GetIdentStringValues(ident *ast.Ident) []string
{ values := []string{} obj := ident.Obj if obj != nil { switch decl := obj.Decl.(type) { case *ast.ValueSpec: for _, v := range decl.Values { value, err := GetString(v) if err == nil { values = append(values, value) } } case *ast.AssignStmt: for _, v := range decl.Rhs { value, err := GetString(v) if err == nil { values = append(values, value) } } } } return values }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
helpers.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L217-L231
go
train
// GetImportedName returns the name used for the package within the // code. It will resolve aliases and ignores initialization only imports.
func GetImportedName(path string, ctx *Context) (string, bool)
// GetImportedName returns the name used for the package within the // code. It will resolve aliases and ignores initialization only imports. func GetImportedName(path string, ctx *Context) (string, bool)
{ importName, imported := ctx.Imports.Imported[path] if !imported { return "", false } if _, initonly := ctx.Imports.InitOnly[path]; initonly { return "", false } if alias, ok := ctx.Imports.Aliased[path]; ok { importName = alias } return importName, true }