_store_backends.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. """Storage providers backends for Memory caching."""
  2. import re
  3. import os
  4. import os.path
  5. import datetime
  6. import json
  7. import shutil
  8. import warnings
  9. import collections
  10. import operator
  11. import threading
  12. from abc import ABCMeta, abstractmethod
  13. from .backports import concurrency_safe_rename
  14. from .disk import mkdirp, memstr_to_bytes, rm_subdirs
  15. from . import numpy_pickle
  16. CacheItemInfo = collections.namedtuple('CacheItemInfo',
  17. 'path size last_access')
  18. def concurrency_safe_write(object_to_write, filename, write_func):
  19. """Writes an object into a unique file in a concurrency-safe way."""
  20. thread_id = id(threading.current_thread())
  21. temporary_filename = '{}.thread-{}-pid-{}'.format(
  22. filename, thread_id, os.getpid())
  23. write_func(object_to_write, temporary_filename)
  24. return temporary_filename
  25. class StoreBackendBase(metaclass=ABCMeta):
  26. """Helper Abstract Base Class which defines all methods that
  27. a StorageBackend must implement."""
  28. location = None
  29. @abstractmethod
  30. def _open_item(self, f, mode):
  31. """Opens an item on the store and return a file-like object.
  32. This method is private and only used by the StoreBackendMixin object.
  33. Parameters
  34. ----------
  35. f: a file-like object
  36. The file-like object where an item is stored and retrieved
  37. mode: string, optional
  38. the mode in which the file-like object is opened allowed valued are
  39. 'rb', 'wb'
  40. Returns
  41. -------
  42. a file-like object
  43. """
  44. @abstractmethod
  45. def _item_exists(self, location):
  46. """Checks if an item location exists in the store.
  47. This method is private and only used by the StoreBackendMixin object.
  48. Parameters
  49. ----------
  50. location: string
  51. The location of an item. On a filesystem, this corresponds to the
  52. absolute path, including the filename, of a file.
  53. Returns
  54. -------
  55. True if the item exists, False otherwise
  56. """
  57. @abstractmethod
  58. def _move_item(self, src, dst):
  59. """Moves an item from src to dst in the store.
  60. This method is private and only used by the StoreBackendMixin object.
  61. Parameters
  62. ----------
  63. src: string
  64. The source location of an item
  65. dst: string
  66. The destination location of an item
  67. """
  68. @abstractmethod
  69. def create_location(self, location):
  70. """Creates a location on the store.
  71. Parameters
  72. ----------
  73. location: string
  74. The location in the store. On a filesystem, this corresponds to a
  75. directory.
  76. """
  77. @abstractmethod
  78. def clear_location(self, location):
  79. """Clears a location on the store.
  80. Parameters
  81. ----------
  82. location: string
  83. The location in the store. On a filesystem, this corresponds to a
  84. directory or a filename absolute path
  85. """
  86. @abstractmethod
  87. def get_items(self):
  88. """Returns the whole list of items available in the store.
  89. Returns
  90. -------
  91. The list of items identified by their ids (e.g filename in a
  92. filesystem).
  93. """
  94. @abstractmethod
  95. def configure(self, location, verbose=0, backend_options=dict()):
  96. """Configures the store.
  97. Parameters
  98. ----------
  99. location: string
  100. The base location used by the store. On a filesystem, this
  101. corresponds to a directory.
  102. verbose: int
  103. The level of verbosity of the store
  104. backend_options: dict
  105. Contains a dictionnary of named paremeters used to configure the
  106. store backend.
  107. """
  108. class StoreBackendMixin(object):
  109. """Class providing all logic for managing the store in a generic way.
  110. The StoreBackend subclass has to implement 3 methods: create_location,
  111. clear_location and configure. The StoreBackend also has to provide
  112. a private _open_item, _item_exists and _move_item methods. The _open_item
  113. method has to have the same signature as the builtin open and return a
  114. file-like object.
  115. """
  116. def load_item(self, path, verbose=1, msg=None):
  117. """Load an item from the store given its path as a list of
  118. strings."""
  119. full_path = os.path.join(self.location, *path)
  120. if verbose > 1:
  121. if verbose < 10:
  122. print('{0}...'.format(msg))
  123. else:
  124. print('{0} from {1}'.format(msg, full_path))
  125. mmap_mode = (None if not hasattr(self, 'mmap_mode')
  126. else self.mmap_mode)
  127. filename = os.path.join(full_path, 'output.pkl')
  128. if not self._item_exists(filename):
  129. raise KeyError("Non-existing item (may have been "
  130. "cleared).\nFile %s does not exist" % filename)
  131. # file-like object cannot be used when mmap_mode is set
  132. if mmap_mode is None:
  133. with self._open_item(filename, "rb") as f:
  134. item = numpy_pickle.load(f)
  135. else:
  136. item = numpy_pickle.load(filename, mmap_mode=mmap_mode)
  137. return item
  138. def dump_item(self, path, item, verbose=1):
  139. """Dump an item in the store at the path given as a list of
  140. strings."""
  141. try:
  142. item_path = os.path.join(self.location, *path)
  143. if not self._item_exists(item_path):
  144. self.create_location(item_path)
  145. filename = os.path.join(item_path, 'output.pkl')
  146. if verbose > 10:
  147. print('Persisting in %s' % item_path)
  148. def write_func(to_write, dest_filename):
  149. with self._open_item(dest_filename, "wb") as f:
  150. numpy_pickle.dump(to_write, f,
  151. compress=self.compress)
  152. self._concurrency_safe_write(item, filename, write_func)
  153. except: # noqa: E722
  154. " Race condition in the creation of the directory "
  155. def clear_item(self, path):
  156. """Clear the item at the path, given as a list of strings."""
  157. item_path = os.path.join(self.location, *path)
  158. if self._item_exists(item_path):
  159. self.clear_location(item_path)
  160. def contains_item(self, path):
  161. """Check if there is an item at the path, given as a list of
  162. strings"""
  163. item_path = os.path.join(self.location, *path)
  164. filename = os.path.join(item_path, 'output.pkl')
  165. return self._item_exists(filename)
  166. def get_item_info(self, path):
  167. """Return information about item."""
  168. return {'location': os.path.join(self.location,
  169. *path)}
  170. def get_metadata(self, path):
  171. """Return actual metadata of an item."""
  172. try:
  173. item_path = os.path.join(self.location, *path)
  174. filename = os.path.join(item_path, 'metadata.json')
  175. with self._open_item(filename, 'rb') as f:
  176. return json.loads(f.read().decode('utf-8'))
  177. except: # noqa: E722
  178. return {}
  179. def store_metadata(self, path, metadata):
  180. """Store metadata of a computation."""
  181. try:
  182. item_path = os.path.join(self.location, *path)
  183. self.create_location(item_path)
  184. filename = os.path.join(item_path, 'metadata.json')
  185. def write_func(to_write, dest_filename):
  186. with self._open_item(dest_filename, "wb") as f:
  187. f.write(json.dumps(to_write).encode('utf-8'))
  188. self._concurrency_safe_write(metadata, filename, write_func)
  189. except: # noqa: E722
  190. pass
  191. def contains_path(self, path):
  192. """Check cached function is available in store."""
  193. func_path = os.path.join(self.location, *path)
  194. return self.object_exists(func_path)
  195. def clear_path(self, path):
  196. """Clear all items with a common path in the store."""
  197. func_path = os.path.join(self.location, *path)
  198. if self._item_exists(func_path):
  199. self.clear_location(func_path)
  200. def store_cached_func_code(self, path, func_code=None):
  201. """Store the code of the cached function."""
  202. func_path = os.path.join(self.location, *path)
  203. if not self._item_exists(func_path):
  204. self.create_location(func_path)
  205. if func_code is not None:
  206. filename = os.path.join(func_path, "func_code.py")
  207. with self._open_item(filename, 'wb') as f:
  208. f.write(func_code.encode('utf-8'))
  209. def get_cached_func_code(self, path):
  210. """Store the code of the cached function."""
  211. path += ['func_code.py', ]
  212. filename = os.path.join(self.location, *path)
  213. try:
  214. with self._open_item(filename, 'rb') as f:
  215. return f.read().decode('utf-8')
  216. except: # noqa: E722
  217. raise
  218. def get_cached_func_info(self, path):
  219. """Return information related to the cached function if it exists."""
  220. return {'location': os.path.join(self.location, *path)}
  221. def clear(self):
  222. """Clear the whole store content."""
  223. self.clear_location(self.location)
  224. def reduce_store_size(self, bytes_limit):
  225. """Reduce store size to keep it under the given bytes limit."""
  226. items_to_delete = self._get_items_to_delete(bytes_limit)
  227. for item in items_to_delete:
  228. if self.verbose > 10:
  229. print('Deleting item {0}'.format(item))
  230. try:
  231. self.clear_location(item.path)
  232. except OSError:
  233. # Even with ignore_errors=True shutil.rmtree can raise OSError
  234. # with:
  235. # [Errno 116] Stale file handle if another process has deleted
  236. # the folder already.
  237. pass
  238. def _get_items_to_delete(self, bytes_limit):
  239. """Get items to delete to keep the store under a size limit."""
  240. if isinstance(bytes_limit, str):
  241. bytes_limit = memstr_to_bytes(bytes_limit)
  242. items = self.get_items()
  243. size = sum(item.size for item in items)
  244. to_delete_size = size - bytes_limit
  245. if to_delete_size < 0:
  246. return []
  247. # We want to delete first the cache items that were accessed a
  248. # long time ago
  249. items.sort(key=operator.attrgetter('last_access'))
  250. items_to_delete = []
  251. size_so_far = 0
  252. for item in items:
  253. if size_so_far > to_delete_size:
  254. break
  255. items_to_delete.append(item)
  256. size_so_far += item.size
  257. return items_to_delete
  258. def _concurrency_safe_write(self, to_write, filename, write_func):
  259. """Writes an object into a file in a concurrency-safe way."""
  260. temporary_filename = concurrency_safe_write(to_write,
  261. filename, write_func)
  262. self._move_item(temporary_filename, filename)
  263. def __repr__(self):
  264. """Printable representation of the store location."""
  265. return '{class_name}(location="{location}")'.format(
  266. class_name=self.__class__.__name__, location=self.location)
  267. class FileSystemStoreBackend(StoreBackendBase, StoreBackendMixin):
  268. """A StoreBackend used with local or network file systems."""
  269. _open_item = staticmethod(open)
  270. _item_exists = staticmethod(os.path.exists)
  271. _move_item = staticmethod(concurrency_safe_rename)
  272. def clear_location(self, location):
  273. """Delete location on store."""
  274. if (location == self.location):
  275. rm_subdirs(location)
  276. else:
  277. shutil.rmtree(location, ignore_errors=True)
  278. def create_location(self, location):
  279. """Create object location on store"""
  280. mkdirp(location)
  281. def get_items(self):
  282. """Returns the whole list of items available in the store."""
  283. items = []
  284. for dirpath, _, filenames in os.walk(self.location):
  285. is_cache_hash_dir = re.match('[a-f0-9]{32}',
  286. os.path.basename(dirpath))
  287. if is_cache_hash_dir:
  288. output_filename = os.path.join(dirpath, 'output.pkl')
  289. try:
  290. last_access = os.path.getatime(output_filename)
  291. except OSError:
  292. try:
  293. last_access = os.path.getatime(dirpath)
  294. except OSError:
  295. # The directory has already been deleted
  296. continue
  297. last_access = datetime.datetime.fromtimestamp(last_access)
  298. try:
  299. full_filenames = [os.path.join(dirpath, fn)
  300. for fn in filenames]
  301. dirsize = sum(os.path.getsize(fn)
  302. for fn in full_filenames)
  303. except OSError:
  304. # Either output_filename or one of the files in
  305. # dirpath does not exist any more. We assume this
  306. # directory is being cleaned by another process already
  307. continue
  308. items.append(CacheItemInfo(dirpath, dirsize,
  309. last_access))
  310. return items
  311. def configure(self, location, verbose=1, backend_options=None):
  312. """Configure the store backend.
  313. For this backend, valid store options are 'compress' and 'mmap_mode'
  314. """
  315. if backend_options is None:
  316. backend_options = {}
  317. # setup location directory
  318. self.location = location
  319. if not os.path.exists(self.location):
  320. mkdirp(self.location)
  321. # item can be stored compressed for faster I/O
  322. self.compress = backend_options.get('compress', False)
  323. # FileSystemStoreBackend can be used with mmap_mode options under
  324. # certain conditions.
  325. mmap_mode = backend_options.get('mmap_mode')
  326. if self.compress and mmap_mode is not None:
  327. warnings.warn('Compressed items cannot be memmapped in a '
  328. 'filesystem store. Option will be ignored.',
  329. stacklevel=2)
  330. self.mmap_mode = mmap_mode
  331. self.verbose = verbose