github.com/rudderlabs/rudder-go-kit@v0.30.0/mem/mem.go (about)

     1  package mem
     2  
     3  import (
     4  	"fmt"
     5  
     6  	gomem "github.com/shirou/gopsutil/v3/mem"
     7  
     8  	"github.com/rudderlabs/rudder-go-kit/mem/internal/cgroup"
     9  )
    10  
    11  // Stat represents memory statistics (cgroup aware)
    12  type Stat struct {
    13  	// Total memory in bytes
    14  	Total uint64
    15  	// Available memory in bytes
    16  	Available uint64
    17  	// Available memory in percentage
    18  	AvailablePercent float64
    19  	// Used memory in bytes
    20  	Used uint64
    21  	// Used memory in percentage
    22  	UsedPercent float64
    23  }
    24  
    25  // Get current memory statistics
    26  func Get() (*Stat, error) {
    27  	return _default.Get()
    28  }
    29  
    30  var _default *collector
    31  
    32  func init() {
    33  	_default = &collector{}
    34  }
    35  
    36  type collector struct {
    37  	basePath string
    38  }
    39  
    40  // Get current memory statistics
    41  func (c *collector) Get() (*Stat, error) {
    42  	var stat Stat
    43  	mem, err := gomem.VirtualMemory()
    44  	if err != nil {
    45  		return nil, fmt.Errorf("failed to get memory statistics: %w", err)
    46  	}
    47  
    48  	cgroupLimit := cgroup.GetMemoryLimit(c.basePath, int(mem.Total))
    49  	if cgroupLimit < int(mem.Total) { // if cgroup limit is set read memory statistics from cgroup
    50  		stat.Total = uint64(cgroupLimit)
    51  		stat.Used = uint64(cgroup.GetMemoryUsage(c.basePath))
    52  		if stat.Used > stat.Total {
    53  			stat.Used = stat.Total
    54  		}
    55  		stat.Available = stat.Total - stat.Used
    56  	} else {
    57  		stat.Total = mem.Total
    58  		stat.Available = mem.Available
    59  		stat.Used = stat.Total - stat.Available
    60  	}
    61  	stat.AvailablePercent = float64(stat.Available) * 100 / float64(stat.Total)
    62  	stat.UsedPercent = float64(stat.Used) * 100 / float64(stat.Total)
    63  	return &stat, nil
    64  }