github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/p2p/metrics.go (about)

     1  // This file is part of the go-sberex library. The go-sberex library is 
     2  // free software: you can redistribute it and/or modify it under the terms 
     3  // of the GNU Lesser General Public License as published by the Free 
     4  // Software Foundation, either version 3 of the License, or (at your option)
     5  // any later version.
     6  //
     7  // The go-sberex library is distributed in the hope that it will be useful, 
     8  // but WITHOUT ANY WARRANTY; without even the implied warranty of
     9  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 
    10  // General Public License <http://www.gnu.org/licenses/> for more details.
    11  
    12  // Contains the meters and timers used by the networking layer.
    13  
    14  package p2p
    15  
    16  import (
    17  	"net"
    18  
    19  	"github.com/Sberex/go-sberex/metrics"
    20  )
    21  
    22  var (
    23  	ingressConnectMeter = metrics.NewRegisteredMeter("p2p/InboundConnects", nil)
    24  	ingressTrafficMeter = metrics.NewRegisteredMeter("p2p/InboundTraffic", nil)
    25  	egressConnectMeter  = metrics.NewRegisteredMeter("p2p/OutboundConnects", nil)
    26  	egressTrafficMeter  = metrics.NewRegisteredMeter("p2p/OutboundTraffic", nil)
    27  )
    28  
    29  // meteredConn is a wrapper around a network TCP connection that meters both the
    30  // inbound and outbound network traffic.
    31  type meteredConn struct {
    32  	*net.TCPConn // Network connection to wrap with metering
    33  }
    34  
    35  // newMeteredConn creates a new metered connection, also bumping the ingress or
    36  // egress connection meter. If the metrics system is disabled, this function
    37  // returns the original object.
    38  func newMeteredConn(conn net.Conn, ingress bool) net.Conn {
    39  	// Short circuit if metrics are disabled
    40  	if !metrics.Enabled {
    41  		return conn
    42  	}
    43  	// Otherwise bump the connection counters and wrap the connection
    44  	if ingress {
    45  		ingressConnectMeter.Mark(1)
    46  	} else {
    47  		egressConnectMeter.Mark(1)
    48  	}
    49  	return &meteredConn{conn.(*net.TCPConn)}
    50  }
    51  
    52  // Read delegates a network read to the underlying connection, bumping the ingress
    53  // traffic meter along the way.
    54  func (c *meteredConn) Read(b []byte) (n int, err error) {
    55  	n, err = c.TCPConn.Read(b)
    56  	ingressTrafficMeter.Mark(int64(n))
    57  	return
    58  }
    59  
    60  // Write delegates a network write to the underlying connection, bumping the
    61  // egress traffic meter along the way.
    62  func (c *meteredConn) Write(b []byte) (n int, err error) {
    63  	n, err = c.TCPConn.Write(b)
    64  	egressTrafficMeter.Mark(int64(n))
    65  	return
    66  }