Vega strike Python Modules doc  0.5.1
Documentation of the " Modules " folder of Vega strike
 All Data Structures Namespaces Files Functions Variables
SocketServer.py
Go to the documentation of this file.
1 """Generic socket server classes.
2 
3 This module tries to capture the various aspects of defining a server:
4 
5 For socket-based servers:
6 
7 - address family:
8  - AF_INET{,6}: IP (Internet Protocol) sockets (default)
9  - AF_UNIX: Unix domain sockets
10  - others, e.g. AF_DECNET are conceivable (see <socket.h>
11 - socket type:
12  - SOCK_STREAM (reliable stream, e.g. TCP)
13  - SOCK_DGRAM (datagrams, e.g. UDP)
14 
15 For request-based servers (including socket-based):
16 
17 - client address verification before further looking at the request
18  (This is actually a hook for any processing that needs to look
19  at the request before anything else, e.g. logging)
20 - how to handle multiple requests:
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)
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
27 save some typing. (There's also the issue that a deep class hierarchy
28 slows down method lookups.)
29 
30 There are five classes in an inheritance diagram, four of which represent
31 synchronous servers of four types:
32 
33  +------------+
34  | BaseServer |
35  +------------+
36  |
37  v
38  +-----------+ +------------------+
39  | TCPServer |------->| UnixStreamServer |
40  +-----------+ +------------------+
41  |
42  v
43  +-----------+ +--------------------+
44  | UDPServer |------->| UnixDatagramServer |
45  +-----------+ +--------------------+
46 
47 Note that UnixDatagramServer derives from UDPServer, not from
48 UnixStreamServer -- the only difference between an IP and a Unix
49 stream server is the address family, which is simply repeated in both
50 unix server classes.
51 
52 Forking and threading versions of each type of server can be created
53 using the ForkingServer and ThreadingServer mix-in classes. For
54 instance, a threading UDP server class is created as follows:
55 
56  class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
57 
58 The Mix-in class must come first, since it overrides a method defined
59 in UDPServer!
60 
61 To implement a service, you must derive a class from
62 BaseRequestHandler and redefine its handle() method. You can then run
63 various versions of the service by combining one of the server classes
64 with your request handler class.
65 
66 The request handler class must be different for datagram or stream
67 services. This can be hidden by using the mix-in request handler
68 classes StreamRequestHandler or DatagramRequestHandler.
69 
70 Of course, you still have to use your head!
71 
72 For instance, it makes no sense to use a forking server if the service
73 contains state in memory that can be modified by requests (since the
74 modifications in the child process would never reach the initial state
75 kept in the parent process and passed to each child). In this case,
76 you can use a threading server, but you will probably have to use
77 locks to avoid two requests that come in nearly simultaneous to apply
78 conflicting changes to the server state.
79 
80 On the other hand, if you are building e.g. an HTTP server, where all
81 data is stored externally (e.g. in the file system), a synchronous
82 class will essentially render the service "deaf" while one request is
83 being handled -- which may be for a very long time if a client is slow
84 to reqd all the data it has requested. Here a threading or forking
85 server is appropriate.
86 
87 In some cases, it may be appropriate to process part of a request
88 synchronously, but to finish processing in a forked child depending on
89 the request data. This can be implemented by using a synchronous
90 server and doing an explicit fork in the request handler class
91 handle() method.
92 
93 Another approach to handling multiple simultaneous requests in an
94 environment that supports neither threads nor fork (or where these are
95 too expensive or inappropriate for the service) is to maintain an
96 explicit table of partially finished requests and to use select() to
97 decide which request to work on next (or whether to handle a new
98 incoming request). This is particularly important for stream services
99 where each client can potentially be connected for a long time (if
100 threads or subprocesses cannot be used).
101 
102 Future work:
103 - Standard classes for Sun RPC (which uses either UDP or TCP)
104 - Standard mix-in classes to implement various authentication
105  and encryption schemes
106 - Standard framework for select-based multiplexing
107 
108 XXX Open problems:
109 - What to do with out-of-band data?
110 
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 
119 """
120 
121 # Author of the BaseServer patch: Luke Kenneth Casson Leighton
122 
123 # XXX Warning!
124 # There is a test suite for this module, but it cannot be run by the
125 # standard regression test.
126 # To run it manually, run Lib/test/test_socketserver.py.
127 
128 __version__ = "0.4"
129 
130 
131 import socket
132 import sys
133 import os
134 
135 __all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer",
136  "ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler",
137  "StreamRequestHandler","DatagramRequestHandler",
138  "ThreadingMixIn", "ForkingMixIn"]
139 if hasattr(socket, "AF_UNIX"):
140  __all__.extend(["UnixStreamServer","UnixDatagramServer",
141  "ThreadingUnixStreamServer",
142  "ThreadingUnixDatagramServer"])
143 
145 
146  """Base class for server classes.
147 
148  Methods for the caller:
149 
150  - __init__(server_address, RequestHandlerClass)
151  - serve_forever()
152  - handle_request() # if you do not use serve_forever()
153  - fileno() -> int # for select()
154 
155  Methods that may be overridden:
156 
157  - server_bind()
158  - server_activate()
159  - get_request() -> request, client_address
160  - verify_request(request, client_address)
161  - server_close()
162  - process_request(request, client_address)
163  - close_request(request)
164  - handle_error()
165 
166  Methods for derived classes:
167 
168  - finish_request(request, client_address)
169 
170  Class variables that may be overridden by derived classes or
171  instances:
172 
173  - address_family
174  - socket_type
175  - reuse_address
176 
177  Instance variables:
178 
179  - RequestHandlerClass
180  - socket
181 
182  """
183 
184  def __init__(self, server_address, RequestHandlerClass):
185  """Constructor. May be extended, do not override."""
186  self.server_address = server_address
187  self.RequestHandlerClass = RequestHandlerClass
188 
189  def server_activate(self):
190  """Called by constructor to activate the server.
191 
192  May be overridden.
193 
194  """
195  pass
196 
197  def serve_forever(self):
198  """Handle one request at a time until doomsday."""
199  while 1:
200  self.handle_request()
201 
202  # The distinction between handling, getting, processing and
203  # finishing a request is fairly arbitrary. Remember:
204  #
205  # - handle_request() is the top-level call. It calls
206  # get_request(), verify_request() and process_request()
207  # - get_request() is different for stream or datagram sockets
208  # - process_request() is the place that may fork a new process
209  # or create a new thread to finish the request
210  # - finish_request() instantiates the request handler class;
211  # this constructor will handle the request all by itself
212 
213  def handle_request(self):
214  """Handle one request, possibly blocking."""
215  try:
216  request, client_address = self.get_request()
217  except socket.error:
218  return
219  if self.verify_request(request, client_address):
220  try:
221  self.process_request(request, client_address)
222  except:
223  self.handle_error(request, client_address)
224  self.close_request(request)
225 
226  def verify_request(self, request, client_address):
227  """Verify the request. May be overridden.
228 
229  Return true if we should proceed with this request.
230 
231  """
232  return 1
233 
234  def process_request(self, request, client_address):
235  """Call finish_request.
236 
237  Overridden by ForkingMixIn and ThreadingMixIn.
238 
239  """
240  self.finish_request(request, client_address)
241  self.close_request(request)
242 
243  def server_close(self):
244  """Called to clean-up the server.
245 
246  May be overridden.
247 
248  """
249  pass
250 
251  def finish_request(self, request, client_address):
252  """Finish one request by instantiating RequestHandlerClass."""
253  self.RequestHandlerClass(request, client_address, self)
254 
255  def close_request(self, request):
256  """Called to clean up an individual request."""
257  pass
258 
259  def handle_error(self, request, client_address):
260  """Handle an error gracefully. May be overridden.
261 
262  The default is to print a traceback and continue.
263 
264  """
265  print '-'*40
266  print 'Exception happened during processing of request from',
267  print client_address
268  import traceback
269  traceback.print_exc() # XXX But this goes to stderr!
270  print '-'*40
271 
272 
274 
275  """Base class for various socket-based server classes.
276 
277  Defaults to synchronous IP stream (i.e., TCP).
278 
279  Methods for the caller:
280 
281  - __init__(server_address, RequestHandlerClass)
282  - serve_forever()
283  - handle_request() # if you don't use serve_forever()
284  - fileno() -> int # for select()
285 
286  Methods that may be overridden:
287 
288  - server_bind()
289  - server_activate()
290  - get_request() -> request, client_address
291  - verify_request(request, client_address)
292  - process_request(request, client_address)
293  - close_request(request)
294  - handle_error()
295 
296  Methods for derived classes:
297 
298  - finish_request(request, client_address)
299 
300  Class variables that may be overridden by derived classes or
301  instances:
302 
303  - address_family
304  - socket_type
305  - request_queue_size (only for stream sockets)
306  - reuse_address
307 
308  Instance variables:
309 
310  - server_address
311  - RequestHandlerClass
312  - socket
313 
314  """
315 
316  address_family = socket.AF_INET
317 
318  socket_type = socket.SOCK_STREAM
319 
320  request_queue_size = 5
321 
322  allow_reuse_address = 0
323 
324  def __init__(self, server_address, RequestHandlerClass):
325  """Constructor. May be extended, do not override."""
326  BaseServer.__init__(self, server_address, RequestHandlerClass)
328  self.socket_type)
329  self.server_bind()
330  self.server_activate()
331 
332  def server_bind(self):
333  """Called by constructor to bind the socket.
334 
335  May be overridden.
336 
337  """
338  if self.allow_reuse_address:
339  self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
340  self.socket.bind(self.server_address)
341 
342  def server_activate(self):
343  """Called by constructor to activate the server.
344 
345  May be overridden.
346 
347  """
348  self.socket.listen(self.request_queue_size)
349 
350  def server_close(self):
351  """Called to clean-up the server.
352 
353  May be overridden.
354 
355  """
356  self.socket.close()
357 
358  def fileno(self):
359  """Return socket file number.
360 
361  Interface required by select().
362 
363  """
364  return self.socket.fileno()
365 
366  def get_request(self):
367  """Get the request and client address from the socket.
368 
369  May be overridden.
370 
371  """
372  return self.socket.accept()
373 
374  def close_request(self, request):
375  """Called to clean up an individual request."""
376  request.close()
377 
378 
380 
381  """UDP server class."""
382 
383  allow_reuse_address = 0
384 
385  socket_type = socket.SOCK_DGRAM
386 
387  max_packet_size = 8192
388 
389  def get_request(self):
390  data, client_addr = self.socket.recvfrom(self.max_packet_size)
391  return (data, self.socket), client_addr
392 
393  def server_activate(self):
394  # No need to call listen() for UDP.
395  pass
396 
397  def close_request(self, request):
398  # No need to close anything.
399  pass
400 
401 class ForkingMixIn:
402 
403  """Mix-in class to handle each request in a new process."""
404 
405  active_children = None
406  max_children = 40
407 
408  def collect_children(self):
409  """Internal routine to wait for died children."""
410  while self.active_children:
411  if len(self.active_children) < self.max_children:
412  options = os.WNOHANG
413  else:
414  # If the maximum number of children are already
415  # running, block while waiting for a child to exit
416  options = 0
417  try:
418  pid, status = os.waitpid(0, options)
419  except os.error:
420  pid = None
421  if not pid: break
422  self.active_children.remove(pid)
423 
424  def process_request(self, request, client_address):
425  """Fork a new subprocess to process the request."""
426  self.collect_children()
427  pid = os.fork()
428  if pid:
429  # Parent process
430  if self.active_children is None:
431  self.active_children = []
432  self.active_children.append(pid)
433  self.close_request(request)
434  return
435  else:
436  # Child process.
437  # This must never return, hence os._exit()!
438  try:
439  self.finish_request(request, client_address)
440  os._exit(0)
441  except:
442  try:
443  self.handle_error(request, client_address)
444  finally:
445  os._exit(1)
446 
447 
449  """Mix-in class to handle each request in a new thread."""
450 
451  def process_request_thread(self, request, client_address):
452  """Same as in BaseServer but as a thread.
453 
454  In addition, exception handling is done here.
455 
456  """
457  try:
458  self.finish_request(request, client_address)
459  self.close_request(request)
460  except:
461  self.handle_error(request, client_address)
462  self.close_request(request)
463 
464  def process_request(self, request, client_address):
465  """Start a new thread to process the request."""
466  import threading
467  t = threading.Thread(target = self.process_request_thread,
468  args = (request, client_address))
469  t.start()
470 
471 
474 
477 
478 if hasattr(socket, 'AF_UNIX'):
479 
481  address_family = socket.AF_UNIX
482 
484  address_family = socket.AF_UNIX
485 
487 
489 
491 
492  """Base class for request handler classes.
493 
494  This class is instantiated for each request to be handled. The
495  constructor sets the instance variables request, client_address
496  and server, and then calls the handle() method. To implement a
497  specific service, all you need to do is to derive a class which
498  defines a handle() method.
499 
500  The handle() method can find the request as self.request, the
501  client address as self.client_address, and the server (in case it
502  needs access to per-server information) as self.server. Since a
503  separate instance is created for each request, the handle() method
504  can define arbitrary other instance variariables.
505 
506  """
507 
508  def __init__(self, request, client_address, server):
509  self.request = request
510  self.client_address = client_address
511  self.server = server
512  try:
513  self.setup()
514  self.handle()
515  self.finish()
516  finally:
517  sys.exc_traceback = None # Help garbage collection
518 
519  def setup(self):
520  pass
521 
522  def handle(self):
523  pass
524 
525  def finish(self):
526  pass
527 
528 
529 # The following two classes make it possible to use the same service
530 # class for stream or datagram servers.
531 # Each class sets up these instance variables:
532 # - rfile: a file object from which receives the request is read
533 # - wfile: a file object to which the reply is written
534 # When the handle() method returns, wfile is flushed properly
535 
536 
537 class StreamRequestHandler(BaseRequestHandler):
538 
539  """Define self.rfile and self.wfile for stream sockets."""
540 
541  # Default buffer sizes for rfile, wfile.
542  # We default rfile to buffered because otherwise it could be
543  # really slow for large data (a getc() call per byte); we make
544  # wfile unbuffered because (a) often after a write() we want to
545  # read and we need to flush the line; (b) big writes to unbuffered
546  # files are typically optimized by stdio even when big reads
547  # aren't.
548  rbufsize = -1
549  wbufsize = 0
550 
551  def setup(self):
552  self.connection = self.request
553  self.rfile = self.connection.makefile('rb', self.rbufsize)
554  self.wfile = self.connection.makefile('wb', self.wbufsize)
555 
556  def finish(self):
557  self.wfile.flush()
558  self.wfile.close()
559  self.rfile.close()
560 
561 
563 
564  # XXX Regrettably, I cannot get this working on Linux;
565  # s.recvfrom() doesn't return a meaningful client address.
566 
567  """Define self.rfile and self.wfile for datagram sockets."""
568 
569  def setup(self):
570  import StringIO
571  self.packet, self.socket = self.request
572  self.rfile = StringIO.StringIO(self.packet)
573  self.wfile = StringIO.StringIO(self.packet)
574 
575  def finish(self):
576  self.socket.sendto(self.wfile.getvalue(), self.client_address)