lock.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. import contextlib
  19. import logging
  20. import os
  21. import shlex
  22. import signal
  23. import subprocess
  24. from radicale import pathutils
  25. from radicale.log import logger
  26. class CollectionLockMixin:
  27. def _acquire_cache_lock(self, ns=""):
  28. if self._storage._lock.locked == "w":
  29. return contextlib.ExitStack()
  30. cache_folder = os.path.join(self._filesystem_path, ".Radicale.cache")
  31. self._storage._makedirs_synced(cache_folder)
  32. lock_path = os.path.join(cache_folder,
  33. ".Radicale.lock" + (".%s" % ns if ns else ""))
  34. lock = pathutils.RwLock(lock_path)
  35. return lock.acquire("w")
  36. class StorageLockMixin:
  37. def __init__(self, configuration):
  38. super().__init__(configuration)
  39. folder = self.configuration.get("storage", "filesystem_folder")
  40. lock_path = os.path.join(folder, ".Radicale.lock")
  41. self._lock = pathutils.RwLock(lock_path)
  42. @contextlib.contextmanager
  43. def acquire_lock(self, mode, user=None):
  44. with self._lock.acquire(mode):
  45. yield
  46. # execute hook
  47. hook = self.configuration.get("storage", "hook")
  48. if mode == "w" and hook:
  49. folder = self.configuration.get("storage", "filesystem_folder")
  50. debug = logger.isEnabledFor(logging.DEBUG)
  51. popen_kwargs = dict(
  52. stdin=subprocess.DEVNULL,
  53. stdout=subprocess.PIPE if debug else subprocess.DEVNULL,
  54. stderr=subprocess.PIPE if debug else subprocess.DEVNULL,
  55. shell=True, universal_newlines=True, cwd=folder)
  56. # Use new process group for child to prevent terminals
  57. # from sending SIGINT etc.
  58. if os.name == "posix":
  59. # Process group is also used to identify child processes
  60. popen_kwargs["preexec_fn"] = os.setpgrp
  61. elif os.name == "nt":
  62. popen_kwargs["creationflags"] = (
  63. subprocess.CREATE_NEW_PROCESS_GROUP)
  64. command = hook % {"user": shlex.quote(user or "Anonymous")}
  65. logger.debug("Running hook")
  66. p = subprocess.Popen(command, **popen_kwargs)
  67. try:
  68. stdout_data, stderr_data = p.communicate()
  69. except BaseException: # e.g. KeyboardInterrupt or SystemExit
  70. p.kill()
  71. raise
  72. finally:
  73. if os.name == "posix":
  74. # Try to kill child processes
  75. with contextlib.suppress(OSError):
  76. os.killpg(p.pid, signal.SIGKILL)
  77. if stdout_data:
  78. logger.debug("Captured stdout hook:\n%s", stdout_data)
  79. if stderr_data:
  80. logger.debug("Captured stderr hook:\n%s", stderr_data)
  81. if p.returncode != 0:
  82. raise subprocess.CalledProcessError(p.returncode, p.args)