github.com/keltia/go-ipfs@v0.3.8-0.20150909044612-210793031c63/metrics/bw_stats.go (about) 1 package metrics 2 3 import ( 4 gm "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/whyrusleeping/go-metrics" 5 "sync" 6 7 peer "github.com/ipfs/go-ipfs/p2p/peer" 8 protocol "github.com/ipfs/go-ipfs/p2p/protocol" 9 ) 10 11 type Stats struct { 12 TotalIn int64 13 TotalOut int64 14 RateIn float64 15 RateOut float64 16 } 17 18 type BandwidthCounter struct { 19 lock sync.Mutex 20 totalIn gm.Meter 21 totalOut gm.Meter 22 reg gm.Registry 23 } 24 25 func NewBandwidthCounter() *BandwidthCounter { 26 reg := gm.NewRegistry() 27 return &BandwidthCounter{ 28 totalIn: gm.GetOrRegisterMeter("totalIn", reg), 29 totalOut: gm.GetOrRegisterMeter("totalOut", reg), 30 reg: reg, 31 } 32 } 33 34 func (bwc *BandwidthCounter) LogSentMessage(size int64) { 35 bwc.totalOut.Mark(size) 36 } 37 38 func (bwc *BandwidthCounter) LogRecvMessage(size int64) { 39 bwc.totalIn.Mark(size) 40 } 41 42 func (bwc *BandwidthCounter) LogSentMessageStream(size int64, proto protocol.ID, p peer.ID) { 43 meter := gm.GetOrRegisterMeter("/peer/out/"+string(p), bwc.reg) 44 meter.Mark(size) 45 46 pmeter := gm.GetOrRegisterMeter("/proto/out/"+string(proto), bwc.reg) 47 pmeter.Mark(size) 48 } 49 50 func (bwc *BandwidthCounter) LogRecvMessageStream(size int64, proto protocol.ID, p peer.ID) { 51 meter := gm.GetOrRegisterMeter("/peer/in/"+string(p), bwc.reg) 52 meter.Mark(size) 53 54 pmeter := gm.GetOrRegisterMeter("/proto/in/"+string(proto), bwc.reg) 55 pmeter.Mark(size) 56 } 57 58 func (bwc *BandwidthCounter) GetBandwidthForPeer(p peer.ID) (out Stats) { 59 inMeter := gm.GetOrRegisterMeter("/peer/in/"+string(p), bwc.reg).Snapshot() 60 outMeter := gm.GetOrRegisterMeter("/peer/out/"+string(p), bwc.reg).Snapshot() 61 62 return Stats{ 63 TotalIn: inMeter.Count(), 64 TotalOut: outMeter.Count(), 65 RateIn: inMeter.RateFine(), 66 RateOut: outMeter.RateFine(), 67 } 68 } 69 70 func (bwc *BandwidthCounter) GetBandwidthForProtocol(proto protocol.ID) (out Stats) { 71 inMeter := gm.GetOrRegisterMeter(string("/proto/in/"+proto), bwc.reg).Snapshot() 72 outMeter := gm.GetOrRegisterMeter(string("/proto/out/"+proto), bwc.reg).Snapshot() 73 74 return Stats{ 75 TotalIn: inMeter.Count(), 76 TotalOut: outMeter.Count(), 77 RateIn: inMeter.RateFine(), 78 RateOut: outMeter.RateFine(), 79 } 80 } 81 82 func (bwc *BandwidthCounter) GetBandwidthTotals() (out Stats) { 83 return Stats{ 84 TotalIn: bwc.totalIn.Count(), 85 TotalOut: bwc.totalOut.Count(), 86 RateIn: bwc.totalIn.RateFine(), 87 RateOut: bwc.totalOut.RateFine(), 88 } 89 }