_store_backends.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. """Storage providers backends for Memory caching."""
  2. import collections
  3. import datetime
  4. import json
  5. import operator
  6. import os
  7. import os.path
  8. import re
  9. import shutil
  10. import threading
  11. import time
  12. import uuid
  13. import warnings
  14. from abc import ABCMeta, abstractmethod
  15. from pickle import PicklingError
  16. from . import numpy_pickle
  17. from .backports import concurrency_safe_rename
  18. from .disk import memstr_to_bytes, mkdirp, rm_subdirs
  19. from .logger import format_time
  20. CacheItemInfo = collections.namedtuple("CacheItemInfo", "path size last_access")
  21. class CacheWarning(Warning):
  22. """Warning to capture dump failures except for PicklingError."""
  23. pass
  24. def concurrency_safe_write(object_to_write, filename, write_func):
  25. """Writes an object into a unique file in a concurrency-safe way."""
  26. # Temporary name is composed of UUID, process_id and thread_id to avoid
  27. # collisions due to concurrent write.
  28. # UUID is unique across nodes and time and help avoid collisions, even if
  29. # the cache folder is shared by several Python processes with the same pid and
  30. # thread id on different nodes of a cluster for instance.
  31. thread_id = id(threading.current_thread())
  32. temporary_filename = f"{filename}.{uuid.uuid4().hex}-{os.getpid()}-{thread_id}"
  33. write_func(object_to_write, temporary_filename)
  34. return temporary_filename
  35. class StoreBackendBase(metaclass=ABCMeta):
  36. """Helper Abstract Base Class which defines all methods that
  37. a StorageBackend must implement."""
  38. location = None
  39. @abstractmethod
  40. def _open_item(self, f, mode):
  41. """Opens an item on the store and return a file-like object.
  42. This method is private and only used by the StoreBackendMixin object.
  43. Parameters
  44. ----------
  45. f: a file-like object
  46. The file-like object where an item is stored and retrieved
  47. mode: string, optional
  48. the mode in which the file-like object is opened allowed valued are
  49. 'rb', 'wb'
  50. Returns
  51. -------
  52. a file-like object
  53. """
  54. @abstractmethod
  55. def _item_exists(self, location):
  56. """Checks if an item location exists in the store.
  57. This method is private and only used by the StoreBackendMixin object.
  58. Parameters
  59. ----------
  60. location: string
  61. The location of an item. On a filesystem, this corresponds to the
  62. absolute path, including the filename, of a file.
  63. Returns
  64. -------
  65. True if the item exists, False otherwise
  66. """
  67. @abstractmethod
  68. def _move_item(self, src, dst):
  69. """Moves an item from src to dst in the store.
  70. This method is private and only used by the StoreBackendMixin object.
  71. Parameters
  72. ----------
  73. src: string
  74. The source location of an item
  75. dst: string
  76. The destination location of an item
  77. """
  78. @abstractmethod
  79. def create_location(self, location):
  80. """Creates a location on the store.
  81. Parameters
  82. ----------
  83. location: string
  84. The location in the store. On a filesystem, this corresponds to a
  85. directory.
  86. """
  87. @abstractmethod
  88. def clear_location(self, location):
  89. """Clears a location on the store.
  90. Parameters
  91. ----------
  92. location: string
  93. The location in the store. On a filesystem, this corresponds to a
  94. directory or a filename absolute path
  95. """
  96. @abstractmethod
  97. def get_items(self):
  98. """Returns the whole list of items available in the store.
  99. Returns
  100. -------
  101. The list of items identified by their ids (e.g filename in a
  102. filesystem).
  103. """
  104. @abstractmethod
  105. def configure(self, location, verbose=0, backend_options=dict()):
  106. """Configures the store.
  107. Parameters
  108. ----------
  109. location: string
  110. The base location used by the store. On a filesystem, this
  111. corresponds to a directory.
  112. verbose: int
  113. The level of verbosity of the store
  114. backend_options: dict
  115. Contains a dictionary of named parameters used to configure the
  116. store backend.
  117. """
  118. class StoreBackendMixin(object):
  119. """Class providing all logic for managing the store in a generic way.
  120. The StoreBackend subclass has to implement 3 methods: create_location,
  121. clear_location and configure. The StoreBackend also has to provide
  122. a private _open_item, _item_exists and _move_item methods. The _open_item
  123. method has to have the same signature as the builtin open and return a
  124. file-like object.
  125. """
  126. def load_item(self, call_id, verbose=1, timestamp=None, metadata=None):
  127. """Load an item from the store given its id as a list of str."""
  128. full_path = os.path.join(self.location, *call_id)
  129. if verbose > 1:
  130. ts_string = (
  131. "{: <16}".format(format_time(time.time() - timestamp))
  132. if timestamp is not None
  133. else ""
  134. )
  135. signature = os.path.basename(call_id[0])
  136. if metadata is not None and "input_args" in metadata:
  137. kwargs = ", ".join(
  138. "{}={}".format(*item) for item in metadata["input_args"].items()
  139. )
  140. signature += "({})".format(kwargs)
  141. msg = "[Memory]{}: Loading {}".format(ts_string, signature)
  142. if verbose < 10:
  143. print("{0}...".format(msg))
  144. else:
  145. print("{0} from {1}".format(msg, full_path))
  146. mmap_mode = None if not hasattr(self, "mmap_mode") else self.mmap_mode
  147. filename = os.path.join(full_path, "output.pkl")
  148. if not self._item_exists(filename):
  149. raise KeyError(
  150. "Non-existing item (may have been "
  151. "cleared).\nFile %s does not exist" % filename
  152. )
  153. # file-like object cannot be used when mmap_mode is set
  154. if mmap_mode is None:
  155. with self._open_item(filename, "rb") as f:
  156. item = numpy_pickle.load(f)
  157. else:
  158. item = numpy_pickle.load(filename, mmap_mode=mmap_mode)
  159. return item
  160. def dump_item(self, call_id, item, verbose=1):
  161. """Dump an item in the store at the id given as a list of str."""
  162. try:
  163. item_path = os.path.join(self.location, *call_id)
  164. if not self._item_exists(item_path):
  165. self.create_location(item_path)
  166. filename = os.path.join(item_path, "output.pkl")
  167. if verbose > 10:
  168. print("Persisting in %s" % item_path)
  169. def write_func(to_write, dest_filename):
  170. with self._open_item(dest_filename, "wb") as f:
  171. try:
  172. numpy_pickle.dump(to_write, f, compress=self.compress)
  173. except PicklingError as e:
  174. # TODO(1.5) turn into error
  175. warnings.warn(
  176. "Unable to cache to disk: failed to pickle "
  177. "output. In version 1.5 this will raise an "
  178. f"exception. Exception: {e}.",
  179. FutureWarning,
  180. )
  181. self._concurrency_safe_write(item, filename, write_func)
  182. except Exception as e: # noqa: E722
  183. warnings.warn(
  184. "Unable to cache to disk. Possibly a race condition in the "
  185. f"creation of the directory. Exception: {e}.",
  186. CacheWarning,
  187. )
  188. def clear_item(self, call_id):
  189. """Clear the item at the id, given as a list of str."""
  190. item_path = os.path.join(self.location, *call_id)
  191. if self._item_exists(item_path):
  192. self.clear_location(item_path)
  193. def contains_item(self, call_id):
  194. """Check if there is an item at the id, given as a list of str."""
  195. item_path = os.path.join(self.location, *call_id)
  196. filename = os.path.join(item_path, "output.pkl")
  197. return self._item_exists(filename)
  198. def get_item_info(self, call_id):
  199. """Return information about item."""
  200. return {"location": os.path.join(self.location, *call_id)}
  201. def get_metadata(self, call_id):
  202. """Return actual metadata of an item."""
  203. try:
  204. item_path = os.path.join(self.location, *call_id)
  205. filename = os.path.join(item_path, "metadata.json")
  206. with self._open_item(filename, "rb") as f:
  207. return json.loads(f.read().decode("utf-8"))
  208. except: # noqa: E722
  209. return {}
  210. def store_metadata(self, call_id, metadata):
  211. """Store metadata of a computation."""
  212. try:
  213. item_path = os.path.join(self.location, *call_id)
  214. self.create_location(item_path)
  215. filename = os.path.join(item_path, "metadata.json")
  216. def write_func(to_write, dest_filename):
  217. with self._open_item(dest_filename, "wb") as f:
  218. f.write(json.dumps(to_write).encode("utf-8"))
  219. self._concurrency_safe_write(metadata, filename, write_func)
  220. except: # noqa: E722
  221. pass
  222. def contains_path(self, call_id):
  223. """Check cached function is available in store."""
  224. func_path = os.path.join(self.location, *call_id)
  225. return self.object_exists(func_path)
  226. def clear_path(self, call_id):
  227. """Clear all items with a common path in the store."""
  228. func_path = os.path.join(self.location, *call_id)
  229. if self._item_exists(func_path):
  230. self.clear_location(func_path)
  231. def store_cached_func_code(self, call_id, func_code=None):
  232. """Store the code of the cached function."""
  233. func_path = os.path.join(self.location, *call_id)
  234. if not self._item_exists(func_path):
  235. self.create_location(func_path)
  236. if func_code is not None:
  237. filename = os.path.join(func_path, "func_code.py")
  238. with self._open_item(filename, "wb") as f:
  239. f.write(func_code.encode("utf-8"))
  240. def get_cached_func_code(self, call_id):
  241. """Store the code of the cached function."""
  242. filename = os.path.join(self.location, *call_id, "func_code.py")
  243. try:
  244. with self._open_item(filename, "rb") as f:
  245. return f.read().decode("utf-8")
  246. except: # noqa: E722
  247. raise
  248. def get_cached_func_info(self, call_id):
  249. """Return information related to the cached function if it exists."""
  250. return {"location": os.path.join(self.location, *call_id)}
  251. def clear(self):
  252. """Clear the whole store content."""
  253. self.clear_location(self.location)
  254. def enforce_store_limits(self, bytes_limit, items_limit=None, age_limit=None):
  255. """
  256. Remove the store's oldest files to enforce item, byte, and age limits.
  257. """
  258. items_to_delete = self._get_items_to_delete(bytes_limit, items_limit, age_limit)
  259. for item in items_to_delete:
  260. if self.verbose > 10:
  261. print("Deleting item {0}".format(item))
  262. try:
  263. self.clear_location(item.path)
  264. except OSError:
  265. # Even with ignore_errors=True shutil.rmtree can raise OSError
  266. # with:
  267. # [Errno 116] Stale file handle if another process has deleted
  268. # the folder already.
  269. pass
  270. def _get_items_to_delete(self, bytes_limit, items_limit=None, age_limit=None):
  271. """
  272. Get items to delete to keep the store under size, file, & age limits.
  273. """
  274. if isinstance(bytes_limit, str):
  275. bytes_limit = memstr_to_bytes(bytes_limit)
  276. items = self.get_items()
  277. if not items:
  278. return []
  279. size = sum(item.size for item in items)
  280. if bytes_limit is not None:
  281. to_delete_size = size - bytes_limit
  282. else:
  283. to_delete_size = 0
  284. if items_limit is not None:
  285. to_delete_items = len(items) - items_limit
  286. else:
  287. to_delete_items = 0
  288. if age_limit is not None:
  289. older_item = min(item.last_access for item in items)
  290. if age_limit.total_seconds() < 0:
  291. raise ValueError("age_limit has to be a positive timedelta")
  292. deadline = datetime.datetime.now() - age_limit
  293. else:
  294. deadline = None
  295. if (
  296. to_delete_size <= 0
  297. and to_delete_items <= 0
  298. and (deadline is None or older_item > deadline)
  299. ):
  300. return []
  301. # We want to delete first the cache items that were accessed a
  302. # long time ago
  303. items.sort(key=operator.attrgetter("last_access"))
  304. items_to_delete = []
  305. size_so_far = 0
  306. items_so_far = 0
  307. for item in items:
  308. if (
  309. (size_so_far >= to_delete_size)
  310. and items_so_far >= to_delete_items
  311. and (deadline is None or deadline < item.last_access)
  312. ):
  313. break
  314. items_to_delete.append(item)
  315. size_so_far += item.size
  316. items_so_far += 1
  317. return items_to_delete
  318. def _concurrency_safe_write(self, to_write, filename, write_func):
  319. """Writes an object into a file in a concurrency-safe way."""
  320. temporary_filename = concurrency_safe_write(to_write, filename, write_func)
  321. self._move_item(temporary_filename, filename)
  322. def __repr__(self):
  323. """Printable representation of the store location."""
  324. return '{class_name}(location="{location}")'.format(
  325. class_name=self.__class__.__name__, location=self.location
  326. )
  327. class FileSystemStoreBackend(StoreBackendBase, StoreBackendMixin):
  328. """A StoreBackend used with local or network file systems."""
  329. _open_item = staticmethod(open)
  330. _item_exists = staticmethod(os.path.exists)
  331. _move_item = staticmethod(concurrency_safe_rename)
  332. def clear_location(self, location):
  333. """Delete location on store."""
  334. if location == self.location:
  335. rm_subdirs(location)
  336. else:
  337. shutil.rmtree(location, ignore_errors=True)
  338. def create_location(self, location):
  339. """Create object location on store"""
  340. mkdirp(location)
  341. def get_items(self):
  342. """Returns the whole list of items available in the store."""
  343. items = []
  344. for dirpath, _, filenames in os.walk(self.location):
  345. is_cache_hash_dir = re.match("[a-f0-9]{32}", os.path.basename(dirpath))
  346. if is_cache_hash_dir:
  347. output_filename = os.path.join(dirpath, "output.pkl")
  348. try:
  349. last_access = os.path.getatime(output_filename)
  350. except OSError:
  351. try:
  352. last_access = os.path.getatime(dirpath)
  353. except OSError:
  354. # The directory has already been deleted
  355. continue
  356. last_access = datetime.datetime.fromtimestamp(last_access)
  357. try:
  358. full_filenames = [os.path.join(dirpath, fn) for fn in filenames]
  359. dirsize = sum(os.path.getsize(fn) for fn in full_filenames)
  360. except OSError:
  361. # Either output_filename or one of the files in
  362. # dirpath does not exist any more. We assume this
  363. # directory is being cleaned by another process already
  364. continue
  365. items.append(CacheItemInfo(dirpath, dirsize, last_access))
  366. return items
  367. def configure(self, location, verbose=1, backend_options=None):
  368. """Configure the store backend.
  369. For this backend, valid store options are 'compress' and 'mmap_mode'
  370. """
  371. if backend_options is None:
  372. backend_options = {}
  373. # setup location directory
  374. self.location = location
  375. if not os.path.exists(self.location):
  376. mkdirp(self.location)
  377. # Automatically add `.gitignore` file to the cache folder.
  378. # XXX: the condition is necessary because in `Memory.__init__`, the user
  379. # passed `location` param is modified to be either `{location}` or
  380. # `{location}/joblib` depending on input type (`pathlib.Path` vs `str`).
  381. # The proper resolution of this inconsistency is tracked in:
  382. # https://github.com/joblib/joblib/issues/1684
  383. cache_directory = (
  384. os.path.dirname(location)
  385. if os.path.dirname(location) and os.path.basename(location) == "joblib"
  386. else location
  387. )
  388. gitignore = os.path.join(cache_directory, ".gitignore")
  389. if not os.path.exists(gitignore):
  390. try:
  391. with open(gitignore, "w") as file:
  392. file.write("# Created by joblib automatically.\n")
  393. file.write("*\n")
  394. except OSError as e:
  395. warnings.warn(f"Unable to write {gitignore}. Exception: {e}.")
  396. # item can be stored compressed for faster I/O
  397. self.compress = backend_options.get("compress", False)
  398. # FileSystemStoreBackend can be used with mmap_mode options under
  399. # certain conditions.
  400. mmap_mode = backend_options.get("mmap_mode")
  401. if self.compress and mmap_mode is not None:
  402. warnings.warn(
  403. "Compressed items cannot be memmapped in a "
  404. "filesystem store. Option will be ignored.",
  405. stacklevel=2,
  406. )
  407. self.mmap_mode = mmap_mode
  408. self.verbose = verbose