github.com/pyroscope-io/pyroscope@v0.37.3-0.20230725203016-5f6947968bd0/pkg/storage/mem_linux.go (about)

     1  //go:build linux
     2  // +build linux
     3  
     4  package storage
     5  
     6  import (
     7  	"io"
     8  	"os"
     9  	"strconv"
    10  	"strings"
    11  
    12  	"github.com/pyroscope-io/pyroscope/pkg/util/file"
    13  	"github.com/shirou/gopsutil/mem"
    14  	"github.com/sirupsen/logrus"
    15  )
    16  
    17  const memLimitPath = "/sys/fs/cgroup/memory/memory.limit_in_bytes"
    18  
    19  func getCgroupMemLimit() (uint64, error) {
    20  	f, err := os.Open(memLimitPath)
    21  	if err != nil {
    22  		return 0, err
    23  	}
    24  	b, err := io.ReadAll(f)
    25  	if err != nil {
    26  		return 0, err
    27  	}
    28  	r, err := strconv.Atoi(strings.TrimSuffix(string(b), "\n"))
    29  	if err != nil {
    30  		return 0, err
    31  	}
    32  
    33  	return uint64(r), nil
    34  }
    35  
    36  func getMemTotal() (uint64, error) {
    37  	vm, err := mem.VirtualMemory()
    38  	if err != nil {
    39  		return 0, err
    40  	}
    41  
    42  	if file.Exists(memLimitPath) {
    43  		v, err := getCgroupMemLimit()
    44  		if err == nil {
    45  			if v < vm.Total {
    46  				return v, nil
    47  			}
    48  			return vm.Total, nil
    49  		}
    50  
    51  		logrus.WithError(err).Warn("Could not read cgroup memory limit")
    52  		return vm.Total, nil
    53  	}
    54  
    55  	return vm.Total, nil
    56  }