github.com/prysmaticlabs/prysm@v1.4.4/beacon-chain/sync/deadlines.go (about)

     1  package sync
     2  
     3  import (
     4  	"strings"
     5  	"time"
     6  
     7  	"github.com/libp2p/go-libp2p-core/network"
     8  	"github.com/prysmaticlabs/prysm/shared/params"
     9  	"github.com/sirupsen/logrus"
    10  )
    11  
    12  var defaultReadDuration = ttfbTimeout
    13  var defaultWriteDuration = params.BeaconNetworkConfig().RespTimeout // RESP_TIMEOUT
    14  
    15  // SetRPCStreamDeadlines sets read and write deadlines for libp2p-based connection streams.
    16  func SetRPCStreamDeadlines(stream network.Stream) {
    17  	SetStreamReadDeadline(stream, defaultReadDuration)
    18  	SetStreamWriteDeadline(stream, defaultWriteDuration)
    19  }
    20  
    21  // SetStreamReadDeadline for reading from libp2p connection streams, deciding when to close
    22  // a connection based on a particular duration.
    23  //
    24  // NOTE: libp2p uses the system clock time for determining the deadline so we use
    25  // time.Now() instead of the synchronized roughtime.Now(). If the system
    26  // time is corrupted (i.e. time does not advance), the node will experience
    27  // issues being able to properly close streams, leading to unexpected failures and possible
    28  // memory leaks.
    29  func SetStreamReadDeadline(stream network.Stream, duration time.Duration) {
    30  	if err := stream.SetReadDeadline(time.Now().Add(duration)); err != nil &&
    31  		!strings.Contains(err.Error(), "stream closed") {
    32  		log.WithError(err).WithFields(logrus.Fields{
    33  			"peer":      stream.Conn().RemotePeer(),
    34  			"protocol":  stream.Protocol(),
    35  			"direction": stream.Stat().Direction,
    36  		}).Debug("Could not set stream deadline")
    37  	}
    38  }
    39  
    40  // SetStreamWriteDeadline for writing to libp2p connection streams, deciding when to close
    41  // a connection based on a particular duration.
    42  //
    43  // NOTE: libp2p uses the system clock time for determining the deadline so we use
    44  // time.Now() instead of the synchronized roughtime.Now(). If the system
    45  // time is corrupted (i.e. time does not advance), the node will experience
    46  // issues being able to properly close streams, leading to unexpected failures and possible
    47  // memory leaks.
    48  func SetStreamWriteDeadline(stream network.Stream, duration time.Duration) {
    49  	if err := stream.SetWriteDeadline(time.Now().Add(duration)); err != nil {
    50  		log.WithError(err).WithFields(logrus.Fields{
    51  			"peer":      stream.Conn().RemotePeer(),
    52  			"protocol":  stream.Protocol(),
    53  			"direction": stream.Stat().Direction,
    54  		}).Debug("Could not set stream deadline")
    55  	}
    56  }