__main__.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2011-2017 Guillaume Ayoub
  3. # Copyright © 2017-2019 Unrud <unrud@outlook.com>
  4. #
  5. # This library is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This library is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  17. """
  18. Radicale executable module.
  19. This module can be executed from a command line with ``$python -m radicale``.
  20. Uses the built-in WSGI server.
  21. """
  22. import argparse
  23. import contextlib
  24. import os
  25. import signal
  26. import socket
  27. import sys
  28. from types import FrameType
  29. from typing import Dict, List, cast
  30. from radicale import VERSION, config, log, server, storage
  31. from radicale.log import logger
  32. def run() -> None:
  33. """Run Radicale as a standalone server."""
  34. exit_signal_numbers = [signal.SIGTERM, signal.SIGINT]
  35. if os.name == "posix":
  36. exit_signal_numbers.append(signal.SIGHUP)
  37. exit_signal_numbers.append(signal.SIGQUIT)
  38. if sys.platform == "win32":
  39. exit_signal_numbers.append(signal.SIGBREAK)
  40. # Raise SystemExit when signal arrives to run cleanup code
  41. # (like destructors, try-finish etc.), otherwise the process exits
  42. # without running any of them
  43. def exit_signal_handler(signal_number: "signal.Signals",
  44. stack_frame: FrameType) -> None:
  45. sys.exit(1)
  46. for signal_number in exit_signal_numbers:
  47. signal.signal(signal_number, exit_signal_handler)
  48. log.setup()
  49. # Get command-line arguments
  50. parser = argparse.ArgumentParser(
  51. prog="radicale", usage="%(prog)s [OPTIONS]", allow_abbrev=False)
  52. parser.add_argument("--version", action="version", version=VERSION)
  53. parser.add_argument("--verify-storage", action="store_true",
  54. help="check the storage for errors and exit")
  55. parser.add_argument("-C", "--config",
  56. help="use specific configuration files", nargs="*")
  57. parser.add_argument("-D", "--debug", action="store_true",
  58. help="print debug information")
  59. groups: Dict["argparse._ArgumentGroup", List[str]] = {}
  60. for section, values in config.DEFAULT_CONFIG_SCHEMA.items():
  61. if section.startswith("_"):
  62. continue
  63. group = parser.add_argument_group(section)
  64. groups[group] = []
  65. for option, data in values.items():
  66. if option.startswith("_"):
  67. continue
  68. kwargs = data.copy()
  69. long_name = "--%s-%s" % (section, option.replace("_", "-"))
  70. args: List[str] = list(kwargs.pop("aliases", ()))
  71. args.append(long_name)
  72. kwargs["dest"] = "%s_%s" % (section, option)
  73. groups[group].append(kwargs["dest"])
  74. del kwargs["value"]
  75. with contextlib.suppress(KeyError):
  76. del kwargs["internal"]
  77. if kwargs["type"] == bool:
  78. del kwargs["type"]
  79. kwargs["action"] = "store_const"
  80. kwargs["const"] = "True"
  81. opposite_args = kwargs.pop("opposite", [])
  82. opposite_args.append("--no%s" % long_name[1:])
  83. group.add_argument(*args, **kwargs)
  84. kwargs["const"] = "False"
  85. kwargs["help"] = "do not %s (opposite of %s)" % (
  86. kwargs["help"], long_name)
  87. group.add_argument(*opposite_args, **kwargs)
  88. else:
  89. del kwargs["type"]
  90. group.add_argument(*args, **kwargs)
  91. args_ns = parser.parse_args()
  92. # Preliminary configure logging
  93. if args_ns.debug:
  94. args_ns.logging_level = "debug"
  95. with contextlib.suppress(ValueError):
  96. log.set_level(config.DEFAULT_CONFIG_SCHEMA["logging"]["level"]["type"](
  97. args_ns.logging_level))
  98. # Update Radicale configuration according to arguments
  99. arguments_config = {}
  100. for group, actions in groups.items():
  101. section = group.title or ""
  102. section_config = {}
  103. for action in actions:
  104. value = getattr(args_ns, action)
  105. if value is not None:
  106. section_config[action.split('_', 1)[1]] = value
  107. if section_config:
  108. arguments_config[section] = section_config
  109. try:
  110. configuration = config.load(config.parse_compound_paths(
  111. config.DEFAULT_CONFIG_PATH,
  112. os.environ.get("RADICALE_CONFIG"),
  113. os.pathsep.join(args_ns.config) if args_ns.config else None))
  114. if arguments_config:
  115. configuration.update(arguments_config, "command line arguments")
  116. except Exception as e:
  117. logger.critical("Invalid configuration: %s", e, exc_info=True)
  118. sys.exit(1)
  119. # Configure logging
  120. log.set_level(cast(str, configuration.get("logging", "level")))
  121. # Log configuration after logger is configured
  122. for source, miss in configuration.sources():
  123. logger.info("%s %s", "Skipped missing" if miss else "Loaded", source)
  124. if args_ns.verify_storage:
  125. logger.info("Verifying storage")
  126. try:
  127. storage_ = storage.load(configuration)
  128. with storage_.acquire_lock("r"):
  129. if not storage_.verify():
  130. logger.critical("Storage verifcation failed")
  131. sys.exit(1)
  132. except Exception as e:
  133. logger.critical("An exception occurred during storage "
  134. "verification: %s", e, exc_info=True)
  135. sys.exit(1)
  136. return
  137. # Create a socket pair to notify the server of program shutdown
  138. shutdown_socket, shutdown_socket_out = socket.socketpair()
  139. # Shutdown server when signal arrives
  140. def shutdown_signal_handler(signal_number: "signal.Signals",
  141. stack_frame: FrameType) -> None:
  142. shutdown_socket.close()
  143. for signal_number in exit_signal_numbers:
  144. signal.signal(signal_number, shutdown_signal_handler)
  145. try:
  146. server.serve(configuration, shutdown_socket_out)
  147. except Exception as e:
  148. logger.critical("An exception occurred during server startup: %s", e,
  149. exc_info=True)
  150. sys.exit(1)
  151. if __name__ == "__main__":
  152. run()