cache.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2014 Jean-Marc Martins
  3. # Copyright © 2012-2017 Guillaume Ayoub
  4. # Copyright © 2017-2018 Unrud <unrud@outlook.com>
  5. #
  6. # This library is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  18. import os
  19. import pickle
  20. import time
  21. from hashlib import sha256
  22. from radicale import pathutils, storage
  23. from radicale.log import logger
  24. class CollectionCacheMixin:
  25. def _clean_cache(self, folder, names, max_age=None):
  26. """Delete all ``names`` in ``folder`` that are older than ``max_age``.
  27. """
  28. age_limit = time.time() - max_age if max_age is not None else None
  29. modified = False
  30. for name in names:
  31. if not pathutils.is_safe_filesystem_path_component(name):
  32. continue
  33. if age_limit is not None:
  34. try:
  35. # Race: Another process might have deleted the file.
  36. mtime = os.path.getmtime(os.path.join(folder, name))
  37. except FileNotFoundError:
  38. continue
  39. if mtime > age_limit:
  40. continue
  41. logger.debug("Found expired item in cache: %r", name)
  42. # Race: Another process might have deleted or locked the
  43. # file.
  44. try:
  45. os.remove(os.path.join(folder, name))
  46. except (FileNotFoundError, PermissionError):
  47. continue
  48. modified = True
  49. if modified:
  50. self._storage._sync_directory(folder)
  51. @staticmethod
  52. def _item_cache_hash(raw_text):
  53. _hash = sha256()
  54. _hash.update(storage.CACHE_VERSION)
  55. _hash.update(raw_text)
  56. return _hash.hexdigest()
  57. def _item_cache_content(self, item, cache_hash=None):
  58. text = item.serialize()
  59. if cache_hash is None:
  60. cache_hash = self._item_cache_hash(text.encode(self._encoding))
  61. return (cache_hash, item.uid, item.etag, text, item.name,
  62. item.component_name, *item.time_range)
  63. def _store_item_cache(self, href, item, cache_hash=None):
  64. cache_folder = os.path.join(self._filesystem_path, ".Radicale.cache",
  65. "item")
  66. content = self._item_cache_content(item, cache_hash)
  67. self._storage._makedirs_synced(cache_folder)
  68. try:
  69. # Race: Other processes might have created and locked the
  70. # file.
  71. with self._atomic_write(os.path.join(cache_folder, href),
  72. "wb") as f:
  73. pickle.dump(content, f)
  74. except PermissionError:
  75. pass
  76. return content
  77. def _load_item_cache(self, href, input_hash):
  78. cache_folder = os.path.join(self._filesystem_path, ".Radicale.cache",
  79. "item")
  80. cache_hash = uid = etag = text = name = tag = start = end = None
  81. try:
  82. with open(os.path.join(cache_folder, href), "rb") as f:
  83. cache_hash, *content = pickle.load(f)
  84. if cache_hash == input_hash:
  85. uid, etag, text, name, tag, start, end = content
  86. except FileNotFoundError:
  87. pass
  88. except (pickle.UnpicklingError, ValueError) as e:
  89. logger.warning("Failed to load item cache entry %r in %r: %s",
  90. href, self.path, e, exc_info=True)
  91. return cache_hash, uid, etag, text, name, tag, start, end
  92. def _clean_item_cache(self):
  93. cache_folder = os.path.join(self._filesystem_path, ".Radicale.cache",
  94. "item")
  95. self._clean_cache(cache_folder, (
  96. e.name for e in os.scandir(cache_folder) if not
  97. os.path.isfile(os.path.join(self._filesystem_path, e.name))))