From 9dbd4898b2ac91fa4a261cf75c9b55f2cf2f8e5d Mon Sep 17 00:00:00 2001 From: Shirou WAKAYAMA Date: Mon, 22 Sep 2014 16:35:47 +0900 Subject: [PATCH] add SerialNumber to DiskIOCounterStat. --- disk.go | 17 +++++++++-------- disk_linux.go | 23 +++++++++++++++++++++++ disk_test.go | 13 +++++++------ 3 files changed, 39 insertions(+), 14 deletions(-) diff --git a/disk.go b/disk.go index a76771e..d94caf7 100644 --- a/disk.go +++ b/disk.go @@ -24,14 +24,15 @@ type DiskPartitionStat struct { } type DiskIOCountersStat struct { - ReadCount uint64 `json:"readCount"` - WriteCount uint64 `json:"writeCount"` - ReadBytes uint64 `json:"readBytes"` - WriteBytes uint64 `json:"writeBytes"` - ReadTime uint64 `json:"readTime"` - WriteTime uint64 `json:"writeTime"` - Name string `json:"name"` - IoTime uint64 `json:"ioTime"` + ReadCount uint64 `json:"readCount"` + WriteCount uint64 `json:"writeCount"` + ReadBytes uint64 `json:"readBytes"` + WriteBytes uint64 `json:"writeBytes"` + ReadTime uint64 `json:"readTime"` + WriteTime uint64 `json:"writeTime"` + Name string `json:"name"` + IoTime uint64 `json:"ioTime"` + SerialNumber string `json:"serialNumber"` } func (d DiskUsageStat) String() string { diff --git a/disk_linux.go b/disk_linux.go index bfcc9f1..25a5ad1 100644 --- a/disk_linux.go +++ b/disk_linux.go @@ -3,6 +3,8 @@ package gopsutil import ( + "fmt" + "os/exec" "strconv" "strings" ) @@ -91,7 +93,28 @@ func DiskIOCounters() (map[string]DiskIOCountersStat, error) { } d.Name = name + d.SerialNumber = GetDiskSerialNumber(name) ret[name] = d } return ret, nil } + +func GetDiskSerialNumber(name string) (string, error) { + n := fmt.Sprintf("--name=%s", name) + out, err := exec.Command("/sbin/udevadm", "info", "--query=property", n).Output() + + // does not return error, just an empty string + if err != nil { + return "", nil + } + lines := strings.Split(string(out), "\n") + for _, line := range lines { + values := strings.Split(line, "=") + if len(values) < 2 || values[0] != "ID_SERIAL" { + // only get ID_SERIAL, not ID_SERIAL_SHORT + continue + } + return values[1], nil + } + return "", nil +} diff --git a/disk_test.go b/disk_test.go index 2ced8b7..0f20030 100644 --- a/disk_test.go +++ b/disk_test.go @@ -79,13 +79,14 @@ func TestDiskPartitionStat_String(t *testing.T) { func TestDiskIOCountersStat_String(t *testing.T) { v := DiskIOCountersStat{ - Name: "sd01", - ReadCount: 100, - WriteCount: 200, - ReadBytes: 300, - WriteBytes: 400, + Name: "sd01", + ReadCount: 100, + WriteCount: 200, + ReadBytes: 300, + WriteBytes: 400, + SerialNumber: "SERIAL", } - e := `{"readCount":100,"writeCount":200,"readBytes":300,"writeBytes":400,"readTime":0,"writeTime":0,"name":"sd01","ioTime":0}` + e := `{"readCount":100,"writeCount":200,"readBytes":300,"writeBytes":400,"readTime":0,"writeTime":0,"name":"sd01","ioTime":0,"serialNumber":"SERIAL"}` if e != fmt.Sprintf("%v", v) { t.Errorf("DiskUsageStat string is invalid: %v", v) }