github.com/calmw/ethereum@v0.1.1/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 "net" 21 22 "github.com/calmw/ethereum/metrics" 23 ) 24 25 const ( 26 moduleName = "discover" 27 // ingressMeterName is the prefix of the per-packet inbound metrics. 28 ingressMeterName = moduleName + "/ingress" 29 30 // egressMeterName is the prefix of the per-packet outbound metrics. 31 egressMeterName = moduleName + "/egress" 32 ) 33 34 var ( 35 ingressTrafficMeter = metrics.NewRegisteredMeter(ingressMeterName, nil) 36 egressTrafficMeter = metrics.NewRegisteredMeter(egressMeterName, nil) 37 ) 38 39 // meteredConn is a wrapper around a net.UDPConn that meters both the 40 // inbound and outbound network traffic. 41 type meteredUdpConn struct { 42 UDPConn 43 } 44 45 func newMeteredConn(conn UDPConn) UDPConn { 46 // Short circuit if metrics are disabled 47 if !metrics.Enabled { 48 return conn 49 } 50 return &meteredUdpConn{UDPConn: conn} 51 } 52 53 // Read delegates a network read to the underlying connection, bumping the udp ingress traffic meter along the way. 54 func (c *meteredUdpConn) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) { 55 n, addr, err = c.UDPConn.ReadFromUDP(b) 56 ingressTrafficMeter.Mark(int64(n)) 57 return n, addr, err 58 } 59 60 // Write delegates a network write to the underlying connection, bumping the udp egress traffic meter along the way. 61 func (c *meteredUdpConn) WriteToUDP(b []byte, addr *net.UDPAddr) (n int, err error) { 62 n, err = c.UDPConn.WriteToUDP(b, addr) 63 egressTrafficMeter.Mark(int64(n)) 64 return n, err 65 }