Skip to content

Commit

Permalink
fix(cpu): fixed number of cpus available info (#5321)
Browse files Browse the repository at this point in the history
* fix get cpu

Signed-off-by: joaorufi <[email protected]>

* change variable name

Signed-off-by: joaorufi <[email protected]>

* removed magic number

Signed-off-by: joaorufi <[email protected]>

* change function name

Signed-off-by: joaorufi <[email protected]>

* ...

Signed-off-by: joaorufi <[email protected]>

* check error

Signed-off-by: joaorufi <[email protected]>

* requested changes

Signed-off-by: joaorufi <[email protected]>
  • Loading branch information
joaorufi authored May 11, 2022
1 parent 172ee5a commit 0377df7
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
41 changes: 41 additions & 0 deletions internal/console/helpers/helpers.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
package helpers

import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"

"github.com/BurntSushi/toml"
Expand All @@ -20,6 +23,8 @@ import (
"gopkg.in/yaml.v3"
)

const divisor = float32(100000)

var reportGenerators = map[string]func(path, filename string, body interface{}) error{
"json": report.PrintJSONReport,
"sarif": report.PrintSarifReport,
Expand Down Expand Up @@ -157,3 +162,39 @@ func ListReportFormats() []string {
sort.Strings(supportedFormats)
return supportedFormats
}

// GetNumCPU return the number of cpus available
func GetNumCPU() (float32, error) {
// Check if application is running inside docker
if _, err := os.Stat("/.dockerenv"); err == nil {
f, err := os.Open("/sys/fs/cgroup/cpu/cpu.cfs_quota_us")
if err != nil {
return -1, err
}

defer func() {
if err := f.Close(); err != nil {
log.Err(err).Msg("failed to close '/sys/fs/cgroup/cpu/cpu.cfs_quota_us'")
}
}()

scanner := bufio.NewScanner(f)
if scanner.Scan() {
text := scanner.Text()
cpus, err := strconv.Atoi(text)
if err != nil {
return float32(cpus) / divisor, err
}

if cpus != -1 {
return float32(cpus) / divisor, nil
}

return float32(runtime.NumCPU()), nil
}

return float32(runtime.NumCPU()), nil
}

return float32(runtime.NumCPU()), nil
}
8 changes: 6 additions & 2 deletions internal/console/pre_scan.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,12 @@ func (console *console) preScan() {
log.Info().Msgf("Total memory: %s", bytefmt.ByteSize(mem.Total))
}

cpu := runtime.NumCPU()
log.Info().Msgf("CPU: %d", cpu)
cpu, err := consoleHelpers.GetNumCPU()
if err != nil {
log.Err(err).Msg("failed to get CPU")
} else {
log.Info().Msgf("CPU: %.1f", cpu)
}

noProgress := flags.GetBoolFlag(flags.NoProgressFlag)
if strings.EqualFold(flags.GetStrFlag(flags.LogLevelFlag), "debug") {
Expand Down

0 comments on commit 0377df7

Please sign in to comment.