Skip to content

Commit

Permalink
Add periodic health checks to TChannel (#318)
Browse files Browse the repository at this point in the history
If a TChannel connection stalls (e.g., the remote side has disappeared,
and traffic starts black-holing), TChannel waits for TCP to detect this
issue, but this is often not configurable, and it can be a long period
of time (we've observed many minutes in production).

In many P2P situations, it's desirable to detect these failures as soon
as possible. Support active health checking using TChannel pings on a
periodic basis, with configurable timeouts, number of failures etc.
  • Loading branch information
prashantv committed Sep 29, 2017
1 parent b9dc4c1 commit 1fcf82e
Show file tree
Hide file tree
Showing 8 changed files with 568 additions and 19 deletions.
11 changes: 11 additions & 0 deletions channel.go
Expand Up @@ -84,6 +84,10 @@ type ChannelOptions struct {
// Note: This is not a stable part of the API and may change.
TimeNow func() time.Time

// TimeTicker is a variable for overriding time.Ticker in unit tests.
// Note: This is not a stable part of the API and may change.
TimeTicker func(d time.Duration) *time.Ticker

// Tracer is an OpenTracing Tracer used to manage distributed tracing spans.
// If not set, opentracing.GlobalTracer() is used.
Tracer opentracing.Tracer
Expand Down Expand Up @@ -154,6 +158,7 @@ type channelConnectionCommon struct {
tracer opentracing.Tracer
subChannels *subChannelMap
timeNow func() time.Time
timeTicker func(time.Duration) *time.Ticker
}

// _nextChID is used to allocate unique IDs to every channel for debugging purposes.
Expand Down Expand Up @@ -205,6 +210,11 @@ func NewChannel(serviceName string, opts *ChannelOptions) (*Channel, error) {
timeNow = time.Now
}

timeTicker := opts.TimeTicker
if timeTicker == nil {
timeTicker = time.NewTicker
}

chID := _nextChID.Inc()
ch := &Channel{
channelConnectionCommon: channelConnectionCommon{
Expand All @@ -216,6 +226,7 @@ func NewChannel(serviceName string, opts *ChannelOptions) (*Channel, error) {
statsReporter: statsReporter,
subChannels: &subChannelMap{},
timeNow: timeNow,
timeTicker: timeTicker,
tracer: opts.Tracer,
},
chID: chID,
Expand Down
52 changes: 35 additions & 17 deletions connection.go
Expand Up @@ -136,6 +136,10 @@ type ConnectionOptions struct {

// ToS class name marked on outbound packets.
TosPriority tos.ToS

// HealthChecks configures active connection health checking for this channel.
// By default, health checks are not enabled.
HealthChecks HealthCheckOptions
}

// connectionEvents are the events that can be triggered by a connection.
Expand Down Expand Up @@ -186,6 +190,11 @@ type Connection struct {
// remotePeerAddress is used as a cache for remote peer address parsed into individual
// components that can be used to set peer tags on OpenTracing Span.
remotePeerAddress peerAddressComponents

// healthCheckCtx/Quit are used to stop health checks.
healthCheckCtx context.Context
healthCheckQuit context.CancelFunc
healthCheckHistory *healthHistory
}

type peerAddressComponents struct {
Expand Down Expand Up @@ -237,6 +246,7 @@ func (co ConnectionOptions) withDefaults() ConnectionOptions {
if co.SendBufferSize <= 0 {
co.SendBufferSize = defaultConnectionBufferSize
}
co.HealthChecks = co.HealthChecks.withDefaults()
return co
}

Expand Down Expand Up @@ -282,22 +292,24 @@ func (ch *Channel) newConnection(conn net.Conn, initialID uint32, outboundHP str
c := &Connection{
channelConnectionCommon: ch.channelConnectionCommon,

connID: connID,
conn: conn,
opts: opts,
state: connectionActive,
sendCh: make(chan *Frame, opts.SendBufferSize),
stopCh: make(chan struct{}),
localPeerInfo: peerInfo,
remotePeerInfo: remotePeer,
remotePeerAddress: remotePeerAddress,
outboundHP: outboundHP,
inbound: newMessageExchangeSet(log, messageExchangeSetInbound),
outbound: newMessageExchangeSet(log, messageExchangeSetOutbound),
handler: ch.handler,
events: events,
commonStatsTags: ch.commonStatsTags,
}
connID: connID,
conn: conn,
opts: opts,
state: connectionActive,
sendCh: make(chan *Frame, opts.SendBufferSize),
stopCh: make(chan struct{}),
localPeerInfo: peerInfo,
remotePeerInfo: remotePeer,
remotePeerAddress: remotePeerAddress,
outboundHP: outboundHP,
inbound: newMessageExchangeSet(log, messageExchangeSetInbound),
outbound: newMessageExchangeSet(log, messageExchangeSetOutbound),
handler: ch.handler,
events: events,
commonStatsTags: ch.commonStatsTags,
healthCheckHistory: newHealthHistory(),
}
c.healthCheckCtx, c.healthCheckQuit = context.WithCancel(context.Background())

if tosPriority := opts.TosPriority; tosPriority > 0 {
if err := ch.setConnectionTosPriority(tosPriority, conn); err != nil {
Expand Down Expand Up @@ -347,6 +359,10 @@ func (c *Connection) callOnActive() {
if f := c.events.OnActive; f != nil {
f(c)
}

if c.opts.HealthChecks.enabled() {
go c.healthCheck(c.connID)
}
}

func (c *Connection) callOnCloseStateChange() {
Expand Down Expand Up @@ -530,6 +546,8 @@ func (c *Connection) connectionError(site string, err error) error {
ErrField(err),
}
}

c.stopHealthCheck()
err = c.logConnectionError(site, err)
c.close(closeLogFields...)

Expand Down Expand Up @@ -811,7 +829,7 @@ func (c *Connection) closeNetwork() {
// closed; no need to close the send channel (and closing the send
// channel would be dangerous since other goroutine might be sending)
c.log.Debugf("Closing underlying network connection")
c.closeNetworkCalled.Inc()
c.stopHealthCheck()
if err := c.conn.Close(); err != nil {
c.log.WithFields(
LogField{"remotePeer", c.remotePeerInfo},
Expand Down
168 changes: 168 additions & 0 deletions health.go
@@ -0,0 +1,168 @@
// Copyright (c) 2017 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package tchannel

import (
"sync"
"time"

"golang.org/x/net/context"
)

const (
_defaultHealthCheckTimeout = time.Second
_defaultHealthCheckFailuresToClose = 5

_healthHistorySize = 256
)

// HealthCheckOptions are the parameters to configure active TChannel health
// checks. These are not intended to check application level health, but
// TCP connection health (similar to TCP keep-alives). The health checks use
// TChannel ping messages.
type HealthCheckOptions struct {
// The period between health checks. If this is zeor, active health checks
// are disabled.
Interval time.Duration

// The timeout to use for a health check.
// If no value is specified, it defaults to time.Second.
Timeout time.Duration

// FailuresToClose is the number of consecutive health check failures that
// will cause this connection to be closed.
// If no value is specified, it defaults to 5.
FailuresToClose int
}

type healthHistory struct {
sync.RWMutex

states []bool

insertAt int
total int
}

func newHealthHistory() *healthHistory {
return &healthHistory{
states: make([]bool, _healthHistorySize),
}
}

func (hh *healthHistory) add(b bool) {
hh.Lock()
defer hh.Unlock()

hh.states[hh.insertAt] = b
hh.insertAt = (hh.insertAt + 1) % _healthHistorySize
hh.total++
}

func (hh *healthHistory) asBools() []bool {
hh.RLock()
defer hh.RUnlock()

if hh.total < _healthHistorySize {
return append([]bool(nil), hh.states[:hh.total]...)
}

states := hh.states
copyStates := make([]bool, 0, _healthHistorySize)
copyStates = append(copyStates, states[hh.insertAt:]...)
copyStates = append(copyStates, states[:hh.insertAt]...)
return copyStates
}

func (hco HealthCheckOptions) enabled() bool {
return hco.Interval > 0
}

func (hco HealthCheckOptions) withDefaults() HealthCheckOptions {
if hco.Timeout == 0 {
hco.Timeout = _defaultHealthCheckTimeout
}
if hco.FailuresToClose == 0 {
hco.FailuresToClose = _defaultHealthCheckFailuresToClose
}
return hco
}

// healthCheck will do periodic pings on the connection to check the state of the connection.
// We accept connID on the stack so can more easily debug panics or leaked goroutines.
func (c *Connection) healthCheck(connID uint32) {
opts := c.opts.HealthChecks

ticker := c.timeTicker(opts.Interval)
defer ticker.Stop()

consecutiveFailures := 0
for {
select {
case <-ticker.C:
case <-c.healthCheckCtx.Done():
return
}

ctx, cancel := context.WithTimeout(c.healthCheckCtx, opts.Timeout)
err := c.ping(ctx)
cancel()
c.healthCheckHistory.add(err == nil)
if err == nil {
if c.log.Enabled(LogLevelDebug) {
c.log.Debug("Performed successful active health check.")
}
consecutiveFailures = 0
continue
}

// If the health check failed because the connection closed or health
// checks were stopped, we don't need to log or close the connection.
if GetSystemErrorCode(err) == ErrCodeCancelled || err == ErrInvalidConnectionState {
c.log.WithFields(ErrField(err)).Debug("Health checker stopped.")
return
}

consecutiveFailures++
c.log.WithFields(LogFields{
{"consecutiveFailures", consecutiveFailures},
ErrField(err),
{"failuresToClose", opts.FailuresToClose},
}...).Warn("Failed active health check.")

if consecutiveFailures >= opts.FailuresToClose {
c.close(LogFields{
{"reason", "health check failure"},
ErrField(err),
}...)
return
}
}
}

func (c *Connection) stopHealthCheck() {
// Best effort check to see if health checks were stopped.
if c.healthCheckCtx.Err() != nil {
return
}
c.log.Debug("Stopping health checks.")
c.healthCheckQuit()
}

0 comments on commit 1fcf82e

Please sign in to comment.