lock.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 contextlib
  19. import logging
  20. import os
  21. import shlex
  22. import subprocess
  23. from radicale import pathutils
  24. from radicale.log import logger
  25. class CollectionLockMixin:
  26. @classmethod
  27. def static_init(cls):
  28. super().static_init()
  29. folder = os.path.expanduser(cls.configuration.get(
  30. "storage", "filesystem_folder"))
  31. lock_path = os.path.join(folder, ".Radicale.lock")
  32. cls._lock = pathutils.RwLock(lock_path)
  33. def _acquire_cache_lock(self, ns=""):
  34. if self._lock.locked == "w":
  35. return contextlib.ExitStack()
  36. cache_folder = os.path.join(self._filesystem_path, ".Radicale.cache")
  37. self._makedirs_synced(cache_folder)
  38. lock_path = os.path.join(cache_folder,
  39. ".Radicale.lock" + (".%s" % ns if ns else ""))
  40. lock = pathutils.RwLock(lock_path)
  41. return lock.acquire("w")
  42. @classmethod
  43. @contextlib.contextmanager
  44. def acquire_lock(cls, mode, user=None):
  45. with cls._lock.acquire(mode):
  46. yield
  47. # execute hook
  48. hook = cls.configuration.get("storage", "hook")
  49. if mode == "w" and hook:
  50. folder = os.path.expanduser(cls.configuration.get(
  51. "storage", "filesystem_folder"))
  52. logger.debug("Running hook")
  53. debug = logger.isEnabledFor(logging.DEBUG)
  54. p = subprocess.Popen(
  55. hook % {"user": shlex.quote(user or "Anonymous")},
  56. stdin=subprocess.DEVNULL,
  57. stdout=subprocess.PIPE if debug else subprocess.DEVNULL,
  58. stderr=subprocess.PIPE if debug else subprocess.DEVNULL,
  59. shell=True, universal_newlines=True, cwd=folder)
  60. stdout_data, stderr_data = p.communicate()
  61. if stdout_data:
  62. logger.debug("Captured stdout hook:\n%s", stdout_data)
  63. if stderr_data:
  64. logger.debug("Captured stderr hook:\n%s", stderr_data)
  65. if p.returncode != 0:
  66. raise subprocess.CalledProcessError(p.returncode, p.args)