metrics.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2015 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. // Contains the meters and timers used by the networking layer.
  17. package p2p
  18. import (
  19. "net"
  20. "github.com/ethereum/go-ethereum/metrics"
  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. // meteredConn is a wrapper around a network TCP connection that meters both the
  29. // inbound and outbound network traffic.
  30. type meteredConn struct {
  31. *net.TCPConn // Network connection to wrap with metering
  32. }
  33. // newMeteredConn creates a new metered connection, also bumping the ingress or
  34. // egress connection meter. If the metrics system is disabled, this function
  35. // returns the original object.
  36. func newMeteredConn(conn net.Conn, ingress bool) net.Conn {
  37. // Short circuit if metrics are disabled
  38. if !metrics.Enabled {
  39. return conn
  40. }
  41. // Otherwise bump the connection counters and wrap the connection
  42. if ingress {
  43. ingressConnectMeter.Mark(1)
  44. } else {
  45. egressConnectMeter.Mark(1)
  46. }
  47. return &meteredConn{conn.(*net.TCPConn)}
  48. }
  49. // Read delegates a network read to the underlying connection, bumping the ingress
  50. // traffic meter along the way.
  51. func (c *meteredConn) Read(b []byte) (n int, err error) {
  52. n, err = c.TCPConn.Read(b)
  53. ingressTrafficMeter.Mark(int64(n))
  54. return
  55. }
  56. // Write delegates a network write to the underlying connection, bumping the
  57. // egress traffic meter along the way.
  58. func (c *meteredConn) Write(b []byte) (n int, err error) {
  59. n, err = c.TCPConn.Write(b)
  60. egressTrafficMeter.Mark(int64(n))
  61. return
  62. }