__main__.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2011-2017 Guillaume Ayoub
  3. # Copyright © 2017-2018 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. """
  21. import argparse
  22. import os
  23. import signal
  24. import socket
  25. from radicale import VERSION, config, log, server, storage
  26. from radicale.log import logger
  27. def run():
  28. """Run Radicale as a standalone server."""
  29. log.setup()
  30. # Get command-line arguments
  31. parser = argparse.ArgumentParser(usage="radicale [OPTIONS]")
  32. parser.add_argument("--version", action="version", version=VERSION)
  33. parser.add_argument("--verify-storage", action="store_true",
  34. help="check the storage for errors and exit")
  35. parser.add_argument(
  36. "-C", "--config", help="use a specific configuration file")
  37. parser.add_argument("-D", "--debug", action="store_true",
  38. help="print debug information")
  39. groups = {}
  40. for section, values in config.INITIAL_CONFIG.items():
  41. group = parser.add_argument_group(section)
  42. groups[group] = []
  43. for option, data in values.items():
  44. kwargs = data.copy()
  45. long_name = "--{0}-{1}".format(
  46. section, option.replace("_", "-"))
  47. args = kwargs.pop("aliases", [])
  48. args.append(long_name)
  49. kwargs["dest"] = "{0}_{1}".format(section, option)
  50. groups[group].append(kwargs["dest"])
  51. del kwargs["value"]
  52. if "internal" in kwargs:
  53. del kwargs["internal"]
  54. if kwargs["type"] == bool:
  55. del kwargs["type"]
  56. kwargs["action"] = "store_const"
  57. kwargs["const"] = "True"
  58. opposite_args = kwargs.pop("opposite", [])
  59. opposite_args.append("--no{0}".format(long_name[1:]))
  60. group.add_argument(*args, **kwargs)
  61. kwargs["const"] = "False"
  62. kwargs["help"] = "do not {0} (opposite of {1})".format(
  63. kwargs["help"], long_name)
  64. group.add_argument(*opposite_args, **kwargs)
  65. else:
  66. group.add_argument(*args, **kwargs)
  67. args = parser.parse_args()
  68. # Preliminary configure logging
  69. if args.debug:
  70. args.logging_level = "debug"
  71. if args.logging_level is not None:
  72. log.set_level(args.logging_level)
  73. if args.config is not None:
  74. config_paths = [args.config] if args.config else []
  75. ignore_missing_paths = False
  76. else:
  77. config_paths = ["/etc/radicale/config",
  78. os.path.expanduser("~/.config/radicale/config")]
  79. if "RADICALE_CONFIG" in os.environ:
  80. config_paths.append(os.environ["RADICALE_CONFIG"])
  81. ignore_missing_paths = True
  82. try:
  83. configuration = config.load(config_paths,
  84. ignore_missing_paths=ignore_missing_paths)
  85. except Exception as e:
  86. logger.fatal("Invalid configuration: %s", e, exc_info=True)
  87. exit(1)
  88. # Update Radicale configuration according to arguments
  89. for group, actions in groups.items():
  90. section = group.title
  91. for action in actions:
  92. value = getattr(args, action)
  93. if value is not None:
  94. configuration.set(section, action.split('_', 1)[1], value)
  95. # Configure logging
  96. log.set_level(configuration.get("logging", "level"))
  97. if args.verify_storage:
  98. logger.info("Verifying storage")
  99. try:
  100. Collection = storage.load(configuration)
  101. with Collection.acquire_lock("r"):
  102. if not Collection.verify():
  103. logger.fatal("Storage verifcation failed")
  104. exit(1)
  105. except Exception as e:
  106. logger.fatal("An exception occurred during storage verification: "
  107. "%s", e, exc_info=True)
  108. exit(1)
  109. return
  110. # Create a socket pair to notify the server of program shutdown
  111. shutdown_socket, shutdown_socket_out = socket.socketpair()
  112. # SIGTERM and SIGINT (aka KeyboardInterrupt) shutdown the server
  113. def shutdown(*args):
  114. shutdown_socket.sendall(b" ")
  115. signal.signal(signal.SIGTERM, shutdown)
  116. signal.signal(signal.SIGINT, shutdown)
  117. try:
  118. server.serve(configuration, shutdown_socket_out)
  119. except Exception as e:
  120. logger.fatal("An exception occurred during server startup: %s", e,
  121. exc_info=True)
  122. exit(1)
  123. if __name__ == "__main__":
  124. run()