Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 1 | """Generic socket server classes. |
| 2 | |
| 3 | This module tries to capture the various aspects of defining a server: |
| 4 | |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 5 | For socket-based servers: |
| 6 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 7 | - address family: |
Martin v. Löwis | a43c2f8 | 2001-07-24 20:34:08 +0000 | [diff] [blame] | 8 | - AF_INET{,6}: IP (Internet Protocol) sockets (default) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 9 | - AF_UNIX: Unix domain sockets |
| 10 | - others, e.g. AF_DECNET are conceivable (see <socket.h> |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 11 | - socket type: |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 12 | - SOCK_STREAM (reliable stream, e.g. TCP) |
| 13 | - SOCK_DGRAM (datagrams, e.g. UDP) |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 14 | |
| 15 | For request-based servers (including socket-based): |
| 16 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 17 | - client address verification before further looking at the request |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 18 | (This is actually a hook for any processing that needs to look |
| 19 | at the request before anything else, e.g. logging) |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 20 | - how to handle multiple requests: |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 21 | - synchronous (one request is handled at a time) |
| 22 | - forking (each request is handled by a new process) |
| 23 | - threading (each request is handled by a new thread) |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 24 | |
| 25 | The classes in this module favor the server type that is simplest to |
| 26 | write: a synchronous TCP/IP server. This is bad class design, but |
Jason (Perry) Taylor | d0acdfc | 2019-11-17 05:14:45 +1100 | [diff] [blame] | 27 | saves some typing. (There's also the issue that a deep class hierarchy |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 28 | slows down method lookups.) |
| 29 | |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 30 | There are five classes in an inheritance diagram, four of which represent |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 31 | synchronous servers of four types: |
| 32 | |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 33 | +------------+ |
| 34 | | BaseServer | |
| 35 | +------------+ |
| 36 | | |
| 37 | v |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 38 | +-----------+ +------------------+ |
| 39 | | TCPServer |------->| UnixStreamServer | |
| 40 | +-----------+ +------------------+ |
| 41 | | |
| 42 | v |
| 43 | +-----------+ +--------------------+ |
| 44 | | UDPServer |------->| UnixDatagramServer | |
| 45 | +-----------+ +--------------------+ |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 46 | |
Guido van Rossum | db2b70c | 1997-07-16 16:21:38 +0000 | [diff] [blame] | 47 | Note that UnixDatagramServer derives from UDPServer, not from |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 48 | UnixStreamServer -- the only difference between an IP and a Unix |
| 49 | stream server is the address family, which is simply repeated in both |
Guido van Rossum | db2b70c | 1997-07-16 16:21:38 +0000 | [diff] [blame] | 50 | unix server classes. |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 51 | |
| 52 | Forking and threading versions of each type of server can be created |
Guido van Rossum | ebbffd4 | 2005-04-30 00:20:35 +0000 | [diff] [blame] | 53 | using the ForkingMixIn and ThreadingMixIn mix-in classes. For |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 54 | instance, a threading UDP server class is created as follows: |
| 55 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 56 | class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 57 | |
Guido van Rossum | db2b70c | 1997-07-16 16:21:38 +0000 | [diff] [blame] | 58 | The Mix-in class must come first, since it overrides a method defined |
Martin v. Löwis | f86e8ef | 2002-11-22 08:08:44 +0000 | [diff] [blame] | 59 | in UDPServer! Setting the various member variables also changes |
| 60 | the behavior of the underlying server mechanism. |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 61 | |
| 62 | To implement a service, you must derive a class from |
| 63 | BaseRequestHandler and redefine its handle() method. You can then run |
| 64 | various versions of the service by combining one of the server classes |
| 65 | with your request handler class. |
| 66 | |
| 67 | The request handler class must be different for datagram or stream |
Georg Brandl | ca5feab | 2005-07-18 07:38:44 +0000 | [diff] [blame] | 68 | services. This can be hidden by using the request handler |
| 69 | subclasses StreamRequestHandler or DatagramRequestHandler. |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 70 | |
| 71 | Of course, you still have to use your head! |
| 72 | |
| 73 | For instance, it makes no sense to use a forking server if the service |
| 74 | contains state in memory that can be modified by requests (since the |
| 75 | modifications in the child process would never reach the initial state |
| 76 | kept in the parent process and passed to each child). In this case, |
| 77 | you can use a threading server, but you will probably have to use |
| 78 | locks to avoid two requests that come in nearly simultaneous to apply |
| 79 | conflicting changes to the server state. |
| 80 | |
| 81 | On the other hand, if you are building e.g. an HTTP server, where all |
| 82 | data is stored externally (e.g. in the file system), a synchronous |
| 83 | class will essentially render the service "deaf" while one request is |
| 84 | being handled -- which may be for a very long time if a client is slow |
Ezio Melotti | f78869e | 2011-10-29 10:41:51 +0300 | [diff] [blame] | 85 | to read all the data it has requested. Here a threading or forking |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 86 | server is appropriate. |
| 87 | |
| 88 | In some cases, it may be appropriate to process part of a request |
| 89 | synchronously, but to finish processing in a forked child depending on |
| 90 | the request data. This can be implemented by using a synchronous |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 91 | server and doing an explicit fork in the request handler class |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 92 | handle() method. |
| 93 | |
| 94 | Another approach to handling multiple simultaneous requests in an |
| 95 | environment that supports neither threads nor fork (or where these are |
| 96 | too expensive or inappropriate for the service) is to maintain an |
Charles-François Natali | 1d29cc5 | 2014-03-24 22:25:39 +0000 | [diff] [blame] | 97 | explicit table of partially finished requests and to use a selector to |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 98 | decide which request to work on next (or whether to handle a new |
| 99 | incoming request). This is particularly important for stream services |
| 100 | where each client can potentially be connected for a long time (if |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 101 | threads or subprocesses cannot be used). |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 102 | |
| 103 | Future work: |
| 104 | - Standard classes for Sun RPC (which uses either UDP or TCP) |
| 105 | - Standard mix-in classes to implement various authentication |
| 106 | and encryption schemes |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 107 | |
| 108 | XXX Open problems: |
| 109 | - What to do with out-of-band data? |
| 110 | |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 111 | BaseServer: |
| 112 | - split generic "request" functionality out into BaseServer class. |
| 113 | Copyright (C) 2000 Luke Kenneth Casson Leighton <lkcl@samba.org> |
| 114 | |
| 115 | example: read entries from a SQL database (requires overriding |
| 116 | get_request() to return a table entry from the database). |
| 117 | entry is processed by a RequestHandlerClass. |
| 118 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 119 | """ |
| 120 | |
Guido van Rossum | 10b0418 | 2001-01-19 16:45:46 +0000 | [diff] [blame] | 121 | # Author of the BaseServer patch: Luke Kenneth Casson Leighton |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 122 | |
Guido van Rossum | 7de4d64 | 2001-07-10 11:50:09 +0000 | [diff] [blame] | 123 | __version__ = "0.4" |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 124 | |
| 125 | |
| 126 | import socket |
Charles-François Natali | 1d29cc5 | 2014-03-24 22:25:39 +0000 | [diff] [blame] | 127 | import selectors |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 128 | import os |
Martin Panter | d9108d1 | 2016-02-21 08:49:56 +0000 | [diff] [blame] | 129 | import sys |
Antoine Pitrou | a6a4dc8 | 2017-09-07 18:56:24 +0200 | [diff] [blame] | 130 | import threading |
Martin Panter | 34eeed4 | 2016-06-29 10:12:22 +0000 | [diff] [blame] | 131 | from io import BufferedIOBase |
Victor Stinner | ae58649 | 2014-09-02 23:18:25 +0200 | [diff] [blame] | 132 | from time import monotonic as time |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 133 | |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | cef1f83 | 2016-06-03 00:13:36 +0000 | [diff] [blame] | 134 | __all__ = ["BaseServer", "TCPServer", "UDPServer", |
| 135 | "ThreadingUDPServer", "ThreadingTCPServer", |
Berker Peksag | 3265344 | 2015-02-03 11:55:09 +0200 | [diff] [blame] | 136 | "BaseRequestHandler", "StreamRequestHandler", |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | cef1f83 | 2016-06-03 00:13:36 +0000 | [diff] [blame] | 137 | "DatagramRequestHandler", "ThreadingMixIn"] |
| 138 | if hasattr(os, "fork"): |
| 139 | __all__.extend(["ForkingUDPServer","ForkingTCPServer", "ForkingMixIn"]) |
Skip Montanaro | e99d5ea | 2001-01-20 19:54:20 +0000 | [diff] [blame] | 140 | if hasattr(socket, "AF_UNIX"): |
| 141 | __all__.extend(["UnixStreamServer","UnixDatagramServer", |
| 142 | "ThreadingUnixStreamServer", |
| 143 | "ThreadingUnixDatagramServer"]) |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 144 | |
Charles-François Natali | 1d29cc5 | 2014-03-24 22:25:39 +0000 | [diff] [blame] | 145 | # poll/select have the advantage of not requiring any extra file descriptor, |
| 146 | # contrarily to epoll/kqueue (also, they require a single syscall). |
| 147 | if hasattr(selectors, 'PollSelector'): |
| 148 | _ServerSelector = selectors.PollSelector |
| 149 | else: |
| 150 | _ServerSelector = selectors.SelectSelector |
| 151 | |
Antoine Pitrou | b0a9c66 | 2012-04-09 00:47:24 +0200 | [diff] [blame] | 152 | |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 153 | class BaseServer: |
| 154 | |
| 155 | """Base class for server classes. |
| 156 | |
| 157 | Methods for the caller: |
| 158 | |
| 159 | - __init__(server_address, RequestHandlerClass) |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 160 | - serve_forever(poll_interval=0.5) |
| 161 | - shutdown() |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 162 | - handle_request() # if you do not use serve_forever() |
Charles-François Natali | 1d29cc5 | 2014-03-24 22:25:39 +0000 | [diff] [blame] | 163 | - fileno() -> int # for selector |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 164 | |
| 165 | Methods that may be overridden: |
| 166 | |
| 167 | - server_bind() |
| 168 | - server_activate() |
| 169 | - get_request() -> request, client_address |
Georg Brandl | fceab5a | 2008-01-19 20:08:23 +0000 | [diff] [blame] | 170 | - handle_timeout() |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 171 | - verify_request(request, client_address) |
| 172 | - server_close() |
| 173 | - process_request(request, client_address) |
Kristján Valur Jónsson | a5b47ce | 2009-07-07 09:09:10 +0000 | [diff] [blame] | 174 | - shutdown_request(request) |
Ka-Ping Yee | 285a7e5 | 2001-04-11 04:02:05 +0000 | [diff] [blame] | 175 | - close_request(request) |
Senthil Kumaran | 5e826e8 | 2011-05-26 00:22:59 +0800 | [diff] [blame] | 176 | - service_actions() |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 177 | - handle_error() |
| 178 | |
| 179 | Methods for derived classes: |
| 180 | |
| 181 | - finish_request(request, client_address) |
| 182 | |
| 183 | Class variables that may be overridden by derived classes or |
| 184 | instances: |
| 185 | |
Georg Brandl | fceab5a | 2008-01-19 20:08:23 +0000 | [diff] [blame] | 186 | - timeout |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 187 | - address_family |
| 188 | - socket_type |
Barry Warsaw | b97f0b7 | 2003-10-09 23:48:52 +0000 | [diff] [blame] | 189 | - allow_reuse_address |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 190 | |
| 191 | Instance variables: |
| 192 | |
| 193 | - RequestHandlerClass |
| 194 | - socket |
| 195 | |
| 196 | """ |
| 197 | |
Georg Brandl | fceab5a | 2008-01-19 20:08:23 +0000 | [diff] [blame] | 198 | timeout = None |
| 199 | |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 200 | def __init__(self, server_address, RequestHandlerClass): |
| 201 | """Constructor. May be extended, do not override.""" |
| 202 | self.server_address = server_address |
| 203 | self.RequestHandlerClass = RequestHandlerClass |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 204 | self.__is_shut_down = threading.Event() |
Antoine Pitrou | 3bcba8e | 2010-04-25 22:01:43 +0000 | [diff] [blame] | 205 | self.__shutdown_request = False |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 206 | |
| 207 | def server_activate(self): |
| 208 | """Called by constructor to activate the server. |
| 209 | |
| 210 | May be overridden. |
| 211 | |
| 212 | """ |
| 213 | pass |
| 214 | |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 215 | def serve_forever(self, poll_interval=0.5): |
| 216 | """Handle one request at a time until shutdown. |
| 217 | |
| 218 | Polls for shutdown every poll_interval seconds. Ignores |
| 219 | self.timeout. If you need to do periodic tasks, do them in |
| 220 | another thread. |
| 221 | """ |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 222 | self.__is_shut_down.clear() |
Antoine Pitrou | 3bcba8e | 2010-04-25 22:01:43 +0000 | [diff] [blame] | 223 | try: |
Charles-François Natali | 1d29cc5 | 2014-03-24 22:25:39 +0000 | [diff] [blame] | 224 | # XXX: Consider using another file descriptor or connecting to the |
| 225 | # socket to wake this up instead of polling. Polling reduces our |
| 226 | # responsiveness to a shutdown request and wastes cpu at all other |
| 227 | # times. |
| 228 | with _ServerSelector() as selector: |
| 229 | selector.register(self, selectors.EVENT_READ) |
Senthil Kumaran | 5e826e8 | 2011-05-26 00:22:59 +0800 | [diff] [blame] | 230 | |
Charles-François Natali | 1d29cc5 | 2014-03-24 22:25:39 +0000 | [diff] [blame] | 231 | while not self.__shutdown_request: |
| 232 | ready = selector.select(poll_interval) |
Denis Ledoux | 10cb376 | 2018-10-26 15:46:17 +0200 | [diff] [blame] | 233 | # bpo-35017: shutdown() called during select(), exit immediately. |
| 234 | if self.__shutdown_request: |
| 235 | break |
Charles-François Natali | 1d29cc5 | 2014-03-24 22:25:39 +0000 | [diff] [blame] | 236 | if ready: |
| 237 | self._handle_request_noblock() |
| 238 | |
| 239 | self.service_actions() |
Antoine Pitrou | 3bcba8e | 2010-04-25 22:01:43 +0000 | [diff] [blame] | 240 | finally: |
| 241 | self.__shutdown_request = False |
| 242 | self.__is_shut_down.set() |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 243 | |
| 244 | def shutdown(self): |
| 245 | """Stops the serve_forever loop. |
| 246 | |
| 247 | Blocks until the loop has finished. This must be called while |
| 248 | serve_forever() is running in another thread, or it will |
| 249 | deadlock. |
| 250 | """ |
Antoine Pitrou | 3bcba8e | 2010-04-25 22:01:43 +0000 | [diff] [blame] | 251 | self.__shutdown_request = True |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 252 | self.__is_shut_down.wait() |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 253 | |
Senthil Kumaran | 5e826e8 | 2011-05-26 00:22:59 +0800 | [diff] [blame] | 254 | def service_actions(self): |
| 255 | """Called by the serve_forever() loop. |
| 256 | |
| 257 | May be overridden by a subclass / Mixin to implement any code that |
| 258 | needs to be run during the loop. |
| 259 | """ |
| 260 | pass |
| 261 | |
Charles-François Natali | 1d29cc5 | 2014-03-24 22:25:39 +0000 | [diff] [blame] | 262 | # The distinction between handling, getting, processing and finishing a |
| 263 | # request is fairly arbitrary. Remember: |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 264 | # |
Charles-François Natali | 1d29cc5 | 2014-03-24 22:25:39 +0000 | [diff] [blame] | 265 | # - handle_request() is the top-level call. It calls selector.select(), |
| 266 | # get_request(), verify_request() and process_request() |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 267 | # - get_request() is different for stream or datagram sockets |
Charles-François Natali | 1d29cc5 | 2014-03-24 22:25:39 +0000 | [diff] [blame] | 268 | # - process_request() is the place that may fork a new process or create a |
| 269 | # new thread to finish the request |
| 270 | # - finish_request() instantiates the request handler class; this |
| 271 | # constructor will handle the request all by itself |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 272 | |
| 273 | def handle_request(self): |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 274 | """Handle one request, possibly blocking. |
| 275 | |
| 276 | Respects self.timeout. |
| 277 | """ |
| 278 | # Support people who used socket.settimeout() to escape |
| 279 | # handle_request before self.timeout was available. |
| 280 | timeout = self.socket.gettimeout() |
| 281 | if timeout is None: |
| 282 | timeout = self.timeout |
| 283 | elif self.timeout is not None: |
| 284 | timeout = min(timeout, self.timeout) |
Charles-François Natali | 1d29cc5 | 2014-03-24 22:25:39 +0000 | [diff] [blame] | 285 | if timeout is not None: |
| 286 | deadline = time() + timeout |
| 287 | |
| 288 | # Wait until a request arrives or the timeout expires - the loop is |
Berker Peksag | 1ed2e69 | 2014-10-19 18:07:05 +0300 | [diff] [blame] | 289 | # necessary to accommodate early wakeups due to EINTR. |
Charles-François Natali | 1d29cc5 | 2014-03-24 22:25:39 +0000 | [diff] [blame] | 290 | with _ServerSelector() as selector: |
| 291 | selector.register(self, selectors.EVENT_READ) |
| 292 | |
| 293 | while True: |
| 294 | ready = selector.select(timeout) |
| 295 | if ready: |
| 296 | return self._handle_request_noblock() |
| 297 | else: |
| 298 | if timeout is not None: |
| 299 | timeout = deadline - time() |
| 300 | if timeout < 0: |
| 301 | return self.handle_timeout() |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 302 | |
| 303 | def _handle_request_noblock(self): |
| 304 | """Handle one request, without blocking. |
| 305 | |
Charles-François Natali | 1d29cc5 | 2014-03-24 22:25:39 +0000 | [diff] [blame] | 306 | I assume that selector.select() has returned that the socket is |
| 307 | readable before this function was called, so there should be no risk of |
| 308 | blocking in get_request(). |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 309 | """ |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 310 | try: |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 311 | request, client_address = self.get_request() |
Andrew Svetlov | 0832af6 | 2012-12-18 23:10:48 +0200 | [diff] [blame] | 312 | except OSError: |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 313 | return |
| 314 | if self.verify_request(request, client_address): |
| 315 | try: |
| 316 | self.process_request(request, client_address) |
Martin Panter | d9108d1 | 2016-02-21 08:49:56 +0000 | [diff] [blame] | 317 | except Exception: |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 318 | self.handle_error(request, client_address) |
Kristján Valur Jónsson | a5b47ce | 2009-07-07 09:09:10 +0000 | [diff] [blame] | 319 | self.shutdown_request(request) |
Martin Panter | d9108d1 | 2016-02-21 08:49:56 +0000 | [diff] [blame] | 320 | except: |
| 321 | self.shutdown_request(request) |
| 322 | raise |
Martin Panter | c12fef9 | 2016-02-18 10:43:55 +0000 | [diff] [blame] | 323 | else: |
| 324 | self.shutdown_request(request) |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 325 | |
Georg Brandl | fceab5a | 2008-01-19 20:08:23 +0000 | [diff] [blame] | 326 | def handle_timeout(self): |
| 327 | """Called if no new request arrives within self.timeout. |
| 328 | |
| 329 | Overridden by ForkingMixIn. |
| 330 | """ |
| 331 | pass |
| 332 | |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 333 | def verify_request(self, request, client_address): |
| 334 | """Verify the request. May be overridden. |
| 335 | |
Tim Peters | bc0e910 | 2002-04-04 22:55:58 +0000 | [diff] [blame] | 336 | Return True if we should proceed with this request. |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 337 | |
| 338 | """ |
Tim Peters | bc0e910 | 2002-04-04 22:55:58 +0000 | [diff] [blame] | 339 | return True |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 340 | |
| 341 | def process_request(self, request, client_address): |
| 342 | """Call finish_request. |
| 343 | |
| 344 | Overridden by ForkingMixIn and ThreadingMixIn. |
| 345 | |
| 346 | """ |
| 347 | self.finish_request(request, client_address) |
Kristján Valur Jónsson | a5b47ce | 2009-07-07 09:09:10 +0000 | [diff] [blame] | 348 | self.shutdown_request(request) |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 349 | |
| 350 | def server_close(self): |
| 351 | """Called to clean-up the server. |
| 352 | |
| 353 | May be overridden. |
| 354 | |
| 355 | """ |
| 356 | pass |
| 357 | |
| 358 | def finish_request(self, request, client_address): |
| 359 | """Finish one request by instantiating RequestHandlerClass.""" |
| 360 | self.RequestHandlerClass(request, client_address, self) |
| 361 | |
Kristján Valur Jónsson | a5b47ce | 2009-07-07 09:09:10 +0000 | [diff] [blame] | 362 | def shutdown_request(self, request): |
| 363 | """Called to shutdown and close an individual request.""" |
| 364 | self.close_request(request) |
| 365 | |
Ka-Ping Yee | 285a7e5 | 2001-04-11 04:02:05 +0000 | [diff] [blame] | 366 | def close_request(self, request): |
| 367 | """Called to clean up an individual request.""" |
| 368 | pass |
| 369 | |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 370 | def handle_error(self, request, client_address): |
| 371 | """Handle an error gracefully. May be overridden. |
| 372 | |
| 373 | The default is to print a traceback and continue. |
| 374 | |
| 375 | """ |
Martin Panter | d9108d1 | 2016-02-21 08:49:56 +0000 | [diff] [blame] | 376 | print('-'*40, file=sys.stderr) |
Noah Doersing | 8bcfd31 | 2020-05-01 06:30:10 +0200 | [diff] [blame] | 377 | print('Exception occurred during processing of request from', |
Martin Panter | d9108d1 | 2016-02-21 08:49:56 +0000 | [diff] [blame] | 378 | client_address, file=sys.stderr) |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 379 | import traceback |
Martin Panter | d9108d1 | 2016-02-21 08:49:56 +0000 | [diff] [blame] | 380 | traceback.print_exc() |
| 381 | print('-'*40, file=sys.stderr) |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 382 | |
Martin Panter | 0cab9c1 | 2016-04-13 00:36:52 +0000 | [diff] [blame] | 383 | def __enter__(self): |
| 384 | return self |
| 385 | |
| 386 | def __exit__(self, *args): |
| 387 | self.server_close() |
| 388 | |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 389 | |
| 390 | class TCPServer(BaseServer): |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 391 | |
| 392 | """Base class for various socket-based server classes. |
| 393 | |
| 394 | Defaults to synchronous IP stream (i.e., TCP). |
| 395 | |
| 396 | Methods for the caller: |
| 397 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 398 | - __init__(server_address, RequestHandlerClass, bind_and_activate=True) |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 399 | - serve_forever(poll_interval=0.5) |
| 400 | - shutdown() |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 401 | - handle_request() # if you don't use serve_forever() |
Charles-François Natali | 1d29cc5 | 2014-03-24 22:25:39 +0000 | [diff] [blame] | 402 | - fileno() -> int # for selector |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 403 | |
| 404 | Methods that may be overridden: |
| 405 | |
| 406 | - server_bind() |
| 407 | - server_activate() |
| 408 | - get_request() -> request, client_address |
Georg Brandl | fceab5a | 2008-01-19 20:08:23 +0000 | [diff] [blame] | 409 | - handle_timeout() |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 410 | - verify_request(request, client_address) |
| 411 | - process_request(request, client_address) |
Kristján Valur Jónsson | a5b47ce | 2009-07-07 09:09:10 +0000 | [diff] [blame] | 412 | - shutdown_request(request) |
Ka-Ping Yee | 285a7e5 | 2001-04-11 04:02:05 +0000 | [diff] [blame] | 413 | - close_request(request) |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 414 | - handle_error() |
| 415 | |
| 416 | Methods for derived classes: |
| 417 | |
| 418 | - finish_request(request, client_address) |
| 419 | |
| 420 | Class variables that may be overridden by derived classes or |
| 421 | instances: |
| 422 | |
Georg Brandl | fceab5a | 2008-01-19 20:08:23 +0000 | [diff] [blame] | 423 | - timeout |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 424 | - address_family |
| 425 | - socket_type |
| 426 | - request_queue_size (only for stream sockets) |
Barry Warsaw | 3aaad50 | 2003-10-09 22:44:05 +0000 | [diff] [blame] | 427 | - allow_reuse_address |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 428 | |
| 429 | Instance variables: |
| 430 | |
| 431 | - server_address |
| 432 | - RequestHandlerClass |
| 433 | - socket |
| 434 | |
| 435 | """ |
| 436 | |
| 437 | address_family = socket.AF_INET |
| 438 | |
| 439 | socket_type = socket.SOCK_STREAM |
| 440 | |
| 441 | request_queue_size = 5 |
| 442 | |
Raymond Hettinger | c8f8034 | 2002-08-25 16:36:49 +0000 | [diff] [blame] | 443 | allow_reuse_address = False |
Guido van Rossum | e3c7a5f | 2000-05-09 14:53:29 +0000 | [diff] [blame] | 444 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 445 | def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 446 | """Constructor. May be extended, do not override.""" |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 447 | BaseServer.__init__(self, server_address, RequestHandlerClass) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 448 | self.socket = socket.socket(self.address_family, |
| 449 | self.socket_type) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 450 | if bind_and_activate: |
Charles-François Natali | 0f4f048 | 2014-10-13 19:19:26 +0100 | [diff] [blame] | 451 | try: |
| 452 | self.server_bind() |
| 453 | self.server_activate() |
| 454 | except: |
| 455 | self.server_close() |
| 456 | raise |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 457 | |
| 458 | def server_bind(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 459 | """Called by constructor to bind the socket. |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 460 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 461 | May be overridden. |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 462 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 463 | """ |
Guido van Rossum | e3c7a5f | 2000-05-09 14:53:29 +0000 | [diff] [blame] | 464 | if self.allow_reuse_address: |
| 465 | self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 466 | self.socket.bind(self.server_address) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 467 | self.server_address = self.socket.getsockname() |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 468 | |
| 469 | def server_activate(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 470 | """Called by constructor to activate the server. |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 471 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 472 | May be overridden. |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 473 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 474 | """ |
| 475 | self.socket.listen(self.request_queue_size) |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 476 | |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 477 | def server_close(self): |
| 478 | """Called to clean-up the server. |
| 479 | |
| 480 | May be overridden. |
| 481 | |
| 482 | """ |
| 483 | self.socket.close() |
| 484 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 485 | def fileno(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 486 | """Return socket file number. |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 487 | |
Charles-François Natali | 1d29cc5 | 2014-03-24 22:25:39 +0000 | [diff] [blame] | 488 | Interface required by selector. |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 489 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 490 | """ |
| 491 | return self.socket.fileno() |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 492 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 493 | def get_request(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 494 | """Get the request and client address from the socket. |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 495 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 496 | May be overridden. |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 497 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 498 | """ |
| 499 | return self.socket.accept() |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 500 | |
Kristján Valur Jónsson | a5b47ce | 2009-07-07 09:09:10 +0000 | [diff] [blame] | 501 | def shutdown_request(self, request): |
| 502 | """Called to shutdown and close an individual request.""" |
Kristján Valur Jónsson | 200cfd0 | 2009-07-04 15:18:00 +0000 | [diff] [blame] | 503 | try: |
| 504 | #explicitly shutdown. socket.close() merely releases |
| 505 | #the socket and waits for GC to perform the actual close. |
| 506 | request.shutdown(socket.SHUT_WR) |
Andrew Svetlov | 0832af6 | 2012-12-18 23:10:48 +0200 | [diff] [blame] | 507 | except OSError: |
Kristján Valur Jónsson | 200cfd0 | 2009-07-04 15:18:00 +0000 | [diff] [blame] | 508 | pass #some platforms may raise ENOTCONN here |
Kristján Valur Jónsson | a5b47ce | 2009-07-07 09:09:10 +0000 | [diff] [blame] | 509 | self.close_request(request) |
| 510 | |
| 511 | def close_request(self, request): |
| 512 | """Called to clean up an individual request.""" |
Ka-Ping Yee | 285a7e5 | 2001-04-11 04:02:05 +0000 | [diff] [blame] | 513 | request.close() |
| 514 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 515 | |
| 516 | class UDPServer(TCPServer): |
| 517 | |
| 518 | """UDP server class.""" |
| 519 | |
Raymond Hettinger | c8f8034 | 2002-08-25 16:36:49 +0000 | [diff] [blame] | 520 | allow_reuse_address = False |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 521 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 522 | socket_type = socket.SOCK_DGRAM |
| 523 | |
| 524 | max_packet_size = 8192 |
| 525 | |
| 526 | def get_request(self): |
Guido van Rossum | 3249082 | 1998-06-16 02:27:33 +0000 | [diff] [blame] | 527 | data, client_addr = self.socket.recvfrom(self.max_packet_size) |
| 528 | return (data, self.socket), client_addr |
| 529 | |
| 530 | def server_activate(self): |
| 531 | # No need to call listen() for UDP. |
| 532 | pass |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 533 | |
Kristján Valur Jónsson | a5b47ce | 2009-07-07 09:09:10 +0000 | [diff] [blame] | 534 | def shutdown_request(self, request): |
| 535 | # No need to shutdown anything. |
| 536 | self.close_request(request) |
| 537 | |
Ka-Ping Yee | 285a7e5 | 2001-04-11 04:02:05 +0000 | [diff] [blame] | 538 | def close_request(self, request): |
| 539 | # No need to close anything. |
| 540 | pass |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 541 | |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | cef1f83 | 2016-06-03 00:13:36 +0000 | [diff] [blame] | 542 | if hasattr(os, "fork"): |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | 1bb8109 | 2016-06-03 00:16:02 +0000 | [diff] [blame] | 543 | class ForkingMixIn: |
| 544 | """Mix-in class to handle each request in a new process.""" |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 545 | |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | 1bb8109 | 2016-06-03 00:16:02 +0000 | [diff] [blame] | 546 | timeout = 300 |
| 547 | active_children = None |
| 548 | max_children = 40 |
Victor Stinner | 453bd0b | 2018-05-24 03:14:44 +0200 | [diff] [blame] | 549 | # If true, server_close() waits until all child processes complete. |
| 550 | block_on_close = True |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 551 | |
Victor Stinner | aa8ec34 | 2017-08-10 15:28:16 +0200 | [diff] [blame] | 552 | def collect_children(self, *, blocking=False): |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | 1bb8109 | 2016-06-03 00:16:02 +0000 | [diff] [blame] | 553 | """Internal routine to wait for children that have exited.""" |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 554 | if self.active_children is None: |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | 1bb8109 | 2016-06-03 00:16:02 +0000 | [diff] [blame] | 555 | return |
| 556 | |
| 557 | # If we're above the max number of children, wait and reap them until |
| 558 | # we go back below threshold. Note that we use waitpid(-1) below to be |
| 559 | # able to collect children in size(<defunct children>) syscalls instead |
| 560 | # of size(<children>): the downside is that this might reap children |
| 561 | # which we didn't spawn, which is why we only resort to this when we're |
| 562 | # above max_children. |
| 563 | while len(self.active_children) >= self.max_children: |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 564 | try: |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | 1bb8109 | 2016-06-03 00:16:02 +0000 | [diff] [blame] | 565 | pid, _ = os.waitpid(-1, 0) |
| 566 | self.active_children.discard(pid) |
| 567 | except ChildProcessError: |
| 568 | # we don't have any children, we're done |
| 569 | self.active_children.clear() |
| 570 | except OSError: |
| 571 | break |
| 572 | |
| 573 | # Now reap all defunct children. |
| 574 | for pid in self.active_children.copy(): |
| 575 | try: |
Victor Stinner | aa8ec34 | 2017-08-10 15:28:16 +0200 | [diff] [blame] | 576 | flags = 0 if blocking else os.WNOHANG |
| 577 | pid, _ = os.waitpid(pid, flags) |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | 1bb8109 | 2016-06-03 00:16:02 +0000 | [diff] [blame] | 578 | # if the child hasn't exited yet, pid will be 0 and ignored by |
| 579 | # discard() below |
| 580 | self.active_children.discard(pid) |
| 581 | except ChildProcessError: |
| 582 | # someone else reaped it |
| 583 | self.active_children.discard(pid) |
| 584 | except OSError: |
| 585 | pass |
| 586 | |
| 587 | def handle_timeout(self): |
| 588 | """Wait for zombies after self.timeout seconds of inactivity. |
| 589 | |
| 590 | May be extended, do not override. |
| 591 | """ |
| 592 | self.collect_children() |
| 593 | |
| 594 | def service_actions(self): |
| 595 | """Collect the zombie child processes regularly in the ForkingMixIn. |
| 596 | |
Christopher Hunt | 6ded898 | 2018-12-21 17:22:09 -0500 | [diff] [blame] | 597 | service_actions is called in the BaseServer's serve_forever loop. |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | 1bb8109 | 2016-06-03 00:16:02 +0000 | [diff] [blame] | 598 | """ |
| 599 | self.collect_children() |
| 600 | |
| 601 | def process_request(self, request, client_address): |
| 602 | """Fork a new subprocess to process the request.""" |
| 603 | pid = os.fork() |
| 604 | if pid: |
| 605 | # Parent process |
| 606 | if self.active_children is None: |
| 607 | self.active_children = set() |
| 608 | self.active_children.add(pid) |
| 609 | self.close_request(request) |
| 610 | return |
| 611 | else: |
| 612 | # Child process. |
| 613 | # This must never return, hence os._exit()! |
| 614 | status = 1 |
| 615 | try: |
| 616 | self.finish_request(request, client_address) |
| 617 | status = 0 |
| 618 | except Exception: |
| 619 | self.handle_error(request, client_address) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 620 | finally: |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | 1bb8109 | 2016-06-03 00:16:02 +0000 | [diff] [blame] | 621 | try: |
| 622 | self.shutdown_request(request) |
| 623 | finally: |
| 624 | os._exit(status) |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 625 | |
Victor Stinner | aa8ec34 | 2017-08-10 15:28:16 +0200 | [diff] [blame] | 626 | def server_close(self): |
| 627 | super().server_close() |
Victor Stinner | 453bd0b | 2018-05-24 03:14:44 +0200 | [diff] [blame] | 628 | self.collect_children(blocking=self.block_on_close) |
Victor Stinner | aa8ec34 | 2017-08-10 15:28:16 +0200 | [diff] [blame] | 629 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 630 | |
| 631 | class ThreadingMixIn: |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 632 | """Mix-in class to handle each request in a new thread.""" |
| 633 | |
Martin v. Löwis | f86e8ef | 2002-11-22 08:08:44 +0000 | [diff] [blame] | 634 | # Decides how threads will act upon termination of the |
| 635 | # main process |
Fred Drake | 132e0e8 | 2002-11-22 14:22:49 +0000 | [diff] [blame] | 636 | daemon_threads = False |
Victor Stinner | 453bd0b | 2018-05-24 03:14:44 +0200 | [diff] [blame] | 637 | # If true, server_close() waits until all non-daemonic threads terminate. |
| 638 | block_on_close = True |
Jason R. Coombs | aca67da | 2020-11-02 11:48:56 -0500 | [diff] [blame] | 639 | # For non-daemonic threads, list of threading.Threading objects |
Victor Stinner | b8f4163 | 2017-09-13 01:47:22 -0700 | [diff] [blame] | 640 | # used by server_close() to wait for all threads completion. |
Jason R. Coombs | aca67da | 2020-11-02 11:48:56 -0500 | [diff] [blame] | 641 | _threads = None |
Martin v. Löwis | f86e8ef | 2002-11-22 08:08:44 +0000 | [diff] [blame] | 642 | |
Guido van Rossum | a5343cc | 2001-10-18 18:02:07 +0000 | [diff] [blame] | 643 | def process_request_thread(self, request, client_address): |
Guido van Rossum | 83c3281 | 2001-10-23 21:42:45 +0000 | [diff] [blame] | 644 | """Same as in BaseServer but as a thread. |
| 645 | |
| 646 | In addition, exception handling is done here. |
| 647 | |
| 648 | """ |
| 649 | try: |
| 650 | self.finish_request(request, client_address) |
Martin Panter | d9108d1 | 2016-02-21 08:49:56 +0000 | [diff] [blame] | 651 | except Exception: |
Guido van Rossum | 83c3281 | 2001-10-23 21:42:45 +0000 | [diff] [blame] | 652 | self.handle_error(request, client_address) |
Martin Panter | d9108d1 | 2016-02-21 08:49:56 +0000 | [diff] [blame] | 653 | finally: |
Jason R. Coombs | aca67da | 2020-11-02 11:48:56 -0500 | [diff] [blame] | 654 | self.shutdown_request(request) |
Guido van Rossum | a5343cc | 2001-10-18 18:02:07 +0000 | [diff] [blame] | 655 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 656 | def process_request(self, request, client_address): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 657 | """Start a new thread to process the request.""" |
Guido van Rossum | a5343cc | 2001-10-18 18:02:07 +0000 | [diff] [blame] | 658 | t = threading.Thread(target = self.process_request_thread, |
Jeremy Hylton | 7526027 | 1999-10-12 16:20:13 +0000 | [diff] [blame] | 659 | args = (request, client_address)) |
Florent Xicluna | 12b66b5 | 2011-11-04 10:16:28 +0100 | [diff] [blame] | 660 | t.daemon = self.daemon_threads |
Jason R. Coombs | aca67da | 2020-11-02 11:48:56 -0500 | [diff] [blame] | 661 | if not t.daemon and self.block_on_close: |
| 662 | if self._threads is None: |
| 663 | self._threads = [] |
| 664 | self._threads.append(t) |
Jeremy Hylton | 7526027 | 1999-10-12 16:20:13 +0000 | [diff] [blame] | 665 | t.start() |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 666 | |
Victor Stinner | b8f4163 | 2017-09-13 01:47:22 -0700 | [diff] [blame] | 667 | def server_close(self): |
| 668 | super().server_close() |
Jason R. Coombs | aca67da | 2020-11-02 11:48:56 -0500 | [diff] [blame] | 669 | if self.block_on_close: |
| 670 | threads = self._threads |
| 671 | self._threads = None |
| 672 | if threads: |
| 673 | for thread in threads: |
| 674 | thread.join() |
Victor Stinner | b8f4163 | 2017-09-13 01:47:22 -0700 | [diff] [blame] | 675 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 676 | |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | cef1f83 | 2016-06-03 00:13:36 +0000 | [diff] [blame] | 677 | if hasattr(os, "fork"): |
| 678 | class ForkingUDPServer(ForkingMixIn, UDPServer): pass |
| 679 | class ForkingTCPServer(ForkingMixIn, TCPServer): pass |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 680 | |
| 681 | class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass |
| 682 | class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass |
| 683 | |
Guido van Rossum | 67a40e8 | 1998-11-30 15:07:01 +0000 | [diff] [blame] | 684 | if hasattr(socket, 'AF_UNIX'): |
| 685 | |
| 686 | class UnixStreamServer(TCPServer): |
| 687 | address_family = socket.AF_UNIX |
| 688 | |
| 689 | class UnixDatagramServer(UDPServer): |
| 690 | address_family = socket.AF_UNIX |
| 691 | |
| 692 | class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass |
| 693 | |
| 694 | class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 695 | |
| 696 | class BaseRequestHandler: |
| 697 | |
| 698 | """Base class for request handler classes. |
| 699 | |
| 700 | This class is instantiated for each request to be handled. The |
| 701 | constructor sets the instance variables request, client_address |
| 702 | and server, and then calls the handle() method. To implement a |
| 703 | specific service, all you need to do is to derive a class which |
| 704 | defines a handle() method. |
| 705 | |
| 706 | The handle() method can find the request as self.request, the |
Guido van Rossum | fdb3d1a | 1998-11-16 19:06:30 +0000 | [diff] [blame] | 707 | client address as self.client_address, and the server (in case it |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 708 | needs access to per-server information) as self.server. Since a |
| 709 | separate instance is created for each request, the handle() method |
Martin Panter | 96a4f07 | 2016-02-10 01:17:51 +0000 | [diff] [blame] | 710 | can define other arbitrary instance variables. |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 711 | |
| 712 | """ |
| 713 | |
| 714 | def __init__(self, request, client_address, server): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 715 | self.request = request |
| 716 | self.client_address = client_address |
| 717 | self.server = server |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 718 | self.setup() |
Kristján Valur Jónsson | 985fc6a | 2009-07-01 10:01:31 +0000 | [diff] [blame] | 719 | try: |
| 720 | self.handle() |
| 721 | finally: |
| 722 | self.finish() |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 723 | |
| 724 | def setup(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 725 | pass |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 726 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 727 | def handle(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 728 | pass |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 729 | |
| 730 | def finish(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 731 | pass |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 732 | |
| 733 | |
| 734 | # The following two classes make it possible to use the same service |
| 735 | # class for stream or datagram servers. |
| 736 | # Each class sets up these instance variables: |
| 737 | # - rfile: a file object from which receives the request is read |
| 738 | # - wfile: a file object to which the reply is written |
| 739 | # When the handle() method returns, wfile is flushed properly |
| 740 | |
| 741 | |
| 742 | class StreamRequestHandler(BaseRequestHandler): |
| 743 | |
| 744 | """Define self.rfile and self.wfile for stream sockets.""" |
| 745 | |
Guido van Rossum | 01fed4d | 2000-09-01 03:25:14 +0000 | [diff] [blame] | 746 | # Default buffer sizes for rfile, wfile. |
| 747 | # We default rfile to buffered because otherwise it could be |
| 748 | # really slow for large data (a getc() call per byte); we make |
| 749 | # wfile unbuffered because (a) often after a write() we want to |
| 750 | # read and we need to flush the line; (b) big writes to unbuffered |
| 751 | # files are typically optimized by stdio even when big reads |
| 752 | # aren't. |
| 753 | rbufsize = -1 |
| 754 | wbufsize = 0 |
| 755 | |
Kristján Valur Jónsson | 985fc6a | 2009-07-01 10:01:31 +0000 | [diff] [blame] | 756 | # A timeout to apply to the request socket, if not None. |
| 757 | timeout = None |
| 758 | |
Ezio Melotti | 4969f70 | 2011-03-15 05:59:46 +0200 | [diff] [blame] | 759 | # Disable nagle algorithm for this socket, if True. |
Kristján Valur Jónsson | 41a5750 | 2009-06-28 21:34:22 +0000 | [diff] [blame] | 760 | # Use only when wbufsize != 0, to avoid small packets. |
| 761 | disable_nagle_algorithm = False |
| 762 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 763 | def setup(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 764 | self.connection = self.request |
Kristján Valur Jónsson | 985fc6a | 2009-07-01 10:01:31 +0000 | [diff] [blame] | 765 | if self.timeout is not None: |
| 766 | self.connection.settimeout(self.timeout) |
Kristján Valur Jónsson | 41a5750 | 2009-06-28 21:34:22 +0000 | [diff] [blame] | 767 | if self.disable_nagle_algorithm: |
| 768 | self.connection.setsockopt(socket.IPPROTO_TCP, |
| 769 | socket.TCP_NODELAY, True) |
Guido van Rossum | 01fed4d | 2000-09-01 03:25:14 +0000 | [diff] [blame] | 770 | self.rfile = self.connection.makefile('rb', self.rbufsize) |
Martin Panter | 34eeed4 | 2016-06-29 10:12:22 +0000 | [diff] [blame] | 771 | if self.wbufsize == 0: |
| 772 | self.wfile = _SocketWriter(self.connection) |
| 773 | else: |
| 774 | self.wfile = self.connection.makefile('wb', self.wbufsize) |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 775 | |
| 776 | def finish(self): |
Anthony Baxter | 4cedc1e | 2003-01-02 03:07:48 +0000 | [diff] [blame] | 777 | if not self.wfile.closed: |
Kristján Valur Jónsson | 36852b7 | 2012-12-25 22:46:32 +0000 | [diff] [blame] | 778 | try: |
| 779 | self.wfile.flush() |
| 780 | except socket.error: |
Serhiy Storchaka | 6a7b3a7 | 2016-04-17 08:32:47 +0300 | [diff] [blame] | 781 | # A final socket error may have occurred here, such as |
Kristján Valur Jónsson | 36852b7 | 2012-12-25 22:46:32 +0000 | [diff] [blame] | 782 | # the local error ECONNABORTED. |
| 783 | pass |
Guido van Rossum | 1d5102c | 1998-04-03 16:49:52 +0000 | [diff] [blame] | 784 | self.wfile.close() |
| 785 | self.rfile.close() |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 786 | |
Martin Panter | 34eeed4 | 2016-06-29 10:12:22 +0000 | [diff] [blame] | 787 | class _SocketWriter(BufferedIOBase): |
| 788 | """Simple writable BufferedIOBase implementation for a socket |
| 789 | |
| 790 | Does not hold data in a buffer, avoiding any need to call flush().""" |
| 791 | |
| 792 | def __init__(self, sock): |
| 793 | self._sock = sock |
| 794 | |
| 795 | def writable(self): |
| 796 | return True |
| 797 | |
| 798 | def write(self, b): |
| 799 | self._sock.sendall(b) |
| 800 | with memoryview(b) as view: |
| 801 | return view.nbytes |
| 802 | |
| 803 | def fileno(self): |
| 804 | return self._sock.fileno() |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 805 | |
| 806 | class DatagramRequestHandler(BaseRequestHandler): |
| 807 | |
| 808 | """Define self.rfile and self.wfile for datagram sockets.""" |
| 809 | |
| 810 | def setup(self): |
Guido van Rossum | 15863ea | 2007-08-03 19:03:39 +0000 | [diff] [blame] | 811 | from io import BytesIO |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 812 | self.packet, self.socket = self.request |
Guido van Rossum | 15863ea | 2007-08-03 19:03:39 +0000 | [diff] [blame] | 813 | self.rfile = BytesIO(self.packet) |
| 814 | self.wfile = BytesIO() |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 815 | |
| 816 | def finish(self): |
Guido van Rossum | 3249082 | 1998-06-16 02:27:33 +0000 | [diff] [blame] | 817 | self.socket.sendto(self.wfile.getvalue(), self.client_address) |