/carbono/image_reader/generic.py

https://github.com/igorbonadio/carbono
Python | 73 lines | 45 code | 10 blank | 18 comment | 12 complexity | bd9ae4dafaad80dd2fb4e998fd7e9f4d MD5 | raw file
  1. #!/usr/bin/python
  2. # coding: utf-8
  3. # Copyright (C) 2011 Lucas Alvares Gomes <lucasagomes@gmail.com>
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 2 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, see <http://www.gnu.org/licenses/>.
  17. import os
  18. from carbono.config import *
  19. from carbono.utils import *
  20. class GenericReader:
  21. def __init__(self, image_path, pattern, volumes, notify_status):
  22. self.image_path = image_path
  23. self.pattern = pattern
  24. self.volumes = volumes
  25. self.current_volume = 1
  26. self.notify_callback = notify_status
  27. self._fd = None
  28. def _check_fd(self):
  29. return self._fd is None or self._fd.closed
  30. def open(self):
  31. if self._check_fd():
  32. file_pattern = self.pattern.format(volume=self.current_volume)
  33. # Loop untill find the the next slice or
  34. # cancel the operation
  35. while True:
  36. file_path = self.image_path + file_pattern
  37. if os.path.exists(file_path):
  38. self._fd = open(file_path, 'rb')
  39. else:
  40. self.image_path = self.notify_callback("file_not_found",
  41. {"path": self.image_path, "file": file_pattern})
  42. if self.image_path:
  43. self.image_path = adjust_path(self.image_path)
  44. continue
  45. else:
  46. self.notify_callback("canceled",
  47. {"operation": "Restoring image"})
  48. break
  49. def close(self):
  50. if not self._check_fd():
  51. self._fd.close()
  52. def read_block(self):
  53. if not self._check_fd():
  54. data = self._fd.read(BLOCK_SIZE)
  55. if not len(data):
  56. self.close()
  57. if self.current_volume < self.volumes:
  58. self.current_volume += 1
  59. self.open()
  60. data = self.read_block()
  61. else:
  62. return None
  63. return data