__main__.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. # This file is part of Radicale - CalDAV and CardDAV server
  2. # Copyright © 2011-2017 Guillaume Ayoub
  3. # Copyright © 2017-2022 Unrud <unrud@outlook.com>
  4. # Copyright © 2024-2024 Peter Bieringer <pb@bieringer.de>
  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. Radicale executable module.
  20. This module can be executed from a command line with ``$python -m radicale``.
  21. Uses the built-in WSGI server.
  22. """
  23. import argparse
  24. import contextlib
  25. import os
  26. import signal
  27. import socket
  28. import sys
  29. from types import FrameType
  30. from typing import List, Optional, cast
  31. from radicale import VERSION, config, log, server, storage, types
  32. from radicale.log import logger
  33. def run() -> None:
  34. """Run Radicale as a standalone server."""
  35. exit_signal_numbers = [signal.SIGTERM, signal.SIGINT]
  36. if sys.platform == "win32":
  37. exit_signal_numbers.append(signal.SIGBREAK)
  38. else:
  39. exit_signal_numbers.append(signal.SIGHUP)
  40. exit_signal_numbers.append(signal.SIGQUIT)
  41. # Raise SystemExit when signal arrives to run cleanup code
  42. # (like destructors, try-finish etc.), otherwise the process exits
  43. # without running any of them
  44. def exit_signal_handler(signal_number: int,
  45. stack_frame: Optional[FrameType]) -> None:
  46. sys.exit(1)
  47. for signal_number in exit_signal_numbers:
  48. signal.signal(signal_number, exit_signal_handler)
  49. log.setup()
  50. # Get command-line arguments
  51. # Configuration options are stored in dest with format "c:SECTION:OPTION"
  52. parser = argparse.ArgumentParser(
  53. prog="radicale", usage="%(prog)s [OPTIONS]", allow_abbrev=False)
  54. parser.add_argument("--version", action="version", version=VERSION)
  55. parser.add_argument("--verify-storage", action="store_true",
  56. help="check the storage for errors and exit")
  57. parser.add_argument("-C", "--config",
  58. help="use specific configuration files", nargs="*")
  59. parser.add_argument("-D", "--debug", action="store_const", const="debug",
  60. dest="c:logging:level", default=argparse.SUPPRESS,
  61. help="print debug information")
  62. for section, section_data in config.DEFAULT_CONFIG_SCHEMA.items():
  63. if section.startswith("_"):
  64. continue
  65. assert ":" not in section # check field separator
  66. assert "-" not in section and "_" not in section # not implemented
  67. group_description = None
  68. if section_data.get("_allow_extra"):
  69. group_description = "additional options allowed"
  70. if section == "headers":
  71. group_description += " (e.g. --headers-Pragma=no-cache)"
  72. elif "type" in section_data:
  73. group_description = "backend specific options omitted"
  74. group = parser.add_argument_group(section, group_description)
  75. for option, data in section_data.items():
  76. if option.startswith("_"):
  77. continue
  78. kwargs = data.copy()
  79. long_name = "--%s-%s" % (section, option.replace("_", "-"))
  80. args: List[str] = list(kwargs.pop("aliases", ()))
  81. args.append(long_name)
  82. kwargs["dest"] = "c:%s:%s" % (section, option)
  83. kwargs["metavar"] = "VALUE"
  84. kwargs["default"] = argparse.SUPPRESS
  85. del kwargs["value"]
  86. with contextlib.suppress(KeyError):
  87. del kwargs["internal"]
  88. if kwargs["type"] == bool:
  89. del kwargs["type"]
  90. opposite_args = list(kwargs.pop("opposite_aliases", ()))
  91. opposite_args.append("--no%s" % long_name[1:])
  92. group.add_argument(*args, nargs="?", const="True", **kwargs)
  93. # Opposite argument
  94. kwargs["help"] = "do not %s (opposite of %s)" % (
  95. kwargs["help"], long_name)
  96. group.add_argument(*opposite_args, action="store_const",
  97. const="False", **kwargs)
  98. else:
  99. del kwargs["type"]
  100. group.add_argument(*args, **kwargs)
  101. args_ns, remaining_args = parser.parse_known_args()
  102. unrecognized_args = []
  103. while remaining_args:
  104. arg = remaining_args.pop(0)
  105. for section, data in config.DEFAULT_CONFIG_SCHEMA.items():
  106. if "type" not in data and not data.get("_allow_extra"):
  107. continue
  108. prefix = "--%s-" % section
  109. if arg.startswith(prefix):
  110. arg = arg[len(prefix):]
  111. break
  112. else:
  113. unrecognized_args.append(arg)
  114. continue
  115. value = ""
  116. if "=" in arg:
  117. arg, value = arg.split("=", maxsplit=1)
  118. elif remaining_args and not remaining_args[0].startswith("-"):
  119. value = remaining_args.pop(0)
  120. option = arg
  121. if not data.get("_allow_extra"): # preserve dash in HTTP header names
  122. option = option.replace("-", "_")
  123. vars(args_ns)["c:%s:%s" % (section, option)] = value
  124. if unrecognized_args:
  125. parser.error("unrecognized arguments: %s" %
  126. " ".join(unrecognized_args))
  127. # Preliminary configure logging
  128. with contextlib.suppress(ValueError):
  129. log.set_level(config.DEFAULT_CONFIG_SCHEMA["logging"]["level"]["type"](
  130. vars(args_ns).get("c:logging:level", "")), True)
  131. # Update Radicale configuration according to arguments
  132. arguments_config: types.MUTABLE_CONFIG = {}
  133. for key, value in vars(args_ns).items():
  134. if key.startswith("c:"):
  135. _, section, option = key.split(":", maxsplit=2)
  136. arguments_config[section] = arguments_config.get(section, {})
  137. arguments_config[section][option] = value
  138. try:
  139. configuration = config.load(config.parse_compound_paths(
  140. config.DEFAULT_CONFIG_PATH,
  141. os.environ.get("RADICALE_CONFIG"),
  142. os.pathsep.join(args_ns.config) if args_ns.config is not None
  143. else None))
  144. if arguments_config:
  145. configuration.update(arguments_config, "command line arguments")
  146. except Exception as e:
  147. logger.critical("Invalid configuration: %s", e, exc_info=True)
  148. sys.exit(1)
  149. # Configure logging
  150. log.set_level(cast(str, configuration.get("logging", "level")), configuration.get("logging", "backtrace_on_debug"))
  151. # Log configuration after logger is configured
  152. default_config_active = True
  153. for source, miss in configuration.sources():
  154. logger.info("%s %s", "Skipped missing/unreadable" if miss else "Loaded", source)
  155. if not miss and source != "default config":
  156. default_config_active = False
  157. if default_config_active:
  158. logger.warning("%s", "No config file found/readable - only default config is active")
  159. if args_ns.verify_storage:
  160. logger.info("Verifying storage")
  161. try:
  162. storage_ = storage.load(configuration)
  163. with storage_.acquire_lock("r"):
  164. if not storage_.verify():
  165. logger.critical("Storage verification failed")
  166. sys.exit(1)
  167. except Exception as e:
  168. logger.critical("An exception occurred during storage "
  169. "verification: %s", e, exc_info=True)
  170. sys.exit(1)
  171. return
  172. # Create a socket pair to notify the server of program shutdown
  173. shutdown_socket, shutdown_socket_out = socket.socketpair()
  174. # Shutdown server when signal arrives
  175. def shutdown_signal_handler(signal_number: int,
  176. stack_frame: Optional[FrameType]) -> None:
  177. shutdown_socket.close()
  178. for signal_number in exit_signal_numbers:
  179. signal.signal(signal_number, shutdown_signal_handler)
  180. try:
  181. server.serve(configuration, shutdown_socket_out)
  182. except Exception as e:
  183. logger.critical("An exception occurred during server startup: %s", e,
  184. exc_info=False)
  185. sys.exit(1)
  186. if __name__ == "__main__":
  187. run()