| 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 reqd 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 select() 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 | - Standard framework for select-based multiplexing |
|---|
| 108 | n/a | |
|---|
| 109 | n/a | XXX Open problems: |
|---|
| 110 | n/a | - What to do with out-of-band data? |
|---|
| 111 | n/a | |
|---|
| 112 | n/a | BaseServer: |
|---|
| 113 | n/a | - split generic "request" functionality out into BaseServer class. |
|---|
| 114 | n/a | Copyright (C) 2000 Luke Kenneth Casson Leighton <lkcl@samba.org> |
|---|
| 115 | n/a | |
|---|
| 116 | n/a | example: read entries from a SQL database (requires overriding |
|---|
| 117 | n/a | get_request() to return a table entry from the database). |
|---|
| 118 | n/a | entry is processed by a RequestHandlerClass. |
|---|
| 119 | n/a | |
|---|
| 120 | 1 | """ |
|---|
| 121 | n/a | |
|---|
| 122 | n/a | # Author of the BaseServer patch: Luke Kenneth Casson Leighton |
|---|
| 123 | n/a | |
|---|
| 124 | n/a | # XXX Warning! |
|---|
| 125 | n/a | # There is a test suite for this module, but it cannot be run by the |
|---|
| 126 | n/a | # standard regression test. |
|---|
| 127 | n/a | # To run it manually, run Lib/test/test_socketserver.py. |
|---|
| 128 | n/a | |
|---|
| 129 | 1 | __version__ = "0.4" |
|---|
| 130 | n/a | |
|---|
| 131 | n/a | |
|---|
| 132 | 1 | import socket |
|---|
| 133 | 1 | import select |
|---|
| 134 | 1 | import sys |
|---|
| 135 | 1 | import os |
|---|
| 136 | 1 | try: |
|---|
| 137 | 1 | import threading |
|---|
| 138 | 0 | except ImportError: |
|---|
| 139 | 0 | import dummy_threading as threading |
|---|
| 140 | n/a | |
|---|
| 141 | 1 | __all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer", |
|---|
| 142 | 1 | "ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler", |
|---|
| 143 | 1 | "StreamRequestHandler","DatagramRequestHandler", |
|---|
| 144 | 1 | "ThreadingMixIn", "ForkingMixIn"] |
|---|
| 145 | 1 | if hasattr(socket, "AF_UNIX"): |
|---|
| 146 | 1 | __all__.extend(["UnixStreamServer","UnixDatagramServer", |
|---|
| 147 | 1 | "ThreadingUnixStreamServer", |
|---|
| 148 | 1 | "ThreadingUnixDatagramServer"]) |
|---|
| 149 | n/a | |
|---|
| 150 | 2 | class BaseServer: |
|---|
| 151 | n/a | |
|---|
| 152 | n/a | """Base class for server classes. |
|---|
| 153 | n/a | |
|---|
| 154 | n/a | Methods for the caller: |
|---|
| 155 | n/a | |
|---|
| 156 | n/a | - __init__(server_address, RequestHandlerClass) |
|---|
| 157 | n/a | - serve_forever(poll_interval=0.5) |
|---|
| 158 | n/a | - shutdown() |
|---|
| 159 | n/a | - handle_request() # if you do not use serve_forever() |
|---|
| 160 | n/a | - fileno() -> int # for select() |
|---|
| 161 | n/a | |
|---|
| 162 | n/a | Methods that may be overridden: |
|---|
| 163 | n/a | |
|---|
| 164 | n/a | - server_bind() |
|---|
| 165 | n/a | - server_activate() |
|---|
| 166 | n/a | - get_request() -> request, client_address |
|---|
| 167 | n/a | - handle_timeout() |
|---|
| 168 | n/a | - verify_request(request, client_address) |
|---|
| 169 | n/a | - server_close() |
|---|
| 170 | n/a | - process_request(request, client_address) |
|---|
| 171 | n/a | - shutdown_request(request) |
|---|
| 172 | n/a | - close_request(request) |
|---|
| 173 | n/a | - handle_error() |
|---|
| 174 | n/a | |
|---|
| 175 | n/a | Methods for derived classes: |
|---|
| 176 | n/a | |
|---|
| 177 | n/a | - finish_request(request, client_address) |
|---|
| 178 | n/a | |
|---|
| 179 | n/a | Class variables that may be overridden by derived classes or |
|---|
| 180 | n/a | instances: |
|---|
| 181 | n/a | |
|---|
| 182 | n/a | - timeout |
|---|
| 183 | n/a | - address_family |
|---|
| 184 | n/a | - socket_type |
|---|
| 185 | n/a | - allow_reuse_address |
|---|
| 186 | n/a | |
|---|
| 187 | n/a | Instance variables: |
|---|
| 188 | n/a | |
|---|
| 189 | n/a | - RequestHandlerClass |
|---|
| 190 | n/a | - socket |
|---|
| 191 | n/a | |
|---|
| 192 | 1 | """ |
|---|
| 193 | n/a | |
|---|
| 194 | 1 | timeout = None |
|---|
| 195 | n/a | |
|---|
| 196 | 1 | def __init__(self, server_address, RequestHandlerClass): |
|---|
| 197 | n/a | """Constructor. May be extended, do not override.""" |
|---|
| 198 | 101 | self.server_address = server_address |
|---|
| 199 | 101 | self.RequestHandlerClass = RequestHandlerClass |
|---|
| 200 | 101 | self.__is_shut_down = threading.Event() |
|---|
| 201 | 101 | self.__shutdown_request = False |
|---|
| 202 | n/a | |
|---|
| 203 | 1 | def server_activate(self): |
|---|
| 204 | n/a | """Called by constructor to activate the server. |
|---|
| 205 | n/a | |
|---|
| 206 | n/a | May be overridden. |
|---|
| 207 | n/a | |
|---|
| 208 | n/a | """ |
|---|
| 209 | 0 | pass |
|---|
| 210 | n/a | |
|---|
| 211 | 1 | def serve_forever(self, poll_interval=0.5): |
|---|
| 212 | n/a | """Handle one request at a time until shutdown. |
|---|
| 213 | n/a | |
|---|
| 214 | n/a | Polls for shutdown every poll_interval seconds. Ignores |
|---|
| 215 | n/a | self.timeout. If you need to do periodic tasks, do them in |
|---|
| 216 | n/a | another thread. |
|---|
| 217 | n/a | """ |
|---|
| 218 | 57 | self.__is_shut_down.clear() |
|---|
| 219 | 57 | try: |
|---|
| 220 | 173 | while not self.__shutdown_request: |
|---|
| 221 | n/a | # XXX: Consider using another file descriptor or |
|---|
| 222 | n/a | # connecting to the socket to wake this up instead of |
|---|
| 223 | n/a | # polling. Polling reduces our responsiveness to a |
|---|
| 224 | n/a | # shutdown request and wastes cpu at all other times. |
|---|
| 225 | 116 | r, w, e = select.select([self], [], [], poll_interval) |
|---|
| 226 | 116 | if self in r: |
|---|
| 227 | 62 | self._handle_request_noblock() |
|---|
| 228 | n/a | finally: |
|---|
| 229 | 57 | self.__shutdown_request = False |
|---|
| 230 | 57 | self.__is_shut_down.set() |
|---|
| 231 | n/a | |
|---|
| 232 | 1 | def shutdown(self): |
|---|
| 233 | n/a | """Stops the serve_forever loop. |
|---|
| 234 | n/a | |
|---|
| 235 | n/a | Blocks until the loop has finished. This must be called while |
|---|
| 236 | n/a | serve_forever() is running in another thread, or it will |
|---|
| 237 | n/a | deadlock. |
|---|
| 238 | n/a | """ |
|---|
| 239 | 57 | self.__shutdown_request = True |
|---|
| 240 | 57 | self.__is_shut_down.wait() |
|---|
| 241 | n/a | |
|---|
| 242 | n/a | # The distinction between handling, getting, processing and |
|---|
| 243 | n/a | # finishing a request is fairly arbitrary. Remember: |
|---|
| 244 | n/a | # |
|---|
| 245 | n/a | # - handle_request() is the top-level call. It calls |
|---|
| 246 | n/a | # select, get_request(), verify_request() and process_request() |
|---|
| 247 | n/a | # - get_request() is different for stream or datagram sockets |
|---|
| 248 | n/a | # - process_request() is the place that may fork a new process |
|---|
| 249 | n/a | # or create a new thread to finish the request |
|---|
| 250 | n/a | # - finish_request() instantiates the request handler class; |
|---|
| 251 | n/a | # this constructor will handle the request all by itself |
|---|
| 252 | n/a | |
|---|
| 253 | 1 | def handle_request(self): |
|---|
| 254 | n/a | """Handle one request, possibly blocking. |
|---|
| 255 | n/a | |
|---|
| 256 | n/a | Respects self.timeout. |
|---|
| 257 | n/a | """ |
|---|
| 258 | n/a | # Support people who used socket.settimeout() to escape |
|---|
| 259 | n/a | # handle_request before self.timeout was available. |
|---|
| 260 | 57 | timeout = self.socket.gettimeout() |
|---|
| 261 | 57 | if timeout is None: |
|---|
| 262 | 9 | timeout = self.timeout |
|---|
| 263 | 48 | elif self.timeout is not None: |
|---|
| 264 | 0 | timeout = min(timeout, self.timeout) |
|---|
| 265 | 57 | fd_sets = select.select([self], [], [], timeout) |
|---|
| 266 | 57 | if not fd_sets[0]: |
|---|
| 267 | 4 | self.handle_timeout() |
|---|
| 268 | 4 | return |
|---|
| 269 | 53 | self._handle_request_noblock() |
|---|
| 270 | n/a | |
|---|
| 271 | 1 | def _handle_request_noblock(self): |
|---|
| 272 | n/a | """Handle one request, without blocking. |
|---|
| 273 | n/a | |
|---|
| 274 | n/a | I assume that select.select has returned that the socket is |
|---|
| 275 | n/a | readable before this function was called, so there should be |
|---|
| 276 | n/a | no risk of blocking in get_request(). |
|---|
| 277 | n/a | """ |
|---|
| 278 | 115 | try: |
|---|
| 279 | 115 | request, client_address = self.get_request() |
|---|
| 280 | 0 | except socket.error: |
|---|
| 281 | 0 | return |
|---|
| 282 | 115 | if self.verify_request(request, client_address): |
|---|
| 283 | 115 | try: |
|---|
| 284 | 115 | self.process_request(request, client_address) |
|---|
| 285 | 0 | except: |
|---|
| 286 | 0 | self.handle_error(request, client_address) |
|---|
| 287 | 0 | self.shutdown_request(request) |
|---|
| 288 | n/a | |
|---|
| 289 | 1 | def handle_timeout(self): |
|---|
| 290 | n/a | """Called if no new request arrives within self.timeout. |
|---|
| 291 | n/a | |
|---|
| 292 | n/a | Overridden by ForkingMixIn. |
|---|
| 293 | n/a | """ |
|---|
| 294 | 4 | pass |
|---|
| 295 | n/a | |
|---|
| 296 | 1 | def verify_request(self, request, client_address): |
|---|
| 297 | n/a | """Verify the request. May be overridden. |
|---|
| 298 | n/a | |
|---|
| 299 | n/a | Return True if we should proceed with this request. |
|---|
| 300 | n/a | |
|---|
| 301 | n/a | """ |
|---|
| 302 | 115 | return True |
|---|
| 303 | n/a | |
|---|
| 304 | 1 | def process_request(self, request, client_address): |
|---|
| 305 | n/a | """Call finish_request. |
|---|
| 306 | n/a | |
|---|
| 307 | n/a | Overridden by ForkingMixIn and ThreadingMixIn. |
|---|
| 308 | n/a | |
|---|
| 309 | n/a | """ |
|---|
| 310 | 94 | self.finish_request(request, client_address) |
|---|
| 311 | 94 | self.shutdown_request(request) |
|---|
| 312 | n/a | |
|---|
| 313 | 1 | def server_close(self): |
|---|
| 314 | n/a | """Called to clean-up the server. |
|---|
| 315 | n/a | |
|---|
| 316 | n/a | May be overridden. |
|---|
| 317 | n/a | |
|---|
| 318 | n/a | """ |
|---|
| 319 | 0 | pass |
|---|
| 320 | n/a | |
|---|
| 321 | 1 | def finish_request(self, request, client_address): |
|---|
| 322 | n/a | """Finish one request by instantiating RequestHandlerClass.""" |
|---|
| 323 | 109 | self.RequestHandlerClass(request, client_address, self) |
|---|
| 324 | n/a | |
|---|
| 325 | 1 | def shutdown_request(self, request): |
|---|
| 326 | n/a | """Called to shutdown and close an individual request.""" |
|---|
| 327 | 0 | self.close_request(request) |
|---|
| 328 | n/a | |
|---|
| 329 | 1 | def close_request(self, request): |
|---|
| 330 | n/a | """Called to clean up an individual request.""" |
|---|
| 331 | 0 | pass |
|---|
| 332 | n/a | |
|---|
| 333 | 1 | def handle_error(self, request, client_address): |
|---|
| 334 | n/a | """Handle an error gracefully. May be overridden. |
|---|
| 335 | n/a | |
|---|
| 336 | n/a | The default is to print a traceback and continue. |
|---|
| 337 | n/a | |
|---|
| 338 | n/a | """ |
|---|
| 339 | 0 | print '-'*40 |
|---|
| 340 | 0 | print 'Exception happened during processing of request from', |
|---|
| 341 | 0 | print client_address |
|---|
| 342 | 0 | import traceback |
|---|
| 343 | 0 | traceback.print_exc() # XXX But this goes to stderr! |
|---|
| 344 | 0 | print '-'*40 |
|---|
| 345 | n/a | |
|---|
| 346 | n/a | |
|---|
| 347 | 2 | class TCPServer(BaseServer): |
|---|
| 348 | n/a | |
|---|
| 349 | n/a | """Base class for various socket-based server classes. |
|---|
| 350 | n/a | |
|---|
| 351 | n/a | Defaults to synchronous IP stream (i.e., TCP). |
|---|
| 352 | n/a | |
|---|
| 353 | n/a | Methods for the caller: |
|---|
| 354 | n/a | |
|---|
| 355 | n/a | - __init__(server_address, RequestHandlerClass, bind_and_activate=True) |
|---|
| 356 | n/a | - serve_forever(poll_interval=0.5) |
|---|
| 357 | n/a | - shutdown() |
|---|
| 358 | n/a | - handle_request() # if you don't use serve_forever() |
|---|
| 359 | n/a | - fileno() -> int # for select() |
|---|
| 360 | n/a | |
|---|
| 361 | n/a | Methods that may be overridden: |
|---|
| 362 | n/a | |
|---|
| 363 | n/a | - server_bind() |
|---|
| 364 | n/a | - server_activate() |
|---|
| 365 | n/a | - get_request() -> request, client_address |
|---|
| 366 | n/a | - handle_timeout() |
|---|
| 367 | n/a | - verify_request(request, client_address) |
|---|
| 368 | n/a | - process_request(request, client_address) |
|---|
| 369 | n/a | - shutdown_request(request) |
|---|
| 370 | n/a | - close_request(request) |
|---|
| 371 | n/a | - handle_error() |
|---|
| 372 | n/a | |
|---|
| 373 | n/a | Methods for derived classes: |
|---|
| 374 | n/a | |
|---|
| 375 | n/a | - finish_request(request, client_address) |
|---|
| 376 | n/a | |
|---|
| 377 | n/a | Class variables that may be overridden by derived classes or |
|---|
| 378 | n/a | instances: |
|---|
| 379 | n/a | |
|---|
| 380 | n/a | - timeout |
|---|
| 381 | n/a | - address_family |
|---|
| 382 | n/a | - socket_type |
|---|
| 383 | n/a | - request_queue_size (only for stream sockets) |
|---|
| 384 | n/a | - allow_reuse_address |
|---|
| 385 | n/a | |
|---|
| 386 | n/a | Instance variables: |
|---|
| 387 | n/a | |
|---|
| 388 | n/a | - server_address |
|---|
| 389 | n/a | - RequestHandlerClass |
|---|
| 390 | n/a | - socket |
|---|
| 391 | n/a | |
|---|
| 392 | 1 | """ |
|---|
| 393 | n/a | |
|---|
| 394 | 1 | address_family = socket.AF_INET |
|---|
| 395 | n/a | |
|---|
| 396 | 1 | socket_type = socket.SOCK_STREAM |
|---|
| 397 | n/a | |
|---|
| 398 | 1 | request_queue_size = 5 |
|---|
| 399 | n/a | |
|---|
| 400 | 1 | allow_reuse_address = False |
|---|
| 401 | n/a | |
|---|
| 402 | 1 | def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True): |
|---|
| 403 | n/a | """Constructor. May be extended, do not override.""" |
|---|
| 404 | 98 | BaseServer.__init__(self, server_address, RequestHandlerClass) |
|---|
| 405 | 98 | self.socket = socket.socket(self.address_family, |
|---|
| 406 | 98 | self.socket_type) |
|---|
| 407 | 98 | if bind_and_activate: |
|---|
| 408 | 78 | self.server_bind() |
|---|
| 409 | 78 | self.server_activate() |
|---|
| 410 | n/a | |
|---|
| 411 | 1 | def server_bind(self): |
|---|
| 412 | n/a | """Called by constructor to bind the socket. |
|---|
| 413 | n/a | |
|---|
| 414 | n/a | May be overridden. |
|---|
| 415 | n/a | |
|---|
| 416 | n/a | """ |
|---|
| 417 | 98 | if self.allow_reuse_address: |
|---|
| 418 | 65 | self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
|---|
| 419 | 98 | self.socket.bind(self.server_address) |
|---|
| 420 | 98 | self.server_address = self.socket.getsockname() |
|---|
| 421 | n/a | |
|---|
| 422 | 1 | def server_activate(self): |
|---|
| 423 | n/a | """Called by constructor to activate the server. |
|---|
| 424 | n/a | |
|---|
| 425 | n/a | May be overridden. |
|---|
| 426 | n/a | |
|---|
| 427 | n/a | """ |
|---|
| 428 | 95 | self.socket.listen(self.request_queue_size) |
|---|
| 429 | n/a | |
|---|
| 430 | 1 | def server_close(self): |
|---|
| 431 | n/a | """Called to clean-up the server. |
|---|
| 432 | n/a | |
|---|
| 433 | n/a | May be overridden. |
|---|
| 434 | n/a | |
|---|
| 435 | n/a | """ |
|---|
| 436 | 30 | self.socket.close() |
|---|
| 437 | n/a | |
|---|
| 438 | 1 | def fileno(self): |
|---|
| 439 | n/a | """Return socket file number. |
|---|
| 440 | n/a | |
|---|
| 441 | n/a | Interface required by select(). |
|---|
| 442 | n/a | |
|---|
| 443 | n/a | """ |
|---|
| 444 | 225 | return self.socket.fileno() |
|---|
| 445 | n/a | |
|---|
| 446 | 1 | def get_request(self): |
|---|
| 447 | n/a | """Get the request and client address from the socket. |
|---|
| 448 | n/a | |
|---|
| 449 | n/a | May be overridden. |
|---|
| 450 | n/a | |
|---|
| 451 | n/a | """ |
|---|
| 452 | 59 | return self.socket.accept() |
|---|
| 453 | n/a | |
|---|
| 454 | 1 | def shutdown_request(self, request): |
|---|
| 455 | n/a | """Called to shutdown and close an individual request.""" |
|---|
| 456 | 100 | try: |
|---|
| 457 | n/a | #explicitly shutdown. socket.close() merely releases |
|---|
| 458 | n/a | #the socket and waits for GC to perform the actual close. |
|---|
| 459 | 100 | request.shutdown(socket.SHUT_WR) |
|---|
| 460 | 5 | except socket.error: |
|---|
| 461 | 5 | pass #some platforms may raise ENOTCONN here |
|---|
| 462 | 100 | self.close_request(request) |
|---|
| 463 | n/a | |
|---|
| 464 | 1 | def close_request(self, request): |
|---|
| 465 | n/a | """Called to clean up an individual request.""" |
|---|
| 466 | 106 | request.close() |
|---|
| 467 | n/a | |
|---|
| 468 | n/a | |
|---|
| 469 | 2 | class UDPServer(TCPServer): |
|---|
| 470 | n/a | |
|---|
| 471 | 1 | """UDP server class.""" |
|---|
| 472 | n/a | |
|---|
| 473 | 1 | allow_reuse_address = False |
|---|
| 474 | n/a | |
|---|
| 475 | 1 | socket_type = socket.SOCK_DGRAM |
|---|
| 476 | n/a | |
|---|
| 477 | 1 | max_packet_size = 8192 |
|---|
| 478 | n/a | |
|---|
| 479 | 1 | def get_request(self): |
|---|
| 480 | 9 | data, client_addr = self.socket.recvfrom(self.max_packet_size) |
|---|
| 481 | 9 | return (data, self.socket), client_addr |
|---|
| 482 | n/a | |
|---|
| 483 | 1 | def server_activate(self): |
|---|
| 484 | n/a | # No need to call listen() for UDP. |
|---|
| 485 | 3 | pass |
|---|
| 486 | n/a | |
|---|
| 487 | 1 | def shutdown_request(self, request): |
|---|
| 488 | n/a | # No need to shutdown anything. |
|---|
| 489 | 6 | self.close_request(request) |
|---|
| 490 | n/a | |
|---|
| 491 | 1 | def close_request(self, request): |
|---|
| 492 | n/a | # No need to close anything. |
|---|
| 493 | 9 | pass |
|---|
| 494 | n/a | |
|---|
| 495 | 2 | class ForkingMixIn: |
|---|
| 496 | n/a | |
|---|
| 497 | 1 | """Mix-in class to handle each request in a new process.""" |
|---|
| 498 | n/a | |
|---|
| 499 | 1 | timeout = 300 |
|---|
| 500 | 1 | active_children = None |
|---|
| 501 | 1 | max_children = 40 |
|---|
| 502 | n/a | |
|---|
| 503 | 1 | def collect_children(self): |
|---|
| 504 | n/a | """Internal routine to wait for children that have exited.""" |
|---|
| 505 | 9 | if self.active_children is None: return |
|---|
| 506 | 6 | while len(self.active_children) >= self.max_children: |
|---|
| 507 | n/a | # XXX: This will wait for any child process, not just ones |
|---|
| 508 | n/a | # spawned by this library. This could confuse other |
|---|
| 509 | n/a | # libraries that expect to be able to wait for their own |
|---|
| 510 | n/a | # children. |
|---|
| 511 | 0 | try: |
|---|
| 512 | 0 | pid, status = os.waitpid(0, 0) |
|---|
| 513 | 0 | except os.error: |
|---|
| 514 | 0 | pid = None |
|---|
| 515 | 0 | if pid not in self.active_children: continue |
|---|
| 516 | 0 | self.active_children.remove(pid) |
|---|
| 517 | n/a | |
|---|
| 518 | n/a | # XXX: This loop runs more system calls than it ought |
|---|
| 519 | n/a | # to. There should be a way to put the active_children into a |
|---|
| 520 | n/a | # process group and then use os.waitpid(-pgid) to wait for any |
|---|
| 521 | n/a | # of that set, but I couldn't find a way to allocate pgids |
|---|
| 522 | n/a | # that couldn't collide. |
|---|
| 523 | 12 | for child in self.active_children: |
|---|
| 524 | 6 | try: |
|---|
| 525 | 6 | pid, status = os.waitpid(child, os.WNOHANG) |
|---|
| 526 | 0 | except os.error: |
|---|
| 527 | 0 | pid = None |
|---|
| 528 | 6 | if not pid: continue |
|---|
| 529 | 3 | try: |
|---|
| 530 | 3 | self.active_children.remove(pid) |
|---|
| 531 | 0 | except ValueError, e: |
|---|
| 532 | 0 | raise ValueError('%s. x=%d and list=%r' % (e.message, pid, |
|---|
| 533 | 0 | self.active_children)) |
|---|
| 534 | n/a | |
|---|
| 535 | 1 | def handle_timeout(self): |
|---|
| 536 | n/a | """Wait for zombies after self.timeout seconds of inactivity. |
|---|
| 537 | n/a | |
|---|
| 538 | n/a | May be extended, do not override. |
|---|
| 539 | n/a | """ |
|---|
| 540 | 0 | self.collect_children() |
|---|
| 541 | n/a | |
|---|
| 542 | 1 | def process_request(self, request, client_address): |
|---|
| 543 | n/a | """Fork a new subprocess to process the request.""" |
|---|
| 544 | 9 | self.collect_children() |
|---|
| 545 | 9 | pid = os.fork() |
|---|
| 546 | 9 | if pid: |
|---|
| 547 | n/a | # Parent process |
|---|
| 548 | 9 | if self.active_children is None: |
|---|
| 549 | 3 | self.active_children = [] |
|---|
| 550 | 9 | self.active_children.append(pid) |
|---|
| 551 | 9 | self.close_request(request) #close handle in parent process |
|---|
| 552 | 9 | return |
|---|
| 553 | n/a | else: |
|---|
| 554 | n/a | # Child process. |
|---|
| 555 | n/a | # This must never return, hence os._exit()! |
|---|
| 556 | 0 | try: |
|---|
| 557 | 0 | self.finish_request(request, client_address) |
|---|
| 558 | 0 | self.shutdown_request(request) |
|---|
| 559 | 0 | os._exit(0) |
|---|
| 560 | 0 | except: |
|---|
| 561 | 0 | try: |
|---|
| 562 | 0 | self.handle_error(request, client_address) |
|---|
| 563 | 0 | self.shutdown_request(request) |
|---|
| 564 | n/a | finally: |
|---|
| 565 | 0 | os._exit(1) |
|---|
| 566 | n/a | |
|---|
| 567 | n/a | |
|---|
| 568 | 2 | class ThreadingMixIn: |
|---|
| 569 | 1 | """Mix-in class to handle each request in a new thread.""" |
|---|
| 570 | n/a | |
|---|
| 571 | n/a | # Decides how threads will act upon termination of the |
|---|
| 572 | n/a | # main process |
|---|
| 573 | 1 | daemon_threads = False |
|---|
| 574 | n/a | |
|---|
| 575 | 1 | def process_request_thread(self, request, client_address): |
|---|
| 576 | n/a | """Same as in BaseServer but as a thread. |
|---|
| 577 | n/a | |
|---|
| 578 | n/a | In addition, exception handling is done here. |
|---|
| 579 | n/a | |
|---|
| 580 | n/a | """ |
|---|
| 581 | 12 | try: |
|---|
| 582 | 12 | self.finish_request(request, client_address) |
|---|
| 583 | 12 | self.shutdown_request(request) |
|---|
| 584 | 0 | except: |
|---|
| 585 | 0 | self.handle_error(request, client_address) |
|---|
| 586 | 0 | self.shutdown_request(request) |
|---|
| 587 | n/a | |
|---|
| 588 | 1 | def process_request(self, request, client_address): |
|---|
| 589 | n/a | """Start a new thread to process the request.""" |
|---|
| 590 | 12 | t = threading.Thread(target = self.process_request_thread, |
|---|
| 591 | 12 | args = (request, client_address)) |
|---|
| 592 | 12 | if self.daemon_threads: |
|---|
| 593 | 0 | t.setDaemon (1) |
|---|
| 594 | 12 | t.start() |
|---|
| 595 | n/a | |
|---|
| 596 | n/a | |
|---|
| 597 | 2 | class ForkingUDPServer(ForkingMixIn, UDPServer): pass |
|---|
| 598 | 2 | class ForkingTCPServer(ForkingMixIn, TCPServer): pass |
|---|
| 599 | n/a | |
|---|
| 600 | 2 | class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass |
|---|
| 601 | 2 | class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass |
|---|
| 602 | n/a | |
|---|
| 603 | 1 | if hasattr(socket, 'AF_UNIX'): |
|---|
| 604 | n/a | |
|---|
| 605 | 2 | class UnixStreamServer(TCPServer): |
|---|
| 606 | 1 | address_family = socket.AF_UNIX |
|---|
| 607 | n/a | |
|---|
| 608 | 2 | class UnixDatagramServer(UDPServer): |
|---|
| 609 | 1 | address_family = socket.AF_UNIX |
|---|
| 610 | n/a | |
|---|
| 611 | 2 | class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass |
|---|
| 612 | n/a | |
|---|
| 613 | 2 | class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass |
|---|
| 614 | n/a | |
|---|
| 615 | 2 | class BaseRequestHandler: |
|---|
| 616 | n/a | |
|---|
| 617 | n/a | """Base class for request handler classes. |
|---|
| 618 | n/a | |
|---|
| 619 | n/a | This class is instantiated for each request to be handled. The |
|---|
| 620 | n/a | constructor sets the instance variables request, client_address |
|---|
| 621 | n/a | and server, and then calls the handle() method. To implement a |
|---|
| 622 | n/a | specific service, all you need to do is to derive a class which |
|---|
| 623 | n/a | defines a handle() method. |
|---|
| 624 | n/a | |
|---|
| 625 | n/a | The handle() method can find the request as self.request, the |
|---|
| 626 | n/a | client address as self.client_address, and the server (in case it |
|---|
| 627 | n/a | needs access to per-server information) as self.server. Since a |
|---|
| 628 | n/a | separate instance is created for each request, the handle() method |
|---|
| 629 | n/a | can define arbitrary other instance variariables. |
|---|
| 630 | n/a | |
|---|
| 631 | 1 | """ |
|---|
| 632 | n/a | |
|---|
| 633 | 1 | def __init__(self, request, client_address, server): |
|---|
| 634 | 109 | self.request = request |
|---|
| 635 | 109 | self.client_address = client_address |
|---|
| 636 | 109 | self.server = server |
|---|
| 637 | 109 | self.setup() |
|---|
| 638 | 109 | try: |
|---|
| 639 | 109 | self.handle() |
|---|
| 640 | n/a | finally: |
|---|
| 641 | 109 | self.finish() |
|---|
| 642 | n/a | |
|---|
| 643 | 1 | def setup(self): |
|---|
| 644 | 0 | pass |
|---|
| 645 | n/a | |
|---|
| 646 | 1 | def handle(self): |
|---|
| 647 | 0 | pass |
|---|
| 648 | n/a | |
|---|
| 649 | 1 | def finish(self): |
|---|
| 650 | 0 | pass |
|---|
| 651 | n/a | |
|---|
| 652 | n/a | |
|---|
| 653 | n/a | # The following two classes make it possible to use the same service |
|---|
| 654 | n/a | # class for stream or datagram servers. |
|---|
| 655 | n/a | # Each class sets up these instance variables: |
|---|
| 656 | n/a | # - rfile: a file object from which receives the request is read |
|---|
| 657 | n/a | # - wfile: a file object to which the reply is written |
|---|
| 658 | n/a | # When the handle() method returns, wfile is flushed properly |
|---|
| 659 | n/a | |
|---|
| 660 | n/a | |
|---|
| 661 | 2 | class StreamRequestHandler(BaseRequestHandler): |
|---|
| 662 | n/a | |
|---|
| 663 | 1 | """Define self.rfile and self.wfile for stream sockets.""" |
|---|
| 664 | n/a | |
|---|
| 665 | n/a | # Default buffer sizes for rfile, wfile. |
|---|
| 666 | n/a | # We default rfile to buffered because otherwise it could be |
|---|
| 667 | n/a | # really slow for large data (a getc() call per byte); we make |
|---|
| 668 | n/a | # wfile unbuffered because (a) often after a write() we want to |
|---|
| 669 | n/a | # read and we need to flush the line; (b) big writes to unbuffered |
|---|
| 670 | n/a | # files are typically optimized by stdio even when big reads |
|---|
| 671 | n/a | # aren't. |
|---|
| 672 | 1 | rbufsize = -1 |
|---|
| 673 | 1 | wbufsize = 0 |
|---|
| 674 | n/a | |
|---|
| 675 | n/a | # A timeout to apply to the request socket, if not None. |
|---|
| 676 | 1 | timeout = None |
|---|
| 677 | n/a | |
|---|
| 678 | n/a | # Disable nagle algoritm for this socket, if True. |
|---|
| 679 | n/a | # Use only when wbufsize != 0, to avoid small packets. |
|---|
| 680 | 1 | disable_nagle_algorithm = False |
|---|
| 681 | n/a | |
|---|
| 682 | 1 | def setup(self): |
|---|
| 683 | 100 | self.connection = self.request |
|---|
| 684 | 100 | if self.timeout is not None: |
|---|
| 685 | 2 | self.connection.settimeout(self.timeout) |
|---|
| 686 | 100 | if self.disable_nagle_algorithm: |
|---|
| 687 | 30 | self.connection.setsockopt(socket.IPPROTO_TCP, |
|---|
| 688 | 30 | socket.TCP_NODELAY, True) |
|---|
| 689 | 100 | self.rfile = self.connection.makefile('rb', self.rbufsize) |
|---|
| 690 | 100 | self.wfile = self.connection.makefile('wb', self.wbufsize) |
|---|
| 691 | n/a | |
|---|
| 692 | 1 | def finish(self): |
|---|
| 693 | 100 | if not self.wfile.closed: |
|---|
| 694 | 100 | self.wfile.flush() |
|---|
| 695 | 100 | self.wfile.close() |
|---|
| 696 | 100 | self.rfile.close() |
|---|
| 697 | n/a | |
|---|
| 698 | n/a | |
|---|
| 699 | 2 | class DatagramRequestHandler(BaseRequestHandler): |
|---|
| 700 | n/a | |
|---|
| 701 | n/a | # XXX Regrettably, I cannot get this working on Linux; |
|---|
| 702 | n/a | # s.recvfrom() doesn't return a meaningful client address. |
|---|
| 703 | n/a | |
|---|
| 704 | 1 | """Define self.rfile and self.wfile for datagram sockets.""" |
|---|
| 705 | n/a | |
|---|
| 706 | 1 | def setup(self): |
|---|
| 707 | 6 | try: |
|---|
| 708 | 6 | from cStringIO import StringIO |
|---|
| 709 | 0 | except ImportError: |
|---|
| 710 | 0 | from StringIO import StringIO |
|---|
| 711 | 6 | self.packet, self.socket = self.request |
|---|
| 712 | 6 | self.rfile = StringIO(self.packet) |
|---|
| 713 | 6 | self.wfile = StringIO() |
|---|
| 714 | n/a | |
|---|
| 715 | 1 | def finish(self): |
|---|
| 716 | 6 | self.socket.sendto(self.wfile.getvalue(), self.client_address) |
|---|