diff --git a/blockdevice/stats.go b/blockdevice/stats.go index 22533002..087137a0 100644 --- a/blockdevice/stats.go +++ b/blockdevice/stats.go @@ -209,6 +209,8 @@ const ( sysBlockQueue = "queue" sysBlockDM = "dm" sysUnderlyingDev = "slaves" + sysBlockSize = "size" + sectorSize = 512 ) // FS represents the pseudo-filesystems proc and sys, which provides an @@ -474,3 +476,13 @@ func (fs FS) SysBlockDeviceUnderlyingDevices(device string) (UnderlyingDeviceInf return UnderlyingDeviceInfo{DeviceNames: underlying}, nil } + +// SysBlockDeviceSizeBytes returns the size of the block device from /sys/block//size +// in bytes by multiplying the value by the Linux sector length of 512. +func (fs FS) SysBlockDeviceSizeBytes(device string) (uint64, error) { + size, err := util.ReadUintFromFile(fs.sys.Path(sysBlockPath, device, sysBlockSize)) + if err != nil { + return 0, err + } + return sectorSize * size, nil +} diff --git a/blockdevice/stats_test.go b/blockdevice/stats_test.go index c065c294..1d04d208 100644 --- a/blockdevice/stats_test.go +++ b/blockdevice/stats_test.go @@ -219,3 +219,22 @@ func TestSysBlockDeviceUnderlyingDevices(t *testing.T) { t.Errorf("Incorrect BlockQueueStat, expected: \n%+v, got: \n%+v", underlying0Expected, underlying0) } } + +func TestSysBlockDeviceSize(t *testing.T) { + blockdevice, err := NewFS("testdata/fixtures/proc", "testdata/fixtures/sys") + if err != nil { + t.Fatalf("failed to access blockdevice fs: %v", err) + } + devices, err := blockdevice.SysBlockDevices() + if err != nil { + t.Fatal(err) + } + sizeBytes7, err := blockdevice.SysBlockDeviceSizeBytes(devices[7]) + if err != nil { + t.Fatal(err) + } + sizeBytes7Expected := uint64(3750748848) + if sizeBytes7 != sizeBytes7Expected { + t.Errorf("Incorrect BlockDeviceSize, expected: \n%+v, got: \n%+v", sizeBytes7Expected, sizeBytes7) + } +} diff --git a/testdata/fixtures.ttar b/testdata/fixtures.ttar index 4bc508b8..350a4aa2 100644 --- a/testdata/fixtures.ttar +++ b/testdata/fixtures.ttar @@ -4335,6 +4335,11 @@ Lines: 1 none Mode: 444 # ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/sys/block/sda/size +Lines: 1 +3750748848EOF +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Path: fixtures/sys/block/sda/stat Lines: 1 9652963 396792 759304206 412943 8422549 6731723 286915323 13947418 0 5658367 19174573 1 2 3 12 diff --git a/testdata/fixtures/sys/block/sda/size b/testdata/fixtures/sys/block/sda/size new file mode 100644 index 00000000..117c151b --- /dev/null +++ b/testdata/fixtures/sys/block/sda/size @@ -0,0 +1 @@ +3750748848 \ No newline at end of file