__main__.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. # -*- coding: utf-8 -*-
  2. #
  3. # This file is part of Radicale Server - Calendar Server
  4. # Copyright © 2011-2013 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 select
  28. import signal
  29. import socket
  30. from wsgiref.simple_server import make_server
  31. from . import (
  32. Application, config, HTTPServer, HTTPSServer, log, RequestHandler, VERSION)
  33. # This is a script, many branches and variables
  34. # pylint: disable=R0912,R0914
  35. def run():
  36. """Run Radicale as a standalone server."""
  37. # Get command-line options
  38. parser = optparse.OptionParser(version=VERSION)
  39. parser.add_option(
  40. "-d", "--daemon", action="store_true",
  41. help="launch as daemon")
  42. parser.add_option(
  43. "-p", "--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. help="set server hostnames and ports")
  51. parser.add_option(
  52. "-s", "--ssl", action="store_true",
  53. help="use SSL connection")
  54. parser.add_option(
  55. "-S", "--no-ssl", action="store_false", dest="ssl",
  56. help="do not use SSL connection (opposite of --ssl)")
  57. parser.add_option(
  58. "-k", "--key",
  59. help="set private key file")
  60. parser.add_option(
  61. "-c", "--certificate",
  62. help="set certificate file")
  63. parser.add_option(
  64. "-D", "--debug", action="store_true",
  65. help="print debug information")
  66. parser.add_option(
  67. "-C", "--config",
  68. help="use a specific configuration file")
  69. options = parser.parse_args()[0]
  70. # Read in the configuration specified by the command line (if specified)
  71. configuration_found = (
  72. config.read(options.config) if options.config else True)
  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. if value is not None:
  80. config.set(section, key, str(value))
  81. # Start logging
  82. log.start()
  83. # Log a warning if the configuration file of the command line is not found
  84. if not configuration_found:
  85. log.LOGGER.warning(
  86. "Configuration file '%s' not found" % options.config)
  87. # Fork if Radicale is launched as daemon
  88. if config.getboolean("server", "daemon"):
  89. # Check and create PID file in a race-free manner
  90. if config.get("server", "pid"):
  91. try:
  92. pid_fd = os.open(
  93. config.get("server", "pid"),
  94. os.O_CREAT | os.O_EXCL | os.O_WRONLY)
  95. except:
  96. raise OSError(
  97. "PID file exists: %s" % config.get("server", "pid"))
  98. pid = os.fork()
  99. if pid:
  100. sys.exit()
  101. # Write PID
  102. if config.get("server", "pid"):
  103. with os.fdopen(pid_fd, "w") as pid_file:
  104. pid_file.write(str(os.getpid()))
  105. # Decouple environment
  106. os.umask(0)
  107. os.chdir("/")
  108. os.setsid()
  109. with open(os.devnull, "r") as null_in:
  110. os.dup2(null_in.fileno(), sys.stdin.fileno())
  111. with open(os.devnull, "w") as null_out:
  112. os.dup2(null_out.fileno(), sys.stdout.fileno())
  113. os.dup2(null_out.fileno(), sys.stderr.fileno())
  114. # Register exit function
  115. def cleanup():
  116. """Remove the PID files."""
  117. log.LOGGER.debug("Cleaning up")
  118. # Remove PID file
  119. if (config.get("server", "pid") and
  120. config.getboolean("server", "daemon")):
  121. os.unlink(config.get("server", "pid"))
  122. atexit.register(cleanup)
  123. log.LOGGER.info("Starting Radicale")
  124. log.LOGGER.debug(
  125. "Base URL prefix: %s" % config.get("server", "base_prefix"))
  126. # Create collection servers
  127. servers = {}
  128. server_class = (
  129. HTTPSServer if config.getboolean("server", "ssl") else HTTPServer)
  130. shutdown_program = [False]
  131. for host in config.get("server", "hosts").split(","):
  132. address, port = host.strip().rsplit(":", 1)
  133. address, port = address.strip("[] "), int(port)
  134. server = make_server(address, port, Application(),
  135. server_class, RequestHandler)
  136. servers[server.socket] = server
  137. log.LOGGER.debug(
  138. "Listening to %s port %s" % (
  139. server.server_name, server.server_port))
  140. if config.getboolean("server", "ssl"):
  141. log.LOGGER.debug("Using SSL")
  142. # Create a socket pair to notify the select syscall of program shutdown
  143. # This is not available in python < 3.5 on Windows
  144. if hasattr(socket, "socketpair"):
  145. shutdown_program_socket_in, shutdown_program_socket_out = \
  146. socket.socketpair()
  147. else:
  148. shutdown_program_socket_in, shutdown_program_socket_out = None, None
  149. # SIGTERM and SIGINT (aka KeyboardInterrupt) should just mark this for
  150. # shutdown
  151. def shutdown(*_):
  152. if shutdown_program[0]:
  153. # Ignore following signals
  154. return
  155. log.LOGGER.info("Stopping Radicale")
  156. shutdown_program[0] = True
  157. if shutdown_program_socket_in:
  158. shutdown_program_socket_in.sendall(b"goodbye")
  159. signal.signal(signal.SIGTERM, shutdown)
  160. signal.signal(signal.SIGINT, shutdown)
  161. # Main loop: wait for requests on any of the servers or program shutdown
  162. sockets = list(servers.keys())
  163. if shutdown_program_socket_out:
  164. # Use socket pair to get notified of program shutdown
  165. sockets.append(shutdown_program_socket_out)
  166. select_timeout = None
  167. else:
  168. # Fallback to busy waiting
  169. select_timeout = 1.0
  170. log.LOGGER.debug("Radicale server ready")
  171. while not shutdown_program[0]:
  172. try:
  173. rlist, _, xlist = select.select(sockets, [], sockets,
  174. select_timeout)
  175. except (KeyboardInterrupt, select.error):
  176. # SIGINT ist handled by signal handler above
  177. rlist, _, xlist = [], [], []
  178. if xlist:
  179. raise RuntimeError("Unhandled socket error")
  180. if rlist:
  181. server = servers.get(rlist[0])
  182. if server:
  183. server.handle_request()
  184. # pylint: enable=R0912,R0914
  185. if __name__ == "__main__":
  186. run()