__main__.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. from . import (
  31. Application, config, HTTPServer, HTTPSServer, log, RequestHandler, VERSION)
  32. # This is a script, many branches and variables
  33. # pylint: disable=R0912,R0914
  34. def run():
  35. """Run Radicale as a standalone server."""
  36. # Get command-line options
  37. parser = optparse.OptionParser(version=VERSION)
  38. parser.add_option(
  39. "-d", "--daemon", action="store_true",
  40. default=config.getboolean("server", "daemon"),
  41. help="launch as daemon")
  42. parser.add_option(
  43. "-p", "--pid",
  44. default=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=config.get("server", "hosts"),
  52. help="set server hostnames and ports")
  53. parser.add_option(
  54. "-s", "--ssl", action="store_true",
  55. default=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=config.get("server", "key"),
  63. help="set private key file")
  64. parser.add_option(
  65. "-c", "--certificate",
  66. default=config.get("server", "certificate"),
  67. help="set certificate file")
  68. parser.add_option(
  69. "-D", "--debug", action="store_true",
  70. default=config.getboolean("logging", "debug"),
  71. help="print debug information")
  72. parser.add_option(
  73. "-C", "--config",
  74. help="use a specific configuration file")
  75. options = parser.parse_args()[0]
  76. # Read in the configuration specified by the command line (if specified)
  77. if options.config:
  78. config.read(options.config)
  79. # Update Radicale configuration according to options
  80. for option in parser.option_list:
  81. key = option.dest
  82. if key:
  83. section = "logging" if key == "debug" else "server"
  84. value = getattr(options, key)
  85. config.set(section, key, str(value))
  86. # Start logging
  87. log.start()
  88. # Fork if Radicale is launched as daemon
  89. if options.daemon:
  90. if options.pid and os.path.exists(options.pid):
  91. raise OSError("PID file exists: %s" % options.pid)
  92. pid = os.fork()
  93. if pid:
  94. try:
  95. if options.pid:
  96. open(options.pid, "w").write(str(pid))
  97. finally:
  98. sys.exit()
  99. sys.stdout = sys.stderr = open(os.devnull, "w")
  100. # Register exit function
  101. def cleanup():
  102. """Remove the PID files."""
  103. log.LOGGER.debug("Cleaning up")
  104. # Remove PID file
  105. if options.pid and options.daemon:
  106. os.unlink(options.pid)
  107. atexit.register(cleanup)
  108. log.LOGGER.info("Starting Radicale")
  109. # Create collection servers
  110. servers = []
  111. server_class = HTTPSServer if options.ssl else HTTPServer
  112. shutdown_program = threading.Event()
  113. for host in options.hosts.split(","):
  114. address, port = host.strip().rsplit(":", 1)
  115. address, port = address.strip("[] "), int(port)
  116. servers.append(
  117. make_server(address, port, Application(),
  118. server_class, RequestHandler))
  119. # SIGTERM and SIGINT (aka KeyboardInterrupt) should just mark this for
  120. # shutdown
  121. signal.signal(signal.SIGTERM, lambda *_: shutdown_program.set())
  122. signal.signal(signal.SIGINT, lambda *_: shutdown_program.set())
  123. def serve_forever(server):
  124. """Serve a server forever, cleanly shutdown when things go wrong."""
  125. try:
  126. server.serve_forever()
  127. finally:
  128. shutdown_program.set()
  129. # Start the servers in a different loop to avoid possible race-conditions,
  130. # when a server exists but another server is added to the list at the same
  131. # time
  132. for server in servers:
  133. log.LOGGER.debug(
  134. "Listening to %s port %s" % (
  135. server.server_name, server.server_port))
  136. if options.ssl:
  137. log.LOGGER.debug("Using SSL")
  138. threading.Thread(target=serve_forever, args=(server,)).start()
  139. log.LOGGER.debug("Radicale server ready")
  140. # Main loop: wait until all servers are exited
  141. try:
  142. # We must do the busy-waiting here, as all ``.join()`` calls completly
  143. # block the thread, such that signals are not received
  144. while True:
  145. # The number is irrelevant, it only needs to be greater than 0.05
  146. # due to python implementing its own busy-waiting logic
  147. shutdown_program.wait(5.0)
  148. if shutdown_program.is_set():
  149. break
  150. finally:
  151. # Ignore signals, so that they cannot interfere
  152. signal.signal(signal.SIGINT, signal.SIG_IGN)
  153. signal.signal(signal.SIGTERM, signal.SIG_IGN)
  154. log.LOGGER.info("Stopping Radicale")
  155. for server in servers:
  156. log.LOGGER.debug(
  157. "Closing server listening to %s port %s" % (
  158. server.server_name, server.server_port))
  159. server.shutdown()
  160. # pylint: enable=R0912,R0914
  161. if __name__ == "__main__":
  162. run()