From 4694ce0e4d1a3e14c4fd5c1df1721ef8660e3275 Mon Sep 17 00:00:00 2001 From: WAKAYAMA Shirou Date: Sun, 15 Feb 2015 21:25:33 +0900 Subject: [PATCH] cpu: use wmic to get CPUInfo on Windows --- common/common_windows.go | 18 ++++++++++++++++++ cpu/cpu_test.go | 3 +++ cpu/cpu_windows.go | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+) diff --git a/common/common_windows.go b/common/common_windows.go index 8c5625e..df79d27 100644 --- a/common/common_windows.go +++ b/common/common_windows.go @@ -3,6 +3,9 @@ package common import ( + "fmt" + "os/exec" + "strings" "syscall" "unsafe" ) @@ -29,3 +32,18 @@ func BytePtrToString(p *uint8) string { } return string(a[:i]) } + +// exec wmic and return lines splited by newline +func GetWmic(target string, query string) ([]string, error) { + ret, err := exec.Command("wmic", target, "get", query, "/format:csv").Output() + if err != nil { + return []string{}, err + } + lines := strings.Split(string(ret), "\r\r\n") + if len(lines) <= 2 { + return []string{}, fmt.Errorf("wmic result malformed: [%q]", lines) + } + + // skip first two line + return lines[2:], nil +} diff --git a/cpu/cpu_test.go b/cpu/cpu_test.go index 1768af5..490b129 100644 --- a/cpu/cpu_test.go +++ b/cpu/cpu_test.go @@ -51,6 +51,9 @@ func TestCpuInfo(t *testing.T) { if err != nil { t.Errorf("error %v", err) } + if len(v) == 0 { + t.Errorf("could not get CPU Info") + } for _, vv := range v { if vv.ModelName == "" { t.Errorf("could not get CPU Info: %v", vv) diff --git a/cpu/cpu_windows.go b/cpu/cpu_windows.go index b2fa3a0..41f0054 100644 --- a/cpu/cpu_windows.go +++ b/cpu/cpu_windows.go @@ -3,6 +3,8 @@ package cpu import ( + "strconv" + "strings" "syscall" "unsafe" @@ -41,5 +43,39 @@ func CPUTimes(percpu bool) ([]CPUTimesStat, error) { func CPUInfo() ([]CPUInfoStat, error) { var ret []CPUInfoStat + lines, err := common.GetWmic("cpu", "Family,L2CacheSize,Manufacturer,Name,NumberOfLogicalProcessors,ProcessorId,Stepping") + if err != nil { + return ret, err + } + for i, l := range lines { + t := strings.Split(l, ",") + if len(t) < 2 { + continue + } + cache, err := strconv.Atoi(t[2]) + if err != nil { + cache = 0 + } + cores, err := strconv.Atoi(t[5]) + if err != nil { + cores = 0 + } + stepping, err := strconv.Atoi(t[7]) + if err != nil { + stepping = 0 + } + cpu := CPUInfoStat{ + CPU: int32(i), + Family: t[1], + CacheSize: int32(cache), + VendorID: t[3], + ModelName: t[4], + Cores: int32(cores), + PhysicalID: t[6], + Stepping: int32(stepping), + Flags: []string{}, + } + ret = append(ret, cpu) + } return ret, nil }