File: cpu.go

package info (click to toggle)
golang-github-jouyouyun-hardware 0.1.8-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 184 kB
  • sloc: ansic: 43; makefile: 4
file content (108 lines) | stat: -rw-r--r-- 2,006 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package cpu

import (
	"strconv"

	"github.com/jouyouyun/hardware/utils"
)

const (
	cpuKeyName      = "model name"
	cpuKeyCores     = "cpu cores"
	cpuKeyModel     = "cpu model"     // for sw and loonson
	cpuKeyCPUs      = "cpus detected" // for sw
	cpuKeyProcessor = "processor"     // for loonson and arm
	cpuKeyNameARM   = "Processor"     // for arm

	cpuKeyDelim = ":"
	cpuFilename = "/proc/cpuinfo"
)

var (
	_cpu *CPU
)

// CPU store cpu info
type CPU struct {
	Name       string
	Processors int
}

// NewCPU return cpu name and processor number
func NewCPU() (*CPU, error) {
	if _cpu != nil {
		return _cpu, nil
	}

	cpu, err := newCPU(cpuFilename)
	if err == nil {
		_cpu = cpu
		return cpu, nil
	}
	cpu, err = newCPUForSW(cpuFilename)
	if err == nil {
		_cpu = cpu
		return cpu, nil
	}
	cpu, err = newCPUForLoonson(cpuFilename)
	if err == nil {
		_cpu = cpu
		return cpu, nil
	}
	cpu, err = newCPUForARM(cpuFilename)
	if err == nil {
		_cpu = cpu
		return cpu, nil
	}
	return nil, err
}

func newCPU(filename string) (*CPU, error) {
	return doNewCPU(filename, []string{
		cpuKeyName,
		cpuKeyCores,
	}, false, false)
}

func newCPUForSW(filename string) (*CPU, error) {
	return doNewCPU(filename, []string{
		cpuKeyModel,
		cpuKeyCPUs,
	}, false, false)
}

func newCPUForLoonson(filename string) (*CPU, error) {
	return doNewCPU(filename, []string{
		cpuKeyModel,
		cpuKeyProcessor,
	}, true, true)
}

func newCPUForARM(filename string) (*CPU, error) {
	return doNewCPU(filename, []string{
		cpuKeyNameARM,
		cpuKeyProcessor,
	}, true, true)
}

func doNewCPU(filename string, keys []string, fall, numIncr bool) (*CPU, error) {
	var keySet = make(map[string]string)
	for _, key := range keys {
		keySet[key] = ""
	}
	err := utils.ProcGetByKey(filename, cpuKeyDelim, keySet, fall)
	if err != nil {
		return nil, err
	}
	num, err := strconv.Atoi(keySet[keys[1]])
	if err != nil {
		return nil, err
	}
	if numIncr {
		num++
	}
	return &CPU{
		Name:       keySet[keys[0]],
		Processors: num,
	}, nil
}