home *** CD-ROM | disk | FTP | other *** search
/ PC World 2001 April / PCWorld_2001-04_cd.bin / Software / TemaCD / webclean / !!!python!!! / BeOpen-Python-2.0.exe / ASYNCORE.PY < prev    next >
Encoding:
Text File  |  2000-09-28  |  15.9 KB  |  516 lines

  1. # -*- Mode: Python -*-
  2. #   Id: asyncore.py,v 2.51 2000/09/07 22:29:26 rushing Exp 
  3. #   Author: Sam Rushing <rushing@nightmare.com>
  4.  
  5. # ======================================================================
  6. # Copyright 1996 by Sam Rushing
  7. #                         All Rights Reserved
  8. # Permission to use, copy, modify, and distribute this software and
  9. # its documentation for any purpose and without fee is hereby
  10. # granted, provided that the above copyright notice appear in all
  11. # copies and that both that copyright notice and this permission
  12. # notice appear in supporting documentation, and that the name of Sam
  13. # Rushing not be used in advertising or publicity pertaining to
  14. # distribution of the software without specific, written prior
  15. # permission.
  16. # SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
  17. # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
  18. # NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR
  19. # CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  20. # OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  21. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  22. # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  23. # ======================================================================
  24.  
  25. """Basic infrastructure for asynchronous socket service clients and servers.
  26.  
  27. There are only two ways to have a program on a single processor do "more
  28. than one thing at a time".  Multi-threaded programming is the simplest and 
  29. most popular way to do it, but there is another very different technique,
  30. that lets you have nearly all the advantages of multi-threading, without
  31. actually using multiple threads. it's really only practical if your program
  32. is largely I/O bound. If your program is CPU bound, then pre-emptive
  33. scheduled threads are probably what you really need. Network servers are
  34. rarely CPU-bound, however. 
  35.  
  36. If your operating system supports the select() system call in its I/O 
  37. library (and nearly all do), then you can use it to juggle multiple
  38. communication channels at once; doing other work while your I/O is taking
  39. place in the "background."  Although this strategy can seem strange and
  40. complex, especially at first, it is in many ways easier to understand and
  41. control than multi-threaded programming. The module documented here solves
  42. many of the difficult problems for you, making the task of building
  43. sophisticated high-performance network servers and clients a snap. 
  44. """
  45.  
  46. import exceptions
  47. import select
  48. import socket
  49. import string
  50. import sys
  51.  
  52. import os
  53. if os.name == 'nt':
  54.     EWOULDBLOCK = 10035
  55.     EINPROGRESS = 10036
  56.     EALREADY    = 10037
  57.     ECONNRESET  = 10054
  58.     ENOTCONN    = 10057
  59.     ESHUTDOWN   = 10058
  60. else:
  61.     from errno import EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, ENOTCONN, ESHUTDOWN
  62.  
  63. try:
  64.     socket_map
  65. except NameError:
  66.     socket_map = {}
  67.  
  68. class ExitNow (exceptions.Exception):
  69.     pass
  70.  
  71. DEBUG = 0
  72.  
  73. def poll (timeout=0.0, map=None):
  74.     global DEBUG
  75.     if map is None:
  76.         map = socket_map
  77.     if map:
  78.         r = []; w = []; e = []
  79.         for fd, obj in map.items():
  80.             if obj.readable():
  81.                 r.append (fd)
  82.             if obj.writable():
  83.                 w.append (fd)
  84.         r,w,e = select.select (r,w,e, timeout)
  85.  
  86.         if DEBUG:
  87.             print r,w,e
  88.  
  89.         for fd in r:
  90.             try:
  91.                 obj = map[fd]
  92.                 try:
  93.                     obj.handle_read_event()
  94.                 except ExitNow:
  95.                     raise ExitNow
  96.                 except:
  97.                     obj.handle_error()
  98.             except KeyError:
  99.                 pass
  100.  
  101.         for fd in w:
  102.             try:
  103.                 obj = map[fd]
  104.                 try:
  105.                     obj.handle_write_event()
  106.                 except ExitNow:
  107.                     raise ExitNow
  108.                 except:
  109.                     obj.handle_error()
  110.             except KeyError:
  111.                 pass
  112.  
  113. def poll2 (timeout=0.0, map=None):
  114.     import poll
  115.     if map is None:
  116.         map=socket_map
  117.     # timeout is in milliseconds
  118.     timeout = int(timeout*1000)
  119.     if map:
  120.         l = []
  121.         for fd, obj in map.items():
  122.             flags = 0
  123.             if obj.readable():
  124.                 flags = poll.POLLIN
  125.             if obj.writable():
  126.                 flags = flags | poll.POLLOUT
  127.             if flags:
  128.                 l.append ((fd, flags))
  129.         r = poll.poll (l, timeout)
  130.         for fd, flags in r:
  131.             try:
  132.                 obj = map[fd]
  133.                 try:
  134.                     if (flags  & poll.POLLIN):
  135.                         obj.handle_read_event()
  136.                     if (flags & poll.POLLOUT):
  137.                         obj.handle_write_event()
  138.                 except ExitNow:
  139.                     raise ExitNow
  140.                 except:
  141.                     obj.handle_error()
  142.             except KeyError:
  143.                 pass
  144.  
  145. def loop (timeout=30.0, use_poll=0, map=None):
  146.  
  147.     if use_poll:
  148.         poll_fun = poll2
  149.     else:
  150.         poll_fun = poll
  151.  
  152.         if map is None:
  153.             map=socket_map
  154.  
  155.     while map:
  156.         poll_fun (timeout, map)
  157.  
  158. class dispatcher:
  159.     debug = 0
  160.     connected = 0
  161.     accepting = 0
  162.     closing = 0
  163.     addr = None
  164.  
  165.     def __init__ (self, sock=None, map=None):
  166.         if sock:
  167.             self.set_socket (sock, map)
  168.             # I think it should inherit this anyway
  169.             self.socket.setblocking (0)
  170.             self.connected = 1
  171.  
  172.     def __repr__ (self):
  173.         try:
  174.             status = []
  175.             if self.accepting and self.addr:
  176.                 status.append ('listening')
  177.             elif self.connected:
  178.                 status.append ('connected')
  179.             if self.addr:
  180.                 status.append ('%s:%d' % self.addr)
  181.             return '<%s %s at %x>' % (
  182.                 self.__class__.__name__,
  183.                 string.join (status, ' '),
  184.                 id(self)
  185.                 )
  186.         except:
  187.             try:
  188.                 ar = repr(self.addr)
  189.             except:
  190.                 ar = 'no self.addr!'
  191.                 
  192.             return '<__repr__ (self) failed for object at %x (addr=%s)>' % (id(self),ar)
  193.  
  194.     def add_channel (self, map=None):
  195.         #self.log_info ('adding channel %s' % self)
  196.         if map is None:
  197.             map=socket_map
  198.         map [self._fileno] = self
  199.  
  200.     def del_channel (self, map=None):
  201.         fd = self._fileno
  202.         if map is None:
  203.             map=socket_map
  204.         if map.has_key (fd):
  205.             #self.log_info ('closing channel %d:%s' % (fd, self))
  206.             del map [fd]
  207.  
  208.     def create_socket (self, family, type):
  209.         self.family_and_type = family, type
  210.         self.socket = socket.socket (family, type)
  211.         self.socket.setblocking(0)
  212.         self._fileno = self.socket.fileno()
  213.         self.add_channel()
  214.  
  215.     def set_socket (self, sock, map=None):
  216.         self.__dict__['socket'] = sock
  217.         self._fileno = sock.fileno()
  218.         self.add_channel (map)
  219.  
  220.     def set_reuse_addr (self):
  221.         # try to re-use a server port if possible
  222.         try:
  223.             self.socket.setsockopt (
  224.                 socket.SOL_SOCKET, socket.SO_REUSEADDR,
  225.                 self.socket.getsockopt (socket.SOL_SOCKET, socket.SO_REUSEADDR) | 1
  226.                 )
  227.         except:
  228.             pass
  229.  
  230.     # ==================================================
  231.     # predicates for select()
  232.     # these are used as filters for the lists of sockets
  233.     # to pass to select().
  234.     # ==================================================
  235.  
  236.     def readable (self):
  237.         return 1
  238.  
  239.     if os.name == 'mac':
  240.         # The macintosh will select a listening socket for
  241.         # write if you let it.  What might this mean?
  242.         def writable (self):
  243.             return not self.accepting
  244.     else:
  245.         def writable (self):
  246.             return 1
  247.  
  248.     # ==================================================
  249.     # socket object methods.
  250.     # ==================================================
  251.  
  252.     def listen (self, num):
  253.         self.accepting = 1
  254.         if os.name == 'nt' and num > 5:
  255.             num = 1
  256.         return self.socket.listen (num)
  257.  
  258.     def bind (self, addr):
  259.         self.addr = addr
  260.         return self.socket.bind (addr)
  261.  
  262.     def connect (self, address):
  263.         self.connected = 0
  264.         try:
  265.             self.socket.connect (address)
  266.         except socket.error, why:
  267.             if why[0] in (EINPROGRESS, EALREADY, EWOULDBLOCK):
  268.                 return
  269.             else:
  270.                 raise socket.error, why
  271.         self.connected = 1
  272.         self.handle_connect()
  273.  
  274.     def accept (self):
  275.         try:
  276.             conn, addr = self.socket.accept()
  277.             return conn, addr
  278.         except socket.error, why:
  279.             if why[0] == EWOULDBLOCK:
  280.                 pass
  281.             else:
  282.                 raise socket.error, why
  283.  
  284.     def send (self, data):
  285.         try:
  286.             result = self.socket.send (data)
  287.             return result
  288.         except socket.error, why:
  289.             if why[0] == EWOULDBLOCK:
  290.                 return 0
  291.             else:
  292.                 raise socket.error, why
  293.             return 0
  294.  
  295.     def recv (self, buffer_size):
  296.         try:
  297.             data = self.socket.recv (buffer_size)
  298.             if not data:
  299.                 # a closed connection is indicated by signaling
  300.                 # a read condition, and having recv() return 0.
  301.                 self.handle_close()
  302.                 return ''
  303.             else:
  304.                 return data
  305.         except socket.error, why:
  306.             # winsock sometimes throws ENOTCONN
  307.             if why[0] in [ECONNRESET, ENOTCONN, ESHUTDOWN]:
  308.                 self.handle_close()
  309.                 return ''
  310.             else:
  311.                 raise socket.error, why
  312.  
  313.     def close (self):
  314.         self.del_channel()
  315.         self.socket.close()
  316.  
  317.     # cheap inheritance, used to pass all other attribute
  318.     # references to the underlying socket object.
  319.     def __getattr__ (self, attr):
  320.         return getattr (self.socket, attr)
  321.  
  322.     # log and log_info maybe overriden to provide more sophisitcated
  323.     # logging and warning methods. In general, log is for 'hit' logging
  324.     # and 'log_info' is for informational, warning and error logging. 
  325.  
  326.     def log (self, message):
  327.         sys.stderr.write ('log: %s\n' % str(message))
  328.  
  329.     def log_info (self, message, type='info'):
  330.         if __debug__ or type != 'info':
  331.             print '%s: %s' % (type, message)
  332.  
  333.     def handle_read_event (self):
  334.         if self.accepting:
  335.             # for an accepting socket, getting a read implies
  336.             # that we are connected
  337.             if not self.connected:
  338.                 self.connected = 1
  339.             self.handle_accept()
  340.         elif not self.connected:
  341.             self.handle_connect()
  342.             self.connected = 1
  343.             self.handle_read()
  344.         else:
  345.             self.handle_read()
  346.  
  347.     def handle_write_event (self):
  348.         # getting a write implies that we are connected
  349.         if not self.connected:
  350.             self.handle_connect()
  351.             self.connected = 1
  352.         self.handle_write()
  353.  
  354.     def handle_expt_event (self):
  355.         self.handle_expt()
  356.  
  357.     def handle_error (self):
  358.         (file,fun,line), t, v, tbinfo = compact_traceback()
  359.  
  360.         # sometimes a user repr method will crash.
  361.         try:
  362.             self_repr = repr (self)
  363.         except:
  364.             self_repr = '<__repr__ (self) failed for object at %0x>' % id(self)
  365.  
  366.         self.log_info (
  367.             'uncaptured python exception, closing channel %s (%s:%s %s)' % (
  368.                 self_repr,
  369.                 t,
  370.                 v,
  371.                 tbinfo
  372.                 ),
  373.             'error'
  374.             )
  375.         self.close()
  376.  
  377.     def handle_expt (self):
  378.         self.log_info ('unhandled exception', 'warning')
  379.  
  380.     def handle_read (self):
  381.         self.log_info ('unhandled read event', 'warning')
  382.  
  383.     def handle_write (self):
  384.         self.log_info ('unhandled write event', 'warning')
  385.  
  386.     def handle_connect (self):
  387.         self.log_info ('unhandled connect event', 'warning')
  388.  
  389.     def handle_accept (self):
  390.         self.log_info ('unhandled accept event', 'warning')
  391.  
  392.     def handle_close (self):
  393.         self.log_info ('unhandled close event', 'warning')
  394.         self.close()
  395.  
  396. # ---------------------------------------------------------------------------
  397. # adds simple buffered output capability, useful for simple clients.
  398. # [for more sophisticated usage use asynchat.async_chat]
  399. # ---------------------------------------------------------------------------
  400.  
  401. class dispatcher_with_send (dispatcher):
  402.     def __init__ (self, sock=None):
  403.         dispatcher.__init__ (self, sock)
  404.         self.out_buffer = ''
  405.  
  406.     def initiate_send (self):
  407.         num_sent = 0
  408.         num_sent = dispatcher.send (self, self.out_buffer[:512])
  409.         self.out_buffer = self.out_buffer[num_sent:]
  410.  
  411.     def handle_write (self):
  412.         self.initiate_send()
  413.  
  414.     def writable (self):
  415.         return (not self.connected) or len(self.out_buffer)
  416.  
  417.     def send (self, data):
  418.         if self.debug:
  419.             self.log_info ('sending %s' % repr(data))
  420.         self.out_buffer = self.out_buffer + data
  421.         self.initiate_send()
  422.  
  423. # ---------------------------------------------------------------------------
  424. # used for debugging.
  425. # ---------------------------------------------------------------------------
  426.  
  427. def compact_traceback ():
  428.     t,v,tb = sys.exc_info()
  429.     tbinfo = []
  430.     while 1:
  431.         tbinfo.append ((
  432.             tb.tb_frame.f_code.co_filename,
  433.             tb.tb_frame.f_code.co_name,             
  434.             str(tb.tb_lineno)
  435.             ))
  436.         tb = tb.tb_next
  437.         if not tb:
  438.             break
  439.  
  440.     # just to be safe
  441.     del tb
  442.  
  443.     file, function, line = tbinfo[-1]
  444.     info = '[' + string.join (
  445.         map (
  446.             lambda x: string.join (x, '|'),
  447.             tbinfo
  448.             ),
  449.         '] ['
  450.         ) + ']'
  451.     return (file, function, line), t, v, info
  452.  
  453. def close_all (map=None):
  454.     if map is None:
  455.         map=socket_map
  456.     for x in map.values():
  457.         x.socket.close()
  458.     map.clear()
  459.  
  460. # Asynchronous File I/O:
  461. #
  462. # After a little research (reading man pages on various unixen, and
  463. # digging through the linux kernel), I've determined that select()
  464. # isn't meant for doing doing asynchronous file i/o.
  465. # Heartening, though - reading linux/mm/filemap.c shows that linux
  466. # supports asynchronous read-ahead.  So _MOST_ of the time, the data
  467. # will be sitting in memory for us already when we go to read it.
  468. #
  469. # What other OS's (besides NT) support async file i/o?  [VMS?]
  470. #
  471. # Regardless, this is useful for pipes, and stdin/stdout...
  472.  
  473. import os
  474. if os.name == 'posix':
  475.     import fcntl
  476.     import FCNTL
  477.  
  478.     class file_wrapper:
  479.         # here we override just enough to make a file
  480.         # look like a socket for the purposes of asyncore.
  481.         def __init__ (self, fd):
  482.             self.fd = fd
  483.  
  484.         def recv (self, *args):
  485.             return apply (os.read, (self.fd,)+args)
  486.  
  487.         def send (self, *args):
  488.             return apply (os.write, (self.fd,)+args)
  489.  
  490.         read = recv
  491.         write = send
  492.  
  493.         def close (self):
  494.             return os.close (self.fd)
  495.  
  496.         def fileno (self):
  497.             return self.fd
  498.  
  499.     class file_dispatcher (dispatcher):
  500.         def __init__ (self, fd):
  501.             dispatcher.__init__ (self)
  502.             self.connected = 1
  503.             # set it to non-blocking mode
  504.             flags = fcntl.fcntl (fd, FCNTL.F_GETFL, 0)
  505.             flags = flags | FCNTL.O_NONBLOCK
  506.             fcntl.fcntl (fd, FCNTL.F_SETFL, flags)
  507.             self.set_file (fd)
  508.  
  509.         def set_file (self, fd):
  510.             self._fileno = fd
  511.             self.socket = file_wrapper (fd)
  512.             self.add_channel()
  513.