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