radicale.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # This file is part of Radicale Server - Calendar Server
  5. # Copyright © 2008-2011 Guillaume Ayoub
  6. # Copyright © 2008 Nicolas Kandel
  7. # Copyright © 2008 Pascal Halter
  8. #
  9. # This library is free software: you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation, either version 3 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This library is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License
  20. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  21. # This file is just a script, allow [a-z0-9]* variable names
  22. # pylint: disable-msg=C0103
  23. # ``import radicale`` refers to the ``radicale`` module, not ``radicale.py``
  24. # pylint: disable-msg=W0406
  25. """
  26. Radicale CalDAV Server.
  27. Launch the server according to configuration and command-line options.
  28. """
  29. import os
  30. import sys
  31. import optparse
  32. import signal
  33. import threading
  34. from wsgiref.simple_server import make_server
  35. import radicale
  36. # Get command-line options
  37. parser = optparse.OptionParser(version=radicale.VERSION)
  38. parser.add_option(
  39. "-d", "--daemon", action="store_true",
  40. default=radicale.config.getboolean("server", "daemon"),
  41. help="launch as daemon")
  42. parser.add_option(
  43. "-f", "--foreground", action="store_false", dest="daemon",
  44. help="launch in foreground (opposite of --daemon)")
  45. parser.add_option(
  46. "-H", "--hosts",
  47. default=radicale.config.get("server", "hosts"),
  48. help="set server hostnames and ports")
  49. parser.add_option(
  50. "-s", "--ssl", action="store_true",
  51. default=radicale.config.getboolean("server", "ssl"),
  52. help="use SSL connection")
  53. parser.add_option(
  54. "-S", "--no-ssl", action="store_false", dest="ssl",
  55. help="do not use SSL connection (opposite of --ssl)")
  56. parser.add_option(
  57. "-k", "--key",
  58. default=radicale.config.get("server", "key"),
  59. help="set private key file")
  60. parser.add_option(
  61. "-c", "--certificate",
  62. default=radicale.config.get("server", "certificate"),
  63. help="set certificate file")
  64. parser.add_option(
  65. "-D", "--debug", action="store_true",
  66. default=radicale.config.getboolean("logging", "debug"),
  67. help="print debug information")
  68. options = parser.parse_args()[0]
  69. # Update Radicale configuration according to options
  70. for option in parser.option_list:
  71. key = option.dest
  72. if key:
  73. section = "logging" if key == "debug" else "server"
  74. value = getattr(options, key)
  75. radicale.config.set(section, key, str(value))
  76. # Start logging
  77. radicale.log.start()
  78. # Fork if Radicale is launched as daemon
  79. if options.daemon:
  80. if os.fork():
  81. sys.exit()
  82. sys.stdout = sys.stderr = open(os.devnull, "w")
  83. radicale.log.LOGGER.info("Starting Radicale")
  84. # Create calendar servers
  85. servers = []
  86. server_class = radicale.HTTPSServer if options.ssl else radicale.HTTPServer
  87. shutdown_program = threading.Event()
  88. for host in options.hosts.split(','):
  89. address, port = host.strip().rsplit(':', 1)
  90. address, port = address.strip('[] '), int(port)
  91. servers.append(
  92. make_server(address, port, radicale.Application(),
  93. server_class, radicale.RequestHandler))
  94. # SIGTERM and SIGINT (aka KeyboardInterrupt) should just mark this for shutdown
  95. signal.signal(signal.SIGTERM, lambda *_: shutdown_program.set())
  96. signal.signal(signal.SIGINT, lambda *_: shutdown_program.set())
  97. def serve_forever(server):
  98. """Serve a server forever, cleanly shutdown when things go wrong."""
  99. try:
  100. server.serve_forever()
  101. finally:
  102. shutdown_program.set()
  103. # Start the servers in a different loop to avoid possible race-conditions, when
  104. # a server exists but another server is added to the list at the same time
  105. for server in servers:
  106. radicale.log.LOGGER.debug(
  107. "Listening to %s port %s" % (server.server_name, server.server_port))
  108. if options.ssl:
  109. radicale.log.LOGGER.debug("Using SSL")
  110. threading.Thread(target=serve_forever, args=(server,)).start()
  111. radicale.log.LOGGER.debug("Radicale server ready")
  112. # Main loop: wait until all servers are exited
  113. try:
  114. # We must do the busy-waiting here, as all ``.join()`` calls completly
  115. # block the thread, such that signals are not received
  116. while True:
  117. # The number is irrelevant, it only needs to be greater than 0.05 due
  118. # to python implementing its own busy-waiting logic
  119. shutdown_program.wait(5.0)
  120. if shutdown_program.is_set():
  121. break
  122. finally:
  123. # Ignore signals, so that they cannot interfere
  124. signal.signal(signal.SIGINT, signal.SIG_IGN)
  125. signal.signal(signal.SIGTERM, signal.SIG_IGN)
  126. radicale.log.LOGGER.info("Stopping Radicale")
  127. for server in servers:
  128. radicale.log.LOGGER.debug(
  129. "Closing server listening to %s port %s" % (
  130. server.server_name, server.server_port))
  131. server.shutdown()