github.com/pyroscope-io/pyroscope@v0.37.3-0.20230725203016-5f6947968bd0/pkg/agent/ebpfspy/cpuonline/cpuonline.go (about)

     1  package cpuonline
     2  
     3  import (
     4  	"io/ioutil"
     5  	"strconv"
     6  	"strings"
     7  )
     8  
     9  const cpuOnline = "/sys/devices/system/cpu/online"
    10  
    11  // Get returns a slice with the online CPUs, for example `[0, 2, 3]`
    12  func Get() ([]uint, error) {
    13  	buf, err := ioutil.ReadFile(cpuOnline)
    14  	if err != nil {
    15  		return nil, err
    16  	}
    17  	return ReadCPURange(string(buf))
    18  }
    19  
    20  // loosely based on https://github.com/iovisor/bcc/blob/v0.3.0/src/python/bcc/utils.py#L15
    21  func ReadCPURange(cpuRangeStr string) ([]uint, error) {
    22  	var cpus []uint
    23  	cpuRangeStr = strings.Trim(cpuRangeStr, "\n ")
    24  	for _, cpuRange := range strings.Split(cpuRangeStr, ",") {
    25  		rangeOp := strings.SplitN(cpuRange, "-", 2)
    26  		first, err := strconv.ParseUint(rangeOp[0], 10, 32)
    27  		if err != nil {
    28  			return nil, err
    29  		}
    30  		if len(rangeOp) == 1 {
    31  			cpus = append(cpus, uint(first))
    32  			continue
    33  		}
    34  		last, err := strconv.ParseUint(rangeOp[1], 10, 32)
    35  		if err != nil {
    36  			return nil, err
    37  		}
    38  		for n := first; n <= last; n++ {
    39  			cpus = append(cpus, uint(n))
    40  		}
    41  	}
    42  	return cpus, nil
    43  }