__main__.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2011-2016 Guillaume Ayoub
  3. #
  4. # This library is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This library is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  16. """
  17. Radicale executable module.
  18. This module can be executed from a command line with ``$python -m radicale`` or
  19. from a python programme with ``radicale.__main__.run()``.
  20. """
  21. import atexit
  22. import os
  23. import sys
  24. import optparse
  25. import select
  26. import signal
  27. import socket
  28. from wsgiref.simple_server import make_server
  29. from . import (
  30. Application, config, HTTPServer, HTTPSServer, log, RequestHandler, VERSION)
  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=VERSION)
  37. parser.add_option(
  38. "-d", "--daemon", action="store_true",
  39. help="launch as daemon")
  40. parser.add_option(
  41. "-p", "--pid",
  42. help="set PID filename for daemon mode")
  43. parser.add_option(
  44. "-f", "--foreground", action="store_false", dest="daemon",
  45. help="launch in foreground (opposite of --daemon)")
  46. parser.add_option(
  47. "-H", "--hosts",
  48. help="set server hostnames and ports")
  49. parser.add_option(
  50. "-s", "--ssl", action="store_true",
  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. help="set private key file")
  58. parser.add_option(
  59. "-c", "--certificate",
  60. help="set certificate file")
  61. parser.add_option(
  62. "-D", "--debug", action="store_true",
  63. help="print debug information")
  64. parser.add_option(
  65. "-C", "--config",
  66. help="use a specific configuration file")
  67. options = parser.parse_args()[0]
  68. # Read in the configuration specified by the command line (if specified)
  69. configuration_found = (
  70. config.read(options.config) if options.config else True)
  71. # Update Radicale configuration according to options
  72. for option in parser.option_list:
  73. key = option.dest
  74. if key:
  75. section = "logging" if key == "debug" else "server"
  76. value = getattr(options, key)
  77. if value is not None:
  78. config.set(section, key, str(value))
  79. # Start logging
  80. log.start()
  81. # Log a warning if the configuration file of the command line is not found
  82. if not configuration_found:
  83. log.LOGGER.warning(
  84. "Configuration file '%s' not found" % options.config)
  85. # Fork if Radicale is launched as daemon
  86. if config.getboolean("server", "daemon"):
  87. # Check and create PID file in a race-free manner
  88. if config.get("server", "pid"):
  89. try:
  90. pid_fd = os.open(
  91. config.get("server", "pid"),
  92. os.O_CREAT | os.O_EXCL | os.O_WRONLY)
  93. except:
  94. raise OSError(
  95. "PID file exists: %s" % config.get("server", "pid"))
  96. pid = os.fork()
  97. if pid:
  98. sys.exit()
  99. # Write PID
  100. if config.get("server", "pid"):
  101. with os.fdopen(pid_fd, "w") as pid_file:
  102. pid_file.write(str(os.getpid()))
  103. # Decouple environment
  104. os.umask(0)
  105. os.chdir("/")
  106. os.setsid()
  107. with open(os.devnull, "r") as null_in:
  108. os.dup2(null_in.fileno(), sys.stdin.fileno())
  109. with open(os.devnull, "w") as null_out:
  110. os.dup2(null_out.fileno(), sys.stdout.fileno())
  111. os.dup2(null_out.fileno(), sys.stderr.fileno())
  112. # Register exit function
  113. def cleanup():
  114. """Remove the PID files."""
  115. log.LOGGER.debug("Cleaning up")
  116. # Remove PID file
  117. if (config.get("server", "pid") and
  118. config.getboolean("server", "daemon")):
  119. os.unlink(config.get("server", "pid"))
  120. atexit.register(cleanup)
  121. log.LOGGER.info("Starting Radicale")
  122. log.LOGGER.debug(
  123. "Base URL prefix: %s" % config.get("server", "base_prefix"))
  124. # Create collection servers
  125. servers = {}
  126. server_class = (
  127. HTTPSServer if config.getboolean("server", "ssl") else HTTPServer)
  128. shutdown_program = [False]
  129. for host in config.get("server", "hosts").split(","):
  130. address, port = host.strip().rsplit(":", 1)
  131. address, port = address.strip("[] "), int(port)
  132. server = make_server(address, port, Application(),
  133. server_class, RequestHandler)
  134. servers[server.socket] = server
  135. log.LOGGER.debug(
  136. "Listening to %s port %s" % (
  137. server.server_name, server.server_port))
  138. if config.getboolean("server", "ssl"):
  139. log.LOGGER.debug("Using SSL")
  140. # Create a socket pair to notify the select syscall of program shutdown
  141. # This is not available in python < 3.5 on Windows
  142. if hasattr(socket, "socketpair"):
  143. shutdown_program_socket_in, shutdown_program_socket_out = (
  144. socket.socketpair())
  145. else:
  146. shutdown_program_socket_in, shutdown_program_socket_out = None, None
  147. # SIGTERM and SIGINT (aka KeyboardInterrupt) should just mark this for
  148. # shutdown
  149. def shutdown(*args):
  150. if shutdown_program[0]:
  151. # Ignore following signals
  152. return
  153. log.LOGGER.info("Stopping Radicale")
  154. shutdown_program[0] = True
  155. if shutdown_program_socket_in:
  156. shutdown_program_socket_in.sendall(b"goodbye")
  157. signal.signal(signal.SIGTERM, shutdown)
  158. signal.signal(signal.SIGINT, shutdown)
  159. # Main loop: wait for requests on any of the servers or program shutdown
  160. sockets = list(servers.keys())
  161. if shutdown_program_socket_out:
  162. # Use socket pair to get notified of program shutdown
  163. sockets.append(shutdown_program_socket_out)
  164. select_timeout = None
  165. else:
  166. # Fallback to busy waiting
  167. select_timeout = 1.0
  168. log.LOGGER.debug("Radicale server ready")
  169. while not shutdown_program[0]:
  170. try:
  171. rlist, _, xlist = select.select(
  172. sockets, [], sockets, select_timeout)
  173. except (KeyboardInterrupt, select.error):
  174. # SIGINT is handled by signal handler above
  175. rlist, xlist = [], []
  176. if xlist:
  177. raise RuntimeError("Unhandled socket error")
  178. if rlist:
  179. server = servers.get(rlist[0])
  180. if server:
  181. server.handle_request()
  182. # pylint: enable=R0912,R0914
  183. if __name__ == "__main__":
  184. run()