__main__.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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 radicale import VERSION, config, log, server, storage
  29. from radicale.log import logger
  30. def run():
  31. """Run Radicale as a standalone server."""
  32. exit_signal_numbers = [signal.SIGTERM, signal.SIGINT]
  33. if os.name == "posix":
  34. exit_signal_numbers.append(signal.SIGHUP)
  35. exit_signal_numbers.append(signal.SIGQUIT)
  36. elif os.name == "nt":
  37. exit_signal_numbers.append(signal.SIGBREAK)
  38. # Raise SystemExit when signal arrives to run cleanup code
  39. # (like destructors, try-finish etc.), otherwise the process exits
  40. # without running any of them
  41. def exit_signal_handler(signal_number, stack_frame):
  42. sys.exit(1)
  43. for signal_number in exit_signal_numbers:
  44. signal.signal(signal_number, exit_signal_handler)
  45. log.setup()
  46. # Get command-line arguments
  47. parser = argparse.ArgumentParser(
  48. prog="radicale", usage="%(prog)s [OPTIONS]", allow_abbrev=False)
  49. parser.add_argument("--version", action="version", version=VERSION)
  50. parser.add_argument("--verify-storage", action="store_true",
  51. help="check the storage for errors and exit")
  52. parser.add_argument(
  53. "-C", "--config", help="use specific configuration files", nargs="*")
  54. parser.add_argument("-D", "--debug", action="store_true",
  55. help="print debug information")
  56. groups = {}
  57. for section, values in config.DEFAULT_CONFIG_SCHEMA.items():
  58. if section.startswith("_"):
  59. continue
  60. group = parser.add_argument_group(section)
  61. groups[group] = []
  62. for option, data in values.items():
  63. if option.startswith("_"):
  64. continue
  65. kwargs = data.copy()
  66. long_name = "--%s-%s" % (section, option.replace("_", "-"))
  67. args = list(kwargs.pop("aliases", ()))
  68. args.append(long_name)
  69. kwargs["dest"] = "%s_%s" % (section, option)
  70. groups[group].append(kwargs["dest"])
  71. del kwargs["value"]
  72. with contextlib.suppress(KeyError):
  73. del kwargs["internal"]
  74. if kwargs["type"] == bool:
  75. del kwargs["type"]
  76. kwargs["action"] = "store_const"
  77. kwargs["const"] = "True"
  78. opposite_args = kwargs.pop("opposite", [])
  79. opposite_args.append("--no%s" % long_name[1:])
  80. group.add_argument(*args, **kwargs)
  81. kwargs["const"] = "False"
  82. kwargs["help"] = "do not %s (opposite of %s)" % (
  83. kwargs["help"], long_name)
  84. group.add_argument(*opposite_args, **kwargs)
  85. else:
  86. del kwargs["type"]
  87. group.add_argument(*args, **kwargs)
  88. args = parser.parse_args()
  89. # Preliminary configure logging
  90. if args.debug:
  91. args.logging_level = "debug"
  92. with contextlib.suppress(ValueError):
  93. log.set_level(config.DEFAULT_CONFIG_SCHEMA["logging"]["level"]["type"](
  94. args.logging_level))
  95. # Update Radicale configuration according to arguments
  96. arguments_config = {}
  97. for group, actions in groups.items():
  98. section = group.title
  99. section_config = {}
  100. for action in actions:
  101. value = getattr(args, action)
  102. if value is not None:
  103. section_config[action.split('_', 1)[1]] = value
  104. if section_config:
  105. arguments_config[section] = section_config
  106. try:
  107. configuration = config.load(config.parse_compound_paths(
  108. config.DEFAULT_CONFIG_PATH,
  109. os.environ.get("RADICALE_CONFIG"),
  110. os.pathsep.join(args.config) if args.config else None))
  111. if arguments_config:
  112. configuration.update(arguments_config, "arguments")
  113. except Exception as e:
  114. logger.fatal("Invalid configuration: %s", e, exc_info=True)
  115. sys.exit(1)
  116. # Configure logging
  117. log.set_level(configuration.get("logging", "level"))
  118. # Log configuration after logger is configured
  119. for source, miss in configuration.sources():
  120. logger.info("%s %s", "Skipped missing" if miss else "Loaded", source)
  121. if args.verify_storage:
  122. logger.info("Verifying storage")
  123. try:
  124. storage_ = storage.load(configuration)
  125. with storage_.acquire_lock("r"):
  126. if not storage_.verify():
  127. logger.fatal("Storage verifcation failed")
  128. sys.exit(1)
  129. except Exception as e:
  130. logger.fatal("An exception occurred during storage verification: "
  131. "%s", e, exc_info=True)
  132. sys.exit(1)
  133. return
  134. # Create a socket pair to notify the server of program shutdown
  135. shutdown_socket, shutdown_socket_out = socket.socketpair()
  136. # Shutdown server when signal arrives
  137. def shutdown_signal_handler(signal_number, stack_frame):
  138. shutdown_socket.close()
  139. for signal_number in exit_signal_numbers:
  140. signal.signal(signal_number, shutdown_signal_handler)
  141. try:
  142. server.serve(configuration, shutdown_socket_out)
  143. except Exception as e:
  144. logger.fatal("An exception occurred during server startup: %s", e,
  145. exc_info=True)
  146. sys.exit(1)
  147. if __name__ == "__main__":
  148. run()