base.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. # This file is part of Radicale - CalDAV and CardDAV 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. import os
  19. import sys
  20. from tempfile import TemporaryDirectory
  21. from typing import IO, AnyStr, ClassVar, Iterator, Optional, Type
  22. from radicale import config, pathutils, storage, types
  23. from radicale.storage import multifilesystem # noqa:F401
  24. class CollectionBase(storage.BaseCollection):
  25. _storage: "multifilesystem.Storage"
  26. _path: str
  27. _encoding: str
  28. _filesystem_path: str
  29. def __init__(self, storage_: "multifilesystem.Storage", path: str,
  30. filesystem_path: Optional[str] = None) -> None:
  31. super().__init__()
  32. self._storage = storage_
  33. folder = storage_._get_collection_root_folder()
  34. # Path should already be sanitized
  35. self._path = pathutils.strip_path(path)
  36. self._encoding = storage_.configuration.get("encoding", "stock")
  37. if filesystem_path is None:
  38. filesystem_path = pathutils.path_to_filesystem(folder, self.path)
  39. self._filesystem_path = filesystem_path
  40. # TODO: better fix for "mypy"
  41. @types.contextmanager # type: ignore
  42. def _atomic_write(self, path: str, mode: str = "w",
  43. newline: Optional[str] = None) -> Iterator[IO[AnyStr]]:
  44. # TODO: Overload with Literal when dropping support for Python < 3.8
  45. parent_dir, name = os.path.split(path)
  46. # Do not use mkstemp because it creates with permissions 0o600
  47. with TemporaryDirectory(
  48. prefix=".Radicale.tmp-", dir=parent_dir) as tmp_dir:
  49. with open(os.path.join(tmp_dir, name), mode, newline=newline,
  50. encoding=None if "b" in mode else self._encoding) as tmp:
  51. yield tmp
  52. tmp.flush()
  53. self._storage._fsync(tmp)
  54. os.replace(os.path.join(tmp_dir, name), path)
  55. self._storage._sync_directory(parent_dir)
  56. class StorageBase(storage.BaseStorage):
  57. _collection_class: ClassVar[Type["multifilesystem.Collection"]]
  58. _filesystem_folder: str
  59. _filesystem_fsync: bool
  60. def __init__(self, configuration: config.Configuration) -> None:
  61. super().__init__(configuration)
  62. self._filesystem_folder = configuration.get(
  63. "storage", "filesystem_folder")
  64. self._filesystem_fsync = configuration.get(
  65. "storage", "_filesystem_fsync")
  66. def _get_collection_root_folder(self) -> str:
  67. return os.path.join(self._filesystem_folder, "collection-root")
  68. def _fsync(self, f: IO[AnyStr]) -> None:
  69. if self._filesystem_fsync:
  70. try:
  71. pathutils.fsync(f.fileno())
  72. except OSError as e:
  73. raise RuntimeError("Fsync'ing file %r failed: %s" %
  74. (f.name, e)) from e
  75. def _sync_directory(self, path: str) -> None:
  76. """Sync directory to disk.
  77. This only works on POSIX and does nothing on other systems.
  78. """
  79. if not self._filesystem_fsync:
  80. return
  81. if sys.platform != "win32":
  82. try:
  83. fd = os.open(path, 0)
  84. try:
  85. pathutils.fsync(fd)
  86. finally:
  87. os.close(fd)
  88. except OSError as e:
  89. raise RuntimeError("Fsync'ing directory %r failed: %s" %
  90. (path, e)) from e
  91. def _makedirs_synced(self, filesystem_path: str) -> None:
  92. """Recursively create a directory and its parents in a sync'ed way.
  93. This method acts silently when the folder already exists.
  94. """
  95. if os.path.isdir(filesystem_path):
  96. return
  97. parent_filesystem_path = os.path.dirname(filesystem_path)
  98. # Prevent infinite loop
  99. if filesystem_path != parent_filesystem_path:
  100. # Create parent dirs recursively
  101. self._makedirs_synced(parent_filesystem_path)
  102. # Possible race!
  103. os.makedirs(filesystem_path, exist_ok=True)
  104. self._sync_directory(parent_filesystem_path)