Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement disk.GetDiskSerialNumber for Windows via WMI #541

Merged
merged 3 commits into from
Jun 23, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion disk/disk_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ type Win32_PerfFormattedData struct {
AvgDisksecPerRead uint64
AvgDisksecPerWrite uint64
}
type win32_DiskDrive struct {
DeviceID string
SerialNumber string
}
type win32_DiskPartition struct {
DeviceID string
}

const WaitMSec = 500

Expand Down Expand Up @@ -157,7 +164,7 @@ func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOC
continue
}

ret[d.Name] = IOCountersStat{
tmpIO := IOCountersStat{
Name: d.Name,
ReadCount: uint64(d.AvgDiskReadQueueLength),
WriteCount: d.AvgDiskWriteQueueLength,
Expand All @@ -166,6 +173,27 @@ func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOC
ReadTime: d.AvgDisksecPerRead,
WriteTime: d.AvgDisksecPerWrite,
}
tmpIO.SerialNumber = GetDiskSerialNumber(d.Name)
ret[d.Name] = tmpIO
}
return ret, nil
}

// return disk serial number(not volume serial number) of given device or empty string on error. Name of device is drive letter, eg. C:
func GetDiskSerialNumber(name string) string {
return GetDiskSerialNumberWithContext(context.Background(), name)
}

func GetDiskSerialNumberWithContext(ctx context.Context, name string) string {
var diskPart []win32_DiskPartition
var diskDrive []win32_DiskDrive
err := common.WMIQueryWithContext(ctx, "Associators of {Win32_LogicalDisk.DeviceID='"+name+"'} where AssocClass=Win32_LogicalDiskToPartition", &diskPart)
if err != nil || len(diskPart) <= 0 {
return ""
}
err = common.WMIQueryWithContext(ctx, "Associators of {Win32_DiskPartition.DeviceID='"+diskPart[0].DeviceID+"'} where AssocClass=Win32_DiskDriveToDiskPartition", &diskDrive)
if err != nil || len(diskDrive) <= 0 {
return ""
}
return diskDrive[0].SerialNumber
}