fstransactions.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. # Copyright (C) 2012, Ansgar Burchardt <ansgar@debian.org>
  2. #
  3. # This program is free software; you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation; either version 2 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License along
  14. # with this program; if not, write to the Free Software Foundation, Inc.,
  15. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  16. """Transactions for filesystem actions
  17. """
  18. import errno
  19. import os
  20. import shutil
  21. class _FilesystemAction(object):
  22. @property
  23. def temporary_name(self):
  24. raise NotImplementedError()
  25. def check_for_temporary(self):
  26. try:
  27. if os.path.exists(self.temporary_name):
  28. raise IOError("Temporary file '{0}' already exists.".format(self.temporary_name))
  29. except NotImplementedError:
  30. pass
  31. class _FilesystemCopyAction(_FilesystemAction):
  32. def __init__(self, source, destination, link=True, symlink=False, mode=None):
  33. self.destination = destination
  34. self.need_cleanup = False
  35. dirmode = 0o2755
  36. if mode is not None:
  37. dirmode = 0o2700 | mode
  38. # Allow +x for group and others if they have +r.
  39. if dirmode & 0o0040:
  40. dirmode = dirmode | 0o0010
  41. if dirmode & 0o0004:
  42. dirmode = dirmode | 0o0001
  43. self.check_for_temporary()
  44. destdir = os.path.dirname(self.destination)
  45. if not os.path.exists(destdir):
  46. os.makedirs(destdir, dirmode)
  47. if symlink:
  48. os.symlink(source, self.destination)
  49. elif link:
  50. try:
  51. os.link(source, self.destination)
  52. except OSError:
  53. shutil.copy2(source, self.destination)
  54. else:
  55. shutil.copy2(source, self.destination)
  56. self.need_cleanup = True
  57. if mode is not None:
  58. os.chmod(self.destination, mode)
  59. @property
  60. def temporary_name(self):
  61. return self.destination
  62. def commit(self):
  63. pass
  64. def rollback(self):
  65. if self.need_cleanup:
  66. os.unlink(self.destination)
  67. self.need_cleanup = False
  68. class _FilesystemUnlinkAction(_FilesystemAction):
  69. def __init__(self, path):
  70. self.path = path
  71. self.need_cleanup = False
  72. self.check_for_temporary()
  73. os.rename(self.path, self.temporary_name)
  74. self.need_cleanup = True
  75. @property
  76. def temporary_name(self):
  77. return "{0}.dak-rm".format(self.path)
  78. def commit(self):
  79. if self.need_cleanup:
  80. os.unlink(self.temporary_name)
  81. self.need_cleanup = False
  82. def rollback(self):
  83. if self.need_cleanup:
  84. os.rename(self.temporary_name, self.path)
  85. self.need_cleanup = False
  86. class _FilesystemCreateAction(_FilesystemAction):
  87. def __init__(self, path):
  88. self.path = path
  89. self.need_cleanup = True
  90. @property
  91. def temporary_name(self):
  92. return self.path
  93. def commit(self):
  94. pass
  95. def rollback(self):
  96. if self.need_cleanup:
  97. os.unlink(self.path)
  98. self.need_cleanup = False
  99. class FilesystemTransaction(object):
  100. """transactions for filesystem actions"""
  101. def __init__(self):
  102. self.actions = []
  103. def copy(self, source, destination, link=False, symlink=False, mode=None):
  104. """copy C{source} to C{destination}
  105. @type source: str
  106. @param source: source file
  107. @type destination: str
  108. @param destination: destination file
  109. @type link: bool
  110. @param link: try hardlinking, falling back to copying
  111. @type symlink: bool
  112. @param symlink: create a symlink instead of copying
  113. @type mode: int
  114. @param mode: permissions to change C{destination} to
  115. """
  116. if isinstance(mode, str) or isinstance(mode, unicode):
  117. mode = int(mode, 8)
  118. self.actions.append(_FilesystemCopyAction(source, destination, link=link, symlink=symlink, mode=mode))
  119. def move(self, source, destination, mode=None):
  120. """move C{source} to C{destination}
  121. @type source: str
  122. @param source: source file
  123. @type destination: str
  124. @param destination: destination file
  125. @type mode: int
  126. @param mode: permissions to change C{destination} to
  127. """
  128. self.copy(source, destination, link=True, mode=mode)
  129. self.unlink(source)
  130. def unlink(self, path):
  131. """unlink C{path}
  132. @type path: str
  133. @param path: file to unlink
  134. """
  135. self.actions.append(_FilesystemUnlinkAction(path))
  136. def create(self, path, mode=None):
  137. """create C{filename} and return file handle
  138. @type filename: str
  139. @param filename: file to create
  140. @type mode: int
  141. @param mode: permissions for the new file
  142. @return: file handle of the new file
  143. """
  144. if isinstance(mode, str) or isinstance(mode, unicode):
  145. mode = int(mode, 8)
  146. destdir = os.path.dirname(path)
  147. if not os.path.exists(destdir):
  148. os.makedirs(destdir, 0o2775)
  149. if os.path.exists(path):
  150. raise IOError("File '{0}' already exists.".format(path))
  151. fh = open(path, 'w')
  152. self.actions.append(_FilesystemCreateAction(path))
  153. if mode is not None:
  154. os.chmod(path, mode)
  155. return fh
  156. def commit(self):
  157. """Commit all recorded actions."""
  158. try:
  159. for action in self.actions:
  160. action.commit()
  161. except:
  162. self.rollback()
  163. raise
  164. finally:
  165. self.actions = []
  166. def rollback(self):
  167. """Undo all recorded actions."""
  168. try:
  169. for action in self.actions:
  170. action.rollback()
  171. finally:
  172. self.actions = []
  173. def __enter__(self):
  174. return self
  175. def __exit__(self, type, value, traceback):
  176. if type is None:
  177. self.commit()
  178. else:
  179. self.rollback()
  180. return None