2021-04-20 08:28:03 +00:00
|
|
|
package stats
|
|
|
|
|
|
|
|
import (
|
2021-04-23 17:23:44 +00:00
|
|
|
"flag"
|
2021-04-20 08:28:03 +00:00
|
|
|
"fmt"
|
|
|
|
"github.com/dustin/go-humanize"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Stat bundles the metrics we collect into a single struct
|
|
|
|
type Stat struct {
|
|
|
|
SentBytes uint64
|
|
|
|
ReceivedBytes uint64
|
2021-04-26 10:22:11 +00:00
|
|
|
RegisteredPeers uint8
|
|
|
|
AlivePeer uint8
|
2021-04-20 08:28:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// statPipe is a channel used to
|
|
|
|
var stats Stat
|
|
|
|
|
2021-04-23 17:23:44 +00:00
|
|
|
// printStats sets whether we should print stats or not
|
|
|
|
var printStats bool
|
|
|
|
|
|
|
|
// RegisterStatsFlags registers all flags required by the stats module
|
|
|
|
func RegisterStatsFlags() {
|
|
|
|
flag.BoolVar(&printStats, "print-stats", true, "Print traffic statistics every few seconds")
|
|
|
|
}
|
|
|
|
|
2021-04-20 08:28:03 +00:00
|
|
|
// PushStat pushes the given stat
|
2021-04-26 10:22:11 +00:00
|
|
|
// Note that SentBytes, ReceivedBytes and RegisteredPeers are added to the current number,
|
|
|
|
// while AlivePeer is interfaced with SetAlivePeers and is left ignored by PushStat
|
2021-04-20 08:28:03 +00:00
|
|
|
func PushStat(s Stat) {
|
|
|
|
stats.SentBytes += s.SentBytes
|
|
|
|
stats.ReceivedBytes += s.ReceivedBytes
|
2021-04-26 10:22:11 +00:00
|
|
|
stats.RegisteredPeers += s.RegisteredPeers
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetAlivePeers sets the number of alive peers, means peers we could connect to
|
|
|
|
func SetAlivePeers(n uint8) {
|
|
|
|
stats.AlivePeer = n
|
2021-04-20 08:28:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// PrintStats periodically prints the collected statistics
|
|
|
|
func PrintStats() {
|
2021-04-23 17:23:44 +00:00
|
|
|
// Check if we should print stats
|
|
|
|
if !printStats {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-04-20 08:28:03 +00:00
|
|
|
t := time.NewTicker(2 * time.Second)
|
|
|
|
|
|
|
|
for {
|
|
|
|
// Wait until we get a tick
|
|
|
|
<-t.C
|
|
|
|
|
|
|
|
// Format numbers and write them out
|
|
|
|
bIn := humanize.Bytes(stats.ReceivedBytes)
|
|
|
|
bOut := humanize.Bytes(stats.SentBytes)
|
|
|
|
|
2021-04-26 10:22:11 +00:00
|
|
|
fmt.Printf("Traffic: %s in / %s out | Peers: %d seen / %d registered\t\r", bIn, bOut, stats.AlivePeer, stats.RegisteredPeers)
|
2021-04-20 08:28:03 +00:00
|
|
|
}
|
|
|
|
}
|