__init__.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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-2019 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. """
  19. Storage backend that stores data in the file system.
  20. Uses one folder per collection and one file per collection entry.
  21. """
  22. import contextlib
  23. import os
  24. import time
  25. from itertools import chain
  26. from tempfile import NamedTemporaryFile
  27. from radicale import pathutils, storage
  28. from radicale.storage.multifilesystem.cache import CollectionCacheMixin
  29. from radicale.storage.multifilesystem.create_collection import \
  30. CollectionCreateCollectionMixin
  31. from radicale.storage.multifilesystem.delete import CollectionDeleteMixin
  32. from radicale.storage.multifilesystem.discover import CollectionDiscoverMixin
  33. from radicale.storage.multifilesystem.get import CollectionGetMixin
  34. from radicale.storage.multifilesystem.history import CollectionHistoryMixin
  35. from radicale.storage.multifilesystem.lock import CollectionLockMixin
  36. from radicale.storage.multifilesystem.meta import CollectionMetaMixin
  37. from radicale.storage.multifilesystem.move import CollectionMoveMixin
  38. from radicale.storage.multifilesystem.sync import CollectionSyncMixin
  39. from radicale.storage.multifilesystem.upload import CollectionUploadMixin
  40. from radicale.storage.multifilesystem.verify import CollectionVerifyMixin
  41. class Collection(
  42. CollectionCacheMixin, CollectionCreateCollectionMixin,
  43. CollectionDeleteMixin, CollectionDiscoverMixin, CollectionGetMixin,
  44. CollectionHistoryMixin, CollectionLockMixin, CollectionMetaMixin,
  45. CollectionMoveMixin, CollectionSyncMixin, CollectionUploadMixin,
  46. CollectionVerifyMixin, storage.BaseCollection):
  47. """Collection stored in several files per calendar."""
  48. @classmethod
  49. def static_init(cls):
  50. folder = cls.configuration.get("storage", "filesystem_folder")
  51. cls._makedirs_synced(folder)
  52. super().static_init()
  53. def __init__(self, path, filesystem_path=None):
  54. folder = self._get_collection_root_folder()
  55. # Path should already be sanitized
  56. self.path = pathutils.strip_path(path)
  57. self._encoding = self.configuration.get("encoding", "stock")
  58. if filesystem_path is None:
  59. filesystem_path = pathutils.path_to_filesystem(folder, self.path)
  60. self._filesystem_path = filesystem_path
  61. self._etag_cache = None
  62. super().__init__()
  63. @classmethod
  64. def _get_collection_root_folder(cls):
  65. filesystem_folder = cls.configuration.get(
  66. "storage", "filesystem_folder")
  67. return os.path.join(filesystem_folder, "collection-root")
  68. @contextlib.contextmanager
  69. def _atomic_write(self, path, mode="w", newline=None, sync_directory=True,
  70. replace_fn=os.replace):
  71. directory = os.path.dirname(path)
  72. tmp = NamedTemporaryFile(
  73. mode=mode, dir=directory, delete=False, prefix=".Radicale.tmp-",
  74. newline=newline, encoding=None if "b" in mode else self._encoding)
  75. try:
  76. yield tmp
  77. tmp.flush()
  78. try:
  79. self._fsync(tmp.fileno())
  80. except OSError as e:
  81. raise RuntimeError("Fsync'ing file %r failed: %s" %
  82. (path, e)) from e
  83. tmp.close()
  84. replace_fn(tmp.name, path)
  85. except BaseException:
  86. tmp.close()
  87. os.remove(tmp.name)
  88. raise
  89. if sync_directory:
  90. self._sync_directory(directory)
  91. @classmethod
  92. def _fsync(cls, fd):
  93. if cls.configuration.get("internal", "filesystem_fsync"):
  94. pathutils.fsync(fd)
  95. @classmethod
  96. def _sync_directory(cls, path):
  97. """Sync directory to disk.
  98. This only works on POSIX and does nothing on other systems.
  99. """
  100. if not cls.configuration.get("internal", "filesystem_fsync"):
  101. return
  102. if os.name == "posix":
  103. try:
  104. fd = os.open(path, 0)
  105. try:
  106. cls._fsync(fd)
  107. finally:
  108. os.close(fd)
  109. except OSError as e:
  110. raise RuntimeError("Fsync'ing directory %r failed: %s" %
  111. (path, e)) from e
  112. @classmethod
  113. def _makedirs_synced(cls, filesystem_path):
  114. """Recursively create a directory and its parents in a sync'ed way.
  115. This method acts silently when the folder already exists.
  116. """
  117. if os.path.isdir(filesystem_path):
  118. return
  119. parent_filesystem_path = os.path.dirname(filesystem_path)
  120. # Prevent infinite loop
  121. if filesystem_path != parent_filesystem_path:
  122. # Create parent dirs recursively
  123. cls._makedirs_synced(parent_filesystem_path)
  124. # Possible race!
  125. os.makedirs(filesystem_path, exist_ok=True)
  126. cls._sync_directory(parent_filesystem_path)
  127. @property
  128. def last_modified(self):
  129. relevant_files = chain(
  130. (self._filesystem_path,),
  131. (self._props_path,) if os.path.exists(self._props_path) else (),
  132. (os.path.join(self._filesystem_path, h) for h in self._list()))
  133. last = max(map(os.path.getmtime, relevant_files))
  134. return time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(last))
  135. @property
  136. def etag(self):
  137. # reuse cached value if the storage is read-only
  138. if self._lock.locked == "w" or self._etag_cache is None:
  139. self._etag_cache = super().etag
  140. return self._etag_cache