github.com/neatlab/neatio@v1.7.3-0.20220425043230-d903e92fcc75/utilities/metrics/metrics.go (about)

     1  package metrics
     2  
     3  import (
     4  	"os"
     5  	"runtime"
     6  	"strings"
     7  	"time"
     8  
     9  	"github.com/neatlab/neatio/chain/log"
    10  )
    11  
    12  var Enabled bool = false
    13  
    14  const MetricsEnabledFlag = "metrics"
    15  
    16  func init() {
    17  	for _, arg := range os.Args {
    18  		if flag := strings.TrimLeft(arg, "-"); flag == MetricsEnabledFlag {
    19  			log.Info("Enabling metrics collection")
    20  			Enabled = true
    21  		}
    22  	}
    23  }
    24  
    25  func CollectProcessMetrics(refresh time.Duration) {
    26  
    27  	if !Enabled {
    28  		return
    29  	}
    30  
    31  	memstats := make([]*runtime.MemStats, 2)
    32  	diskstats := make([]*DiskStats, 2)
    33  	for i := 0; i < len(memstats); i++ {
    34  		memstats[i] = new(runtime.MemStats)
    35  		diskstats[i] = new(DiskStats)
    36  	}
    37  
    38  	memAllocs := GetOrRegisterMeter("system/memory/allocs", DefaultRegistry)
    39  	memFrees := GetOrRegisterMeter("system/memory/frees", DefaultRegistry)
    40  	memInuse := GetOrRegisterMeter("system/memory/inuse", DefaultRegistry)
    41  	memPauses := GetOrRegisterMeter("system/memory/pauses", DefaultRegistry)
    42  
    43  	var diskReads, diskReadBytes, diskWrites, diskWriteBytes Meter
    44  	if err := ReadDiskStats(diskstats[0]); err == nil {
    45  		diskReads = GetOrRegisterMeter("system/disk/readcount", DefaultRegistry)
    46  		diskReadBytes = GetOrRegisterMeter("system/disk/readdata", DefaultRegistry)
    47  		diskWrites = GetOrRegisterMeter("system/disk/writecount", DefaultRegistry)
    48  		diskWriteBytes = GetOrRegisterMeter("system/disk/writedata", DefaultRegistry)
    49  	} else {
    50  		log.Debug("Failed to read disk metrics", "err", err)
    51  	}
    52  
    53  	for i := 1; ; i++ {
    54  		runtime.ReadMemStats(memstats[i%2])
    55  		memAllocs.Mark(int64(memstats[i%2].Mallocs - memstats[(i-1)%2].Mallocs))
    56  		memFrees.Mark(int64(memstats[i%2].Frees - memstats[(i-1)%2].Frees))
    57  		memInuse.Mark(int64(memstats[i%2].Alloc - memstats[(i-1)%2].Alloc))
    58  		memPauses.Mark(int64(memstats[i%2].PauseTotalNs - memstats[(i-1)%2].PauseTotalNs))
    59  
    60  		if ReadDiskStats(diskstats[i%2]) == nil {
    61  			diskReads.Mark(diskstats[i%2].ReadCount - diskstats[(i-1)%2].ReadCount)
    62  			diskReadBytes.Mark(diskstats[i%2].ReadBytes - diskstats[(i-1)%2].ReadBytes)
    63  			diskWrites.Mark(diskstats[i%2].WriteCount - diskstats[(i-1)%2].WriteCount)
    64  			diskWriteBytes.Mark(diskstats[i%2].WriteBytes - diskstats[(i-1)%2].WriteBytes)
    65  		}
    66  		time.Sleep(refresh)
    67  	}
    68  }