radicale.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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. import radicale
  35. # Get command-line options
  36. parser = optparse.OptionParser(version=radicale.VERSION)
  37. parser.add_option(
  38. "-d", "--daemon", action="store_true",
  39. default=radicale.config.getboolean("server", "daemon"),
  40. help="launch as daemon")
  41. parser.add_option(
  42. "-f", "--foreground", action="store_false", dest="daemon",
  43. help="launch in foreground (opposite of --daemon)")
  44. parser.add_option(
  45. "-H", "--hosts",
  46. default=radicale.config.get("server", "hosts"),
  47. help="set server hostnames and ports")
  48. parser.add_option(
  49. "-s", "--ssl", action="store_true",
  50. default=radicale.config.getboolean("server", "ssl"),
  51. help="use SSL connection")
  52. parser.add_option(
  53. "-S", "--no-ssl", action="store_false", dest="ssl",
  54. help="do not use SSL connection (opposite of --ssl)")
  55. parser.add_option(
  56. "-k", "--key",
  57. default=radicale.config.get("server", "key"),
  58. help="set private key file")
  59. parser.add_option(
  60. "-c", "--certificate",
  61. default=radicale.config.get("server", "certificate"),
  62. help="set certificate file")
  63. parser.add_option(
  64. "-D", "--debug", action="store_true",
  65. default=radicale.config.getboolean("logging", "debug"),
  66. help="print debug information")
  67. options = parser.parse_args()[0]
  68. # Update Radicale configuration according to options
  69. for option in parser.option_list:
  70. key = option.dest
  71. if key:
  72. section = "logging" if key == "debug" else "server"
  73. value = getattr(options, key)
  74. radicale.config.set(section, key, value)
  75. # Start logging
  76. radicale.log.start(options.debug)
  77. # Fork if Radicale is launched as daemon
  78. if options.daemon:
  79. if os.fork():
  80. sys.exit()
  81. sys.stdout = sys.stderr = open(os.devnull, "w")
  82. radicale.log.LOGGER.info("Starting Radicale")
  83. # Create calendar servers
  84. servers = []
  85. server_class = radicale.HTTPSServer if options.ssl else radicale.HTTPServer
  86. shutdown_program = threading.Event()
  87. for host in options.hosts.split(','):
  88. address, port = host.strip().rsplit(':', 1)
  89. address, port = address.strip('[] '), int(port)
  90. servers.append(server_class((address, port), radicale.CalendarHTTPHandler))
  91. # SIGTERM and SIGINT (aka KeyboardInterrupt) should just mark this for shutdown
  92. signal.signal(signal.SIGTERM, lambda *_: shutdown_program.set())
  93. signal.signal(signal.SIGINT, lambda *_: shutdown_program.set())
  94. def serve_forever(server):
  95. """Serve a server forever, cleanly shutdown when things go wrong."""
  96. try:
  97. server.serve_forever()
  98. finally:
  99. shutdown_program.set()
  100. # Start the servers in a different loop to avoid possible race-conditions, when
  101. # a server exists but another server is added to the list at the same time
  102. for server in servers:
  103. threading.Thread(target=serve_forever, args=(server,)).start()
  104. radicale.log.LOGGER.debug(
  105. "Listening to %s port %s" % (server.server_name, server.server_port))
  106. radicale.log.LOGGER.debug("Radicale server ready")
  107. # Main loop: wait until all servers are exited
  108. try:
  109. # We must do the busy-waiting here, as all ``.join()`` calls completly
  110. # block the thread, such that signals are not received
  111. while True:
  112. # The number is irrelevant, it only needs to be greater than 0.05 due
  113. # to python implementing its own busy-waiting logic
  114. shutdown_program.wait(5.0)
  115. if shutdown_program.is_set():
  116. break
  117. finally:
  118. # Ignore signals, so that they cannot interfere
  119. signal.signal(signal.SIGINT, signal.SIG_IGN)
  120. signal.signal(signal.SIGTERM, signal.SIG_IGN)
  121. radicale.log.LOGGER.info("Stopping Radicale")
  122. for server in servers:
  123. radicale.log.LOGGER.debug(
  124. "Closing server listening to %s port %s" % (
  125. server.server_name, server.server_port))
  126. server.shutdown()