-
Notifications
You must be signed in to change notification settings - Fork 111
/
systemresource.go
97 lines (77 loc) · 2.19 KB
/
systemresource.go
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
package systemresource
import (
"errors"
"fmt"
"io/fs"
"os"
"runtime"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/disk"
"github.com/shirou/gopsutil/mem"
)
type SystemResourceInfo interface {
GetNumberOfCPU() int
GetCPUSpeed() (float64, error)
GetMemory() (float64, error)
GetDiskSpaceInfo(dirPath string) (disk.UsageStat, error)
GetDiskPartitions(all bool) ([]disk.PartitionStat, error)
FormatBytes(bytes uint64) string
GetFilePermission(dirPath string) (fs.FileMode, error)
}
func NewSystemResourceInfoImpl() *SystemResourceInfoImpl {
return &SystemResourceInfoImpl{}
}
type SystemResourceInfoImpl struct{}
func (s *SystemResourceInfoImpl) GetNumberOfCPU() int {
return runtime.NumCPU()
}
func (s *SystemResourceInfoImpl) GetCPUSpeed() (float64, error) {
info, err := cpu.Info()
if err != nil {
return 0, err
}
if len(info) == 0 {
return 0, fmt.Errorf("no CPU information available")
}
cpuSpeed := info[0].Mhz
return cpuSpeed / 1000, nil
}
func (s *SystemResourceInfoImpl) GetMemory() (float64, error) {
virtualMemory, err := mem.VirtualMemory()
if err != nil {
return 0, err
}
totalRAM := float64(virtualMemory.Total) / (1024 * 1024 * 1024)
return totalRAM, nil
}
func (s *SystemResourceInfoImpl) GetDiskSpaceInfo(dirPath string) (disk.UsageStat, error) {
usage, err := disk.Usage(dirPath)
if err != nil {
return disk.UsageStat{}, err
}
return *usage, nil
}
func (s *SystemResourceInfoImpl) FormatBytes(bytes uint64) string {
suffixes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
index := 0
floatBytes := float64(bytes)
for floatBytes >= 1024 && index < len(suffixes)-1 {
floatBytes /= 1024
index++
}
return fmt.Sprintf("%.1f %s", floatBytes, suffixes[index])
}
func (s *SystemResourceInfoImpl) GetDiskPartitions(all bool) ([]disk.PartitionStat, error) {
partitions, err := disk.Partitions(all)
if err != nil {
return []disk.PartitionStat{}, errors.New("Failed to retrieve disk partitions: " + err.Error())
}
return partitions, nil
}
func (srs *SystemResourceInfoImpl) GetFilePermission(dirPath string) (fs.FileMode, error) {
fileStats, err := os.Stat(dirPath)
if err != nil {
return 0, err
}
return fileStats.Mode().Perm(), nil
}