__main__.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. # This file is part of Radicale - CalDAV and CardDAV 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 List, Optional, cast
  30. from radicale import VERSION, config, log, server, storage, types
  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 sys.platform == "win32":
  36. exit_signal_numbers.append(signal.SIGBREAK)
  37. else:
  38. exit_signal_numbers.append(signal.SIGHUP)
  39. exit_signal_numbers.append(signal.SIGQUIT)
  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: int,
  44. stack_frame: Optional[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. # Configuration options are stored in dest with format "c:SECTION:OPTION"
  51. parser = argparse.ArgumentParser(
  52. prog="radicale", usage="%(prog)s [OPTIONS]", allow_abbrev=False)
  53. parser.add_argument("--version", action="version", version=VERSION)
  54. parser.add_argument("--verify-storage", action="store_true",
  55. help="check the storage for errors and exit")
  56. parser.add_argument("-C", "--config",
  57. help="use specific configuration files", nargs="*")
  58. parser.add_argument("-D", "--debug", action="store_const", const="debug",
  59. dest="c:logging:level", default=argparse.SUPPRESS,
  60. help="print debug information")
  61. for section, section_data in config.DEFAULT_CONFIG_SCHEMA.items():
  62. if section.startswith("_"):
  63. continue
  64. assert ":" not in section # check field separator
  65. assert "-" not in section and "_" not in section # not implemented
  66. group_description = None
  67. if section_data.get("_allow_extra"):
  68. group_description = "additional options allowed"
  69. if section == "headers":
  70. group_description += " (e.g. --headers-Pragma=no-cache)"
  71. elif "type" in section_data:
  72. group_description = "backend specific options omitted"
  73. group = parser.add_argument_group(section, group_description)
  74. for option, data in section_data.items():
  75. if option.startswith("_"):
  76. continue
  77. kwargs = data.copy()
  78. long_name = "--%s-%s" % (section, option.replace("_", "-"))
  79. args: List[str] = list(kwargs.pop("aliases", ()))
  80. args.append(long_name)
  81. kwargs["dest"] = "c:%s:%s" % (section, option)
  82. kwargs["metavar"] = "VALUE"
  83. kwargs["default"] = argparse.SUPPRESS
  84. del kwargs["value"]
  85. with contextlib.suppress(KeyError):
  86. del kwargs["internal"]
  87. if kwargs["type"] == bool:
  88. del kwargs["type"]
  89. opposite_args = list(kwargs.pop("opposite_aliases", ()))
  90. opposite_args.append("--no%s" % long_name[1:])
  91. group.add_argument(*args, nargs="?", const="True", **kwargs)
  92. # Opposite argument
  93. kwargs["help"] = "do not %s (opposite of %s)" % (
  94. kwargs["help"], long_name)
  95. group.add_argument(*opposite_args, action="store_const",
  96. const="False", **kwargs)
  97. else:
  98. del kwargs["type"]
  99. group.add_argument(*args, **kwargs)
  100. args_ns, remaining_args = parser.parse_known_args()
  101. unrecognized_args = []
  102. while remaining_args:
  103. arg = remaining_args.pop(0)
  104. for section, data in config.DEFAULT_CONFIG_SCHEMA.items():
  105. if "type" not in data and not data.get("_allow_extra"):
  106. continue
  107. prefix = "--%s-" % section
  108. if arg.startswith(prefix):
  109. arg = arg[len(prefix):]
  110. break
  111. else:
  112. unrecognized_args.append(arg)
  113. continue
  114. value = ""
  115. if "=" in arg:
  116. arg, value = arg.split("=", maxsplit=1)
  117. elif remaining_args and not remaining_args[0].startswith("-"):
  118. value = remaining_args.pop(0)
  119. option = arg
  120. if not data.get("_allow_extra"): # preserve dash in HTTP header names
  121. option = option.replace("-", "_")
  122. vars(args_ns)["c:%s:%s" % (section, option)] = value
  123. if unrecognized_args:
  124. parser.error("unrecognized arguments: %s" %
  125. " ".join(unrecognized_args))
  126. # Preliminary configure logging
  127. with contextlib.suppress(ValueError):
  128. log.set_level(config.DEFAULT_CONFIG_SCHEMA["logging"]["level"]["type"](
  129. vars(args_ns).get("c:logging:level", "")))
  130. # Update Radicale configuration according to arguments
  131. arguments_config: types.MUTABLE_CONFIG = {}
  132. for key, value in vars(args_ns).items():
  133. if key.startswith("c:"):
  134. _, section, option = key.split(":", maxsplit=2)
  135. arguments_config[section] = arguments_config.get(section, {})
  136. arguments_config[section][option] = value
  137. try:
  138. configuration = config.load(config.parse_compound_paths(
  139. config.DEFAULT_CONFIG_PATH,
  140. os.environ.get("RADICALE_CONFIG"),
  141. os.pathsep.join(args_ns.config) if args_ns.config is not None
  142. else None))
  143. if arguments_config:
  144. configuration.update(arguments_config, "command line arguments")
  145. except Exception as e:
  146. logger.critical("Invalid configuration: %s", e, exc_info=True)
  147. sys.exit(1)
  148. # Configure logging
  149. log.set_level(cast(str, configuration.get("logging", "level")))
  150. # Log configuration after logger is configured
  151. for source, miss in configuration.sources():
  152. logger.info("%s %s", "Skipped missing" if miss else "Loaded", source)
  153. if args_ns.verify_storage:
  154. logger.info("Verifying storage")
  155. try:
  156. storage_ = storage.load(configuration)
  157. with storage_.acquire_lock("r"):
  158. if not storage_.verify():
  159. logger.critical("Storage verifcation failed")
  160. sys.exit(1)
  161. except Exception as e:
  162. logger.critical("An exception occurred during storage "
  163. "verification: %s", e, exc_info=True)
  164. sys.exit(1)
  165. return
  166. # Create a socket pair to notify the server of program shutdown
  167. shutdown_socket, shutdown_socket_out = socket.socketpair()
  168. # Shutdown server when signal arrives
  169. def shutdown_signal_handler(signal_number: int,
  170. stack_frame: Optional[FrameType]) -> None:
  171. shutdown_socket.close()
  172. for signal_number in exit_signal_numbers:
  173. signal.signal(signal_number, shutdown_signal_handler)
  174. try:
  175. server.serve(configuration, shutdown_socket_out)
  176. except Exception as e:
  177. logger.critical("An exception occurred during server startup: %s", e,
  178. exc_info=True)
  179. sys.exit(1)
  180. if __name__ == "__main__":
  181. run()