__main__.py 5.6 KB

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