github.com/amazechain/amc@v0.1.3/internal/p2p/discover/metrics.go (about)

     1  // Copyright 2023 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package discover
    18  
    19  import (
    20  	"github.com/rcrowley/go-metrics"
    21  	"net"
    22  )
    23  
    24  const (
    25  	moduleName = "discover"
    26  	// ingressMeterName is the prefix of the per-packet inbound metrics.
    27  	ingressMeterName = moduleName + "/ingress"
    28  
    29  	// egressMeterName is the prefix of the per-packet outbound metrics.
    30  	egressMeterName = moduleName + "/egress"
    31  )
    32  
    33  var (
    34  	ingressTrafficMeter = metrics.NewRegisteredMeter(ingressMeterName, nil)
    35  	egressTrafficMeter  = metrics.NewRegisteredMeter(egressMeterName, nil)
    36  )
    37  
    38  // meteredConn is a wrapper around a net.UDPConn that meters both the
    39  // inbound and outbound network traffic.
    40  type meteredUdpConn struct {
    41  	UDPConn
    42  }
    43  
    44  func newMeteredConn(conn UDPConn) UDPConn {
    45  	// Short circuit if metrics are disabled
    46  	//if !metrics.Enabled {
    47  	//	return conn
    48  	//}
    49  	return &meteredUdpConn{UDPConn: conn}
    50  }
    51  
    52  // Read delegates a network read to the underlying connection, bumping the udp ingress traffic meter along the way.
    53  func (c *meteredUdpConn) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) {
    54  	n, addr, err = c.UDPConn.ReadFromUDP(b)
    55  	ingressTrafficMeter.Mark(int64(n))
    56  	return n, addr, err
    57  }
    58  
    59  // Write delegates a network write to the underlying connection, bumping the udp egress traffic meter along the way.
    60  func (c *meteredUdpConn) WriteToUDP(b []byte, addr *net.UDPAddr) (n int, err error) {
    61  	n, err = c.UDPConn.WriteToUDP(b, addr)
    62  	egressTrafficMeter.Mark(int64(n))
    63  	return n, err
    64  }