__main__.py 6.0 KB

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