counting.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package protocol
  7. import (
  8. "io"
  9. "sync/atomic"
  10. "time"
  11. )
  12. type countingReader struct {
  13. io.Reader
  14. idString string
  15. tot atomic.Int64 // bytes
  16. last atomic.Int64 // unix nanos
  17. }
  18. var (
  19. totalIncoming atomic.Int64
  20. totalOutgoing atomic.Int64
  21. )
  22. func (c *countingReader) Read(bs []byte) (int, error) {
  23. n, err := c.Reader.Read(bs)
  24. c.tot.Add(int64(n))
  25. totalIncoming.Add(int64(n))
  26. c.last.Store(time.Now().UnixNano())
  27. metricDeviceRecvBytes.WithLabelValues(c.idString).Add(float64(n))
  28. return n, err
  29. }
  30. func (c *countingReader) Tot() int64 { return c.tot.Load() }
  31. func (c *countingReader) Last() time.Time {
  32. return time.Unix(0, c.last.Load())
  33. }
  34. type countingWriter struct {
  35. io.Writer
  36. idString string
  37. tot atomic.Int64 // bytes
  38. last atomic.Int64 // unix nanos
  39. }
  40. func (c *countingWriter) Write(bs []byte) (int, error) {
  41. n, err := c.Writer.Write(bs)
  42. c.tot.Add(int64(n))
  43. totalOutgoing.Add(int64(n))
  44. c.last.Store(time.Now().UnixNano())
  45. metricDeviceSentBytes.WithLabelValues(c.idString).Add(float64(n))
  46. return n, err
  47. }
  48. func (c *countingWriter) Tot() int64 { return c.tot.Load() }
  49. func (c *countingWriter) Last() time.Time {
  50. return time.Unix(0, c.last.Load())
  51. }
  52. func TotalInOut() (int64, int64) {
  53. return totalIncoming.Load(), totalOutgoing.Load()
  54. }