From fcff38977d575437a5943452abc49f09703bd711 Mon Sep 17 00:00:00 2001
From: Iustin Pop <iustin@google.com>
Date: Sun, 26 Jul 2009 17:09:26 +0200
Subject: [PATCH] bdev: Add function for reading actual disk size

This patch adds a GetActualSize for block devices that returns the
actual disk size. It is done using blockdev (and stat for file storage).

While this could be done via reading /sys/block/N/size, that is not as
simple as running blockdev, as the correspondence between an LV and its
sys entry is not straightforward.

Signed-off-by: Iustin Pop <iustin@google.com>
Reviewed-by: Guido Trotter <ultrotter@google.com>
---
 lib/bdev.py | 30 ++++++++++++++++++++++++++++++
 1 file changed, 30 insertions(+)

diff --git a/lib/bdev.py b/lib/bdev.py
index 2d7c969af..a6dd45d06 100644
--- a/lib/bdev.py
+++ b/lib/bdev.py
@@ -277,6 +277,23 @@ class BlockDev(object):
     """
     raise NotImplementedError
 
+  def GetActualSize(self):
+    """Return the actual disk size.
+
+    @note: the device needs to be active when this is called
+
+    """
+    assert self.attached, "BlockDevice not attached in GetActualSize()"
+    result = utils.RunCmd(["blockdev", "--getsize64", self.dev_path])
+    if result.failed:
+      _ThrowError("blockdev failed (%s): %s",
+                  result.fail_reason, result.output)
+    try:
+      sz = int(result.output.strip())
+    except (ValueError, TypeError), err:
+      _ThrowError("Failed to parse blockdev output: %s", str(err))
+    return sz
+
   def __repr__(self):
     return ("<%s: unique_id: %s, children: %s, %s:%s, %s>" %
             (self.__class__, self.unique_id, self._children,
@@ -1728,6 +1745,19 @@ class FileStorage(BlockDev):
     self.attached = os.path.exists(self.dev_path)
     return self.attached
 
+  def GetActualSize(self):
+    """Return the actual disk size.
+
+    @note: the device needs to be active when this is called
+
+    """
+    assert self.attached, "BlockDevice not attached in GetActualSize()"
+    try:
+      st = os.stat(self.dev_path)
+      return st.st_size
+    except OSError, err:
+      _ThrowError("Can't stat %s: %s", self.dev_path, err)
+
   @classmethod
   def Create(cls, unique_id, children, size):
     """Create a new file.
-- 
GitLab