radicale.py 5.3 KB

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