github.com/kaydxh/golang@v0.0.131/pkg/monitor/opentelemetry/resource/resource.memory.go (about) 1 package resource 2 3 import ( 4 "context" 5 6 net_ "github.com/kaydxh/golang/go/net" 7 resource_ "github.com/kaydxh/golang/pkg/middleware/resource" 8 app_ "github.com/kaydxh/golang/pkg/webserver/app" 9 "github.com/shirou/gopsutil/mem" 10 "go.opentelemetry.io/otel" 11 "go.opentelemetry.io/otel/attribute" 12 "go.opentelemetry.io/otel/metric/instrument/syncfloat64" 13 ) 14 15 const ( 16 MemoryTotalKey = "memory_total" 17 MemoryUsageKey = "memory_usage" 18 MemoryAvaliableKey = "memory_avaliable" 19 ) 20 21 type ResourceStatsMetrics struct { 22 MemoryTotalHistogram syncfloat64.Histogram 23 MemoryUsageHistogram syncfloat64.Histogram 24 MemoryAvaliableHistogram syncfloat64.Histogram 25 } 26 27 func Attrs() []attribute.KeyValue { 28 var attrs []attribute.KeyValue 29 hostIP, err := net_.GetHostIP() 30 if err == nil && hostIP.String() != "" { 31 attrs = append(attrs, resource_.PodIpKey.String(hostIP.String())) 32 } 33 appName := app_.GetVersion().AppName 34 if appName != "" { 35 attrs = append(attrs, resource_.ServerNameKey.String(appName)) 36 } 37 38 return attrs 39 } 40 41 func NewResourceStatsMetrics() (*ResourceStatsMetrics, error) { 42 var err error 43 r := &ResourceStatsMetrics{} 44 call := func(f func()) { 45 if err != nil { 46 return 47 } 48 f() 49 } 50 call(func() { 51 r.MemoryTotalHistogram, err = resource_.GlobalMeter().SyncFloat64().Histogram(MemoryTotalKey) 52 }) 53 call(func() { 54 r.MemoryUsageHistogram, err = resource_.GlobalMeter().SyncFloat64().Histogram(MemoryUsageKey) 55 }) 56 call(func() { 57 r.MemoryAvaliableHistogram, err = resource_.GlobalMeter().SyncFloat64().Histogram(MemoryAvaliableKey) 58 }) 59 if err != nil { 60 otel.Handle(err) 61 } 62 63 return r, nil 64 } 65 66 func (r *ResourceStatsMetrics) ReportMetric(ctx context.Context) (total, avaiable, usage float64) { 67 attrs := Attrs() 68 69 v, err := mem.VirtualMemory() 70 if err != nil { 71 return 0, 0, 0 72 } 73 74 total = float64(v.Total) 75 avaiable = float64(v.Available) 76 usage = v.UsedPercent 77 r.MemoryTotalHistogram.Record(ctx, total, attrs...) 78 r.MemoryAvaliableHistogram.Record(ctx, avaiable, attrs...) 79 r.MemoryUsageHistogram.Record(ctx, usage, attrs...) 80 81 return total, avaiable, usage 82 }