From f3fd46e9c6e387cf4c823e398f77c00d51a6a195 Mon Sep 17 00:00:00 2001 From: Artem Bityutskiy Date: Wed, 10 Apr 2013 11:36:05 +0300 Subject: [PATCH] gpt_parser: introduce a _disk_read helper It is useful because we can encapsulate all the error checking in a single function. Change-Id: I0aac2d2223bc75113b43994db39df71f2ed7cf89 Signed-off-by: Artem Bityutskiy --- mic/utils/gpt_parser.py | 37 ++++++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/mic/utils/gpt_parser.py b/mic/utils/gpt_parser.py index 4160340..ada07af 100644 --- a/mic/utils/gpt_parser.py +++ b/mic/utils/gpt_parser.py @@ -98,6 +98,24 @@ class GptParser: self._disk_obj.close() + def _read_disk(self, offset, size): + """ A helper function which reads 'size' bytes from offset 'offset' of + the disk and checks all the error conditions. """ + + self._disk_obj.seek(offset) + try: + data = self._disk_obj.read(size) + except IOError as err: + raise MountError("cannot read from '%s': %s" % \ + (self.disk_path, err)) + + if len(data) != size: + raise MountError("cannot read %d bytes from offset '%d' of '%s', " \ + "read only %d bytes" % \ + (size, offset, self.disk_path, len(data))) + + return data + def read_header(self, primary = True): """ Read and verify the GPT header and return a tuple containing the following elements: @@ -113,26 +131,15 @@ class GptParser: If the 'primary' parameter is 'True', the primary GPT header is read, otherwise the backup GPT header is read instead. """ - # Read and validate the primary GPT header - self._disk_obj.seek(self.sector_size) - try: - raw_hdr = self._disk_obj.read(struct.calcsize(_GPT_HEADER_FORMAT)) - except IOError as err: - raise MountError("cannot read from file '%s': %s" % \ - (self.disk_path, err)) + header_size = struct.calcsize(_GPT_HEADER_FORMAT) + # Read and validate the primary GPT header + raw_hdr = self._read_disk(self.sector_size, header_size) raw_hdr = struct.unpack(_GPT_HEADER_FORMAT, raw_hdr) _validate_header(raw_hdr) if not primary: - # Read and validate the backup GPT header - self._disk_obj.seek(raw_hdr[6] * self.sector_size) - try: - raw_hdr = self._disk_obj.read(struct.calcsize(_GPT_HEADER_FORMAT)) - except IOError as err: - raise MountError("cannot read from file '%s': %s" % \ - (self.disk_path, err)) - + raw_hdr = self._read_disk(raw_hdr[6] * self.sector_size, header_size) raw_hdr = struct.unpack(_GPT_HEADER_FORMAT, raw_hdr) _validate_header(raw_hdr) -- 2.7.4