github.com/mier85/go-sensor@v1.30.1-0.20220920111756-9bf41b3bc7e0/meter.go (about)

     1  // (c) Copyright IBM Corp. 2021
     2  // (c) Copyright Instana Inc. 2016
     3  
     4  package instana
     5  
     6  import (
     7  	"runtime"
     8  	"time"
     9  
    10  	"github.com/mier85/go-sensor/acceptor"
    11  )
    12  
    13  // SnapshotS struct to hold snapshot data
    14  type SnapshotS acceptor.RuntimeInfo
    15  
    16  // MemoryS struct to hold snapshot data
    17  type MemoryS acceptor.MemoryStats
    18  
    19  // MetricsS struct to hold snapshot data
    20  type MetricsS acceptor.Metrics
    21  
    22  // EntityData struct to hold snapshot data
    23  type EntityData acceptor.GoProcessData
    24  
    25  type meterS struct {
    26  	numGC uint32
    27  	done  chan struct{}
    28  }
    29  
    30  func newMeter(logger LeveledLogger) *meterS {
    31  	logger.Debug("initializing meter")
    32  
    33  	return &meterS{
    34  		done: make(chan struct{}, 1),
    35  	}
    36  }
    37  
    38  func (m *meterS) Run(collectInterval time.Duration) {
    39  	ticker := time.NewTicker(collectInterval)
    40  	defer ticker.Stop()
    41  	for {
    42  		select {
    43  		case <-m.done:
    44  			return
    45  		case <-ticker.C:
    46  			if sensor.Agent().Ready() {
    47  				go sensor.Agent().SendMetrics(m.collectMetrics())
    48  			}
    49  		}
    50  	}
    51  }
    52  
    53  func (m *meterS) Stop() {
    54  	m.done <- struct{}{}
    55  }
    56  
    57  func (m *meterS) collectMemoryMetrics() acceptor.MemoryStats {
    58  	var memStats runtime.MemStats
    59  	runtime.ReadMemStats(&memStats)
    60  	ret := acceptor.MemoryStats{
    61  		Alloc:         memStats.Alloc,
    62  		TotalAlloc:    memStats.TotalAlloc,
    63  		Sys:           memStats.Sys,
    64  		Lookups:       memStats.Lookups,
    65  		Mallocs:       memStats.Mallocs,
    66  		Frees:         memStats.Frees,
    67  		HeapAlloc:     memStats.HeapAlloc,
    68  		HeapSys:       memStats.HeapSys,
    69  		HeapIdle:      memStats.HeapIdle,
    70  		HeapInuse:     memStats.HeapInuse,
    71  		HeapReleased:  memStats.HeapReleased,
    72  		HeapObjects:   memStats.HeapObjects,
    73  		PauseTotalNs:  memStats.PauseTotalNs,
    74  		NumGC:         memStats.NumGC,
    75  		GCCPUFraction: memStats.GCCPUFraction}
    76  
    77  	if m.numGC < memStats.NumGC {
    78  		ret.PauseNs = memStats.PauseNs[(memStats.NumGC+255)%256]
    79  		m.numGC = memStats.NumGC
    80  	}
    81  
    82  	return ret
    83  }
    84  
    85  func (m *meterS) collectMetrics() acceptor.Metrics {
    86  	return acceptor.Metrics{
    87  		CgoCall:     runtime.NumCgoCall(),
    88  		Goroutine:   runtime.NumGoroutine(),
    89  		MemoryStats: m.collectMemoryMetrics(),
    90  	}
    91  }