github.com/neatlab/neatio@v1.7.3-0.20220425043230-d903e92fcc75/network/p2p/metrics.go (about)

     1  package p2p
     2  
     3  import (
     4  	"net"
     5  
     6  	"github.com/neatlab/neatio/utilities/metrics"
     7  )
     8  
     9  var (
    10  	ingressConnectMeter = metrics.NewRegisteredMeter("p2p/InboundConnects", nil)
    11  	ingressTrafficMeter = metrics.NewRegisteredMeter("p2p/InboundTraffic", nil)
    12  	egressConnectMeter  = metrics.NewRegisteredMeter("p2p/OutboundConnects", nil)
    13  	egressTrafficMeter  = metrics.NewRegisteredMeter("p2p/OutboundTraffic", nil)
    14  )
    15  
    16  type meteredConn struct {
    17  	*net.TCPConn
    18  }
    19  
    20  func newMeteredConn(conn net.Conn, ingress bool) net.Conn {
    21  
    22  	if !metrics.Enabled {
    23  		return conn
    24  	}
    25  
    26  	if ingress {
    27  		ingressConnectMeter.Mark(1)
    28  	} else {
    29  		egressConnectMeter.Mark(1)
    30  	}
    31  	return &meteredConn{conn.(*net.TCPConn)}
    32  }
    33  
    34  func (c *meteredConn) Read(b []byte) (n int, err error) {
    35  	n, err = c.TCPConn.Read(b)
    36  	ingressTrafficMeter.Mark(int64(n))
    37  	return
    38  }
    39  
    40  func (c *meteredConn) Write(b []byte) (n int, err error) {
    41  	n, err = c.TCPConn.Write(b)
    42  	egressTrafficMeter.Mark(int64(n))
    43  	return
    44  }