You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

399 lines
12KB

  1. # Copyright (C) 2010, 2011 Sebastian Thiel (byronimo@gmail.com) and contributors
  2. #
  3. # This module is part of GitDB and is released under
  4. # the New BSD License: http://www.opensource.org/licenses/bsd-license.php
  5. import binascii
  6. import os
  7. import mmap
  8. import sys
  9. import time
  10. import errno
  11. from io import BytesIO
  12. from smmap import (
  13. StaticWindowMapManager,
  14. SlidingWindowMapManager,
  15. SlidingWindowMapBuffer
  16. )
  17. # initialize our global memory manager instance
  18. # Use it to free cached (and unused) resources.
  19. mman = SlidingWindowMapManager()
  20. # END handle mman
  21. import hashlib
  22. try:
  23. from struct import unpack_from
  24. except ImportError:
  25. from struct import unpack, calcsize
  26. __calcsize_cache = dict()
  27. def unpack_from(fmt, data, offset=0):
  28. try:
  29. size = __calcsize_cache[fmt]
  30. except KeyError:
  31. size = calcsize(fmt)
  32. __calcsize_cache[fmt] = size
  33. # END exception handling
  34. return unpack(fmt, data[offset: offset + size])
  35. # END own unpack_from implementation
  36. #{ Aliases
  37. hex_to_bin = binascii.a2b_hex
  38. bin_to_hex = binascii.b2a_hex
  39. # errors
  40. ENOENT = errno.ENOENT
  41. # os shortcuts
  42. exists = os.path.exists
  43. mkdir = os.mkdir
  44. chmod = os.chmod
  45. isdir = os.path.isdir
  46. isfile = os.path.isfile
  47. rename = os.rename
  48. dirname = os.path.dirname
  49. basename = os.path.basename
  50. join = os.path.join
  51. read = os.read
  52. write = os.write
  53. close = os.close
  54. fsync = os.fsync
  55. def _retry(func, *args, **kwargs):
  56. # Wrapper around functions, that are problematic on "Windows". Sometimes
  57. # the OS or someone else has still a handle to the file
  58. if sys.platform == "win32":
  59. for _ in range(10):
  60. try:
  61. return func(*args, **kwargs)
  62. except Exception:
  63. time.sleep(0.1)
  64. return func(*args, **kwargs)
  65. else:
  66. return func(*args, **kwargs)
  67. def remove(*args, **kwargs):
  68. return _retry(os.remove, *args, **kwargs)
  69. # Backwards compatibility imports
  70. from gitdb.const import (
  71. NULL_BIN_SHA,
  72. NULL_HEX_SHA
  73. )
  74. #} END Aliases
  75. #{ compatibility stuff ...
  76. class _RandomAccessBytesIO(object):
  77. """Wrapper to provide required functionality in case memory maps cannot or may
  78. not be used. This is only really required in python 2.4"""
  79. __slots__ = '_sio'
  80. def __init__(self, buf=''):
  81. self._sio = BytesIO(buf)
  82. def __getattr__(self, attr):
  83. return getattr(self._sio, attr)
  84. def __len__(self):
  85. return len(self.getvalue())
  86. def __getitem__(self, i):
  87. return self.getvalue()[i]
  88. def __getslice__(self, start, end):
  89. return self.getvalue()[start:end]
  90. def byte_ord(b):
  91. """
  92. Return the integer representation of the byte string. This supports Python
  93. 3 byte arrays as well as standard strings.
  94. """
  95. try:
  96. return ord(b)
  97. except TypeError:
  98. return b
  99. #} END compatibility stuff ...
  100. #{ Routines
  101. def make_sha(source=''.encode("ascii")):
  102. """A python2.4 workaround for the sha/hashlib module fiasco
  103. **Note** From the dulwich project """
  104. try:
  105. return hashlib.sha1(source)
  106. except NameError:
  107. import sha
  108. sha1 = sha.sha(source)
  109. return sha1
  110. def allocate_memory(size):
  111. """:return: a file-protocol accessible memory block of the given size"""
  112. if size == 0:
  113. return _RandomAccessBytesIO(b'')
  114. # END handle empty chunks gracefully
  115. try:
  116. return mmap.mmap(-1, size) # read-write by default
  117. except EnvironmentError:
  118. # setup real memory instead
  119. # this of course may fail if the amount of memory is not available in
  120. # one chunk - would only be the case in python 2.4, being more likely on
  121. # 32 bit systems.
  122. return _RandomAccessBytesIO(b"\0" * size)
  123. # END handle memory allocation
  124. def file_contents_ro(fd, stream=False, allow_mmap=True):
  125. """:return: read-only contents of the file represented by the file descriptor fd
  126. :param fd: file descriptor opened for reading
  127. :param stream: if False, random access is provided, otherwise the stream interface
  128. is provided.
  129. :param allow_mmap: if True, its allowed to map the contents into memory, which
  130. allows large files to be handled and accessed efficiently. The file-descriptor
  131. will change its position if this is False"""
  132. try:
  133. if allow_mmap:
  134. # supports stream and random access
  135. try:
  136. return mmap.mmap(fd, 0, access=mmap.ACCESS_READ)
  137. except EnvironmentError:
  138. # python 2.4 issue, 0 wants to be the actual size
  139. return mmap.mmap(fd, os.fstat(fd).st_size, access=mmap.ACCESS_READ)
  140. # END handle python 2.4
  141. except OSError:
  142. pass
  143. # END exception handling
  144. # read manully
  145. contents = os.read(fd, os.fstat(fd).st_size)
  146. if stream:
  147. return _RandomAccessBytesIO(contents)
  148. return contents
  149. def file_contents_ro_filepath(filepath, stream=False, allow_mmap=True, flags=0):
  150. """Get the file contents at filepath as fast as possible
  151. :return: random access compatible memory of the given filepath
  152. :param stream: see ``file_contents_ro``
  153. :param allow_mmap: see ``file_contents_ro``
  154. :param flags: additional flags to pass to os.open
  155. :raise OSError: If the file could not be opened
  156. **Note** for now we don't try to use O_NOATIME directly as the right value needs to be
  157. shared per database in fact. It only makes a real difference for loose object
  158. databases anyway, and they use it with the help of the ``flags`` parameter"""
  159. fd = os.open(filepath, os.O_RDONLY | getattr(os, 'O_BINARY', 0) | flags)
  160. try:
  161. return file_contents_ro(fd, stream, allow_mmap)
  162. finally:
  163. close(fd)
  164. # END assure file is closed
  165. def sliding_ro_buffer(filepath, flags=0):
  166. """
  167. :return: a buffer compatible object which uses our mapped memory manager internally
  168. ready to read the whole given filepath"""
  169. return SlidingWindowMapBuffer(mman.make_cursor(filepath), flags=flags)
  170. def to_hex_sha(sha):
  171. """:return: hexified version of sha"""
  172. if len(sha) == 40:
  173. return sha
  174. return bin_to_hex(sha)
  175. def to_bin_sha(sha):
  176. if len(sha) == 20:
  177. return sha
  178. return hex_to_bin(sha)
  179. #} END routines
  180. #{ Utilities
  181. class LazyMixin(object):
  182. """
  183. Base class providing an interface to lazily retrieve attribute values upon
  184. first access. If slots are used, memory will only be reserved once the attribute
  185. is actually accessed and retrieved the first time. All future accesses will
  186. return the cached value as stored in the Instance's dict or slot.
  187. """
  188. __slots__ = tuple()
  189. def __getattr__(self, attr):
  190. """
  191. Whenever an attribute is requested that we do not know, we allow it
  192. to be created and set. Next time the same attribute is reqeusted, it is simply
  193. returned from our dict/slots. """
  194. self._set_cache_(attr)
  195. # will raise in case the cache was not created
  196. return object.__getattribute__(self, attr)
  197. def _set_cache_(self, attr):
  198. """
  199. This method should be overridden in the derived class.
  200. It should check whether the attribute named by attr can be created
  201. and cached. Do nothing if you do not know the attribute or call your subclass
  202. The derived class may create as many additional attributes as it deems
  203. necessary in case a git command returns more information than represented
  204. in the single attribute."""
  205. pass
  206. class LockedFD(object):
  207. """
  208. This class facilitates a safe read and write operation to a file on disk.
  209. If we write to 'file', we obtain a lock file at 'file.lock' and write to
  210. that instead. If we succeed, the lock file will be renamed to overwrite
  211. the original file.
  212. When reading, we obtain a lock file, but to prevent other writers from
  213. succeeding while we are reading the file.
  214. This type handles error correctly in that it will assure a consistent state
  215. on destruction.
  216. **note** with this setup, parallel reading is not possible"""
  217. __slots__ = ("_filepath", '_fd', '_write')
  218. def __init__(self, filepath):
  219. """Initialize an instance with the givne filepath"""
  220. self._filepath = filepath
  221. self._fd = None
  222. self._write = None # if True, we write a file
  223. def __del__(self):
  224. # will do nothing if the file descriptor is already closed
  225. if self._fd is not None:
  226. self.rollback()
  227. def _lockfilepath(self):
  228. return "%s.lock" % self._filepath
  229. def open(self, write=False, stream=False):
  230. """
  231. Open the file descriptor for reading or writing, both in binary mode.
  232. :param write: if True, the file descriptor will be opened for writing. Other
  233. wise it will be opened read-only.
  234. :param stream: if True, the file descriptor will be wrapped into a simple stream
  235. object which supports only reading or writing
  236. :return: fd to read from or write to. It is still maintained by this instance
  237. and must not be closed directly
  238. :raise IOError: if the lock could not be retrieved
  239. :raise OSError: If the actual file could not be opened for reading
  240. **note** must only be called once"""
  241. if self._write is not None:
  242. raise AssertionError("Called %s multiple times" % self.open)
  243. self._write = write
  244. # try to open the lock file
  245. binary = getattr(os, 'O_BINARY', 0)
  246. lockmode = os.O_WRONLY | os.O_CREAT | os.O_EXCL | binary
  247. try:
  248. fd = os.open(self._lockfilepath(), lockmode, int("600", 8))
  249. if not write:
  250. os.close(fd)
  251. else:
  252. self._fd = fd
  253. # END handle file descriptor
  254. except OSError:
  255. raise IOError("Lock at %r could not be obtained" % self._lockfilepath())
  256. # END handle lock retrieval
  257. # open actual file if required
  258. if self._fd is None:
  259. # we could specify exlusive here, as we obtained the lock anyway
  260. try:
  261. self._fd = os.open(self._filepath, os.O_RDONLY | binary)
  262. except:
  263. # assure we release our lockfile
  264. remove(self._lockfilepath())
  265. raise
  266. # END handle lockfile
  267. # END open descriptor for reading
  268. if stream:
  269. # need delayed import
  270. from gitdb.stream import FDStream
  271. return FDStream(self._fd)
  272. else:
  273. return self._fd
  274. # END handle stream
  275. def commit(self):
  276. """When done writing, call this function to commit your changes into the
  277. actual file.
  278. The file descriptor will be closed, and the lockfile handled.
  279. **Note** can be called multiple times"""
  280. self._end_writing(successful=True)
  281. def rollback(self):
  282. """Abort your operation without any changes. The file descriptor will be
  283. closed, and the lock released.
  284. **Note** can be called multiple times"""
  285. self._end_writing(successful=False)
  286. def _end_writing(self, successful=True):
  287. """Handle the lock according to the write mode """
  288. if self._write is None:
  289. raise AssertionError("Cannot end operation if it wasn't started yet")
  290. if self._fd is None:
  291. return
  292. os.close(self._fd)
  293. self._fd = None
  294. lockfile = self._lockfilepath()
  295. if self._write and successful:
  296. # on windows, rename does not silently overwrite the existing one
  297. if sys.platform == "win32":
  298. if isfile(self._filepath):
  299. remove(self._filepath)
  300. # END remove if exists
  301. # END win32 special handling
  302. os.rename(lockfile, self._filepath)
  303. # assure others can at least read the file - the tmpfile left it at rw--
  304. # We may also write that file, on windows that boils down to a remove-
  305. # protection as well
  306. chmod(self._filepath, int("644", 8))
  307. else:
  308. # just delete the file so far, we failed
  309. remove(lockfile)
  310. # END successful handling
  311. #} END utilities