|
| 1 | +// Package metrics provides general system and process level metrics collection. |
| 2 | +package metrics |
| 3 | + |
| 4 | +import ( |
| 5 | + "runtime" |
| 6 | + "time" |
| 7 | + |
| 8 | + "github.com/ethereum/go-ethereum/logger" |
| 9 | + "github.com/ethereum/go-ethereum/logger/glog" |
| 10 | + "github.com/rcrowley/go-metrics" |
| 11 | +) |
| 12 | + |
| 13 | +// CollectProcessMetrics periodically collects various metrics about the running |
| 14 | +// process. |
| 15 | +func CollectProcessMetrics(refresh time.Duration) { |
| 16 | + // Create the various data collectors |
| 17 | + memstats := make([]*runtime.MemStats, 2) |
| 18 | + diskstats := make([]*DiskStats, 2) |
| 19 | + for i := 0; i < len(memstats); i++ { |
| 20 | + memstats[i] = new(runtime.MemStats) |
| 21 | + diskstats[i] = new(DiskStats) |
| 22 | + } |
| 23 | + // Define the various metrics to collect |
| 24 | + memAllocs := metrics.GetOrRegisterMeter("system/memory/allocs", metrics.DefaultRegistry) |
| 25 | + memFrees := metrics.GetOrRegisterMeter("system/memory/frees", metrics.DefaultRegistry) |
| 26 | + memInuse := metrics.GetOrRegisterMeter("system/memory/inuse", metrics.DefaultRegistry) |
| 27 | + memPauses := metrics.GetOrRegisterMeter("system/memory/pauses", metrics.DefaultRegistry) |
| 28 | + |
| 29 | + var diskReads, diskReadBytes, diskWrites, diskWriteBytes metrics.Meter |
| 30 | + if err := ReadDiskStats(diskstats[0]); err == nil { |
| 31 | + diskReads = metrics.GetOrRegisterMeter("system/disk/readcount", metrics.DefaultRegistry) |
| 32 | + diskReadBytes = metrics.GetOrRegisterMeter("system/disk/readdata", metrics.DefaultRegistry) |
| 33 | + diskWrites = metrics.GetOrRegisterMeter("system/disk/writecount", metrics.DefaultRegistry) |
| 34 | + diskWriteBytes = metrics.GetOrRegisterMeter("system/disk/writedata", metrics.DefaultRegistry) |
| 35 | + } else { |
| 36 | + glog.V(logger.Debug).Infof("failed to read disk metrics: %v", err) |
| 37 | + } |
| 38 | + // Iterate loading the different stats and updating the meters |
| 39 | + for i := 1; ; i++ { |
| 40 | + runtime.ReadMemStats(memstats[i%2]) |
| 41 | + memAllocs.Mark(int64(memstats[i%2].Mallocs - memstats[(i-1)%2].Mallocs)) |
| 42 | + memFrees.Mark(int64(memstats[i%2].Frees - memstats[(i-1)%2].Frees)) |
| 43 | + memInuse.Mark(int64(memstats[i%2].Alloc - memstats[(i-1)%2].Alloc)) |
| 44 | + memPauses.Mark(int64(memstats[i%2].PauseTotalNs - memstats[(i-1)%2].PauseTotalNs)) |
| 45 | + |
| 46 | + if ReadDiskStats(diskstats[i%2]) == nil { |
| 47 | + diskReads.Mark(int64(diskstats[i%2].ReadCount - diskstats[(i-1)%2].ReadCount)) |
| 48 | + diskReadBytes.Mark(int64(diskstats[i%2].ReadBytes - diskstats[(i-1)%2].ReadBytes)) |
| 49 | + diskWrites.Mark(int64(diskstats[i%2].WriteCount - diskstats[(i-1)%2].WriteCount)) |
| 50 | + diskWriteBytes.Mark(int64(diskstats[i%2].WriteBytes - diskstats[(i-1)%2].WriteBytes)) |
| 51 | + } |
| 52 | + time.Sleep(refresh) |
| 53 | + } |
| 54 | +} |
0 commit comments