home *** CD-ROM | disk | FTP | other *** search
/ linuxmafia.com 2016 / linuxmafia.com.tar / linuxmafia.com / pub / palmos / pippy-0.6beta-src.tar.gz / pippy-0.6beta-src.tar / pippy-0.6beta-src / src / Lib / asyncore.py < prev    next >
Text File  |  2000-12-21  |  12KB  |  475 lines

  1. # -*- Mode: Python; tab-width: 4 -*-
  2. #   Id: asyncore.py,v 2.40 1999/05/27 04:08:25 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 select
  47. import socket
  48. import string
  49. import sys
  50.  
  51. import os
  52. if os.name == 'nt':
  53.     EWOULDBLOCK    = 10035
  54.     EINPROGRESS    = 10036
  55.     EALREADY    = 10037
  56.     ECONNRESET  = 10054
  57.     ENOTCONN    = 10057
  58.     ESHUTDOWN    = 10058
  59. else:
  60.     from errno import EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, ENOTCONN, ESHUTDOWN
  61.  
  62. socket_map = {}
  63.  
  64. def poll (timeout=0.0):
  65.     if socket_map:
  66.         r = []; w = []; e = []
  67.         for s in socket_map.keys():
  68.             if s.readable():
  69.                 r.append (s)
  70.             if s.writable():
  71.                 w.append (s)
  72.  
  73.         (r,w,e) = select.select (r,w,e, timeout)
  74.  
  75.         for x in r:
  76.             try:
  77.                 x.handle_read_event()
  78.             except:
  79.                 x.handle_error()
  80.         for x in w:
  81.             try:
  82.                 x.handle_write_event()
  83.             except:
  84.                 x.handle_error()
  85.  
  86. def poll2 (timeout=0.0):
  87.     import poll
  88.     # timeout is in milliseconds
  89.     timeout = int(timeout*1000)
  90.     if socket_map:
  91.         fd_map = {}
  92.         for s in socket_map.keys():
  93.             fd_map[s.fileno()] = s
  94.         l = []
  95.         for fd, s in fd_map.items():
  96.             flags = 0
  97.             if s.readable():
  98.                 flags = poll.POLLIN
  99.             if s.writable():
  100.                 flags = flags | poll.POLLOUT
  101.             if flags:
  102.                 l.append ((fd, flags))
  103.         r = poll.poll (l, timeout)
  104.         for fd, flags in r:
  105.             s = fd_map[fd]
  106.             try:
  107.                 if (flags & poll.POLLIN):
  108.                     s.handle_read_event()
  109.                 if (flags & poll.POLLOUT):
  110.                     s.handle_write_event()
  111.                 if (flags & poll.POLLERR):
  112.                     s.handle_expt_event()
  113.             except:
  114.                 s.handle_error()
  115.  
  116.  
  117. def loop (timeout=30.0, use_poll=0):
  118.  
  119.     if use_poll:
  120.         poll_fun = poll2
  121.     else:
  122.         poll_fun = poll
  123.  
  124.     while socket_map:
  125.         poll_fun (timeout)
  126.  
  127. class dispatcher:
  128.     debug = 0
  129.     connected = 0
  130.     accepting = 0
  131.     closing = 0
  132.     addr = None
  133.  
  134.     def __init__ (self, sock=None):
  135.         if sock:
  136.             self.set_socket (sock)
  137.             # I think it should inherit this anyway
  138.             self.socket.setblocking (0)
  139.             self.connected = 1
  140.  
  141.     def __repr__ (self):
  142.         try:
  143.             status = []
  144.             if self.accepting and self.addr:
  145.                 status.append ('listening')
  146.             elif self.connected:
  147.                 status.append ('connected')
  148.             if self.addr:
  149.                 status.append ('%s:%d' % self.addr)
  150.             return '<%s %s at %x>' % (
  151.                 self.__class__.__name__,
  152.                 string.join (status, ' '),
  153.                 id(self)
  154.                 )
  155.         except:
  156.             try:
  157.                 ar = repr(self.addr)
  158.             except:
  159.                 ar = 'no self.addr!'
  160.                 
  161.             return '<__repr__ (self) failed for object at %x (addr=%s)>' % (id(self),ar)
  162.  
  163.     def add_channel (self):
  164.         if __debug__:
  165.             self.log ('adding channel %s' % self)
  166.         socket_map [self] = 1
  167.  
  168.     def del_channel (self):
  169.         if socket_map.has_key (self):
  170.             if __debug__:
  171.                 self.log ('closing channel %d:%s' % (self.fileno(), self))
  172.             del socket_map [self]
  173.  
  174.     def create_socket (self, family, type):
  175.         self.family_and_type = family, type
  176.         self.socket = socket.socket (family, type)
  177.         self.socket.setblocking(0)
  178.         self.add_channel()
  179.  
  180.     def set_socket (self, socket):
  181.         # This is done so we can be called safely from __init__
  182.         self.__dict__['socket'] = socket
  183.         self.add_channel()
  184.  
  185.     def set_reuse_addr (self):
  186.         # try to re-use a server port if possible
  187.         try:
  188.             self.socket.setsockopt (
  189.                 socket.SOL_SOCKET, socket.SO_REUSEADDR,
  190.                 self.socket.getsockopt (socket.SOL_SOCKET, socket.SO_REUSEADDR) | 1
  191.                 )
  192.         except:
  193.             pass
  194.  
  195.     # ==================================================
  196.     # predicates for select()
  197.     # these are used as filters for the lists of sockets
  198.     # to pass to select().
  199.     # ==================================================
  200.  
  201.     def readable (self):
  202.         return 1
  203.  
  204.     if os.name == 'mac':
  205.         # The macintosh will select a listening socket for
  206.         # write if you let it.  What might this mean?
  207.         def writable (self):
  208.             return not self.accepting
  209.     else:
  210.         def writable (self):
  211.             return 1
  212.  
  213.     # ==================================================
  214.     # socket object methods.
  215.     # ==================================================
  216.  
  217.     def listen (self, num):
  218.         self.accepting = 1
  219.         if os.name == 'nt' and num > 5:
  220.             num = 1
  221.         return self.socket.listen (num)
  222.  
  223.     def bind (self, addr):
  224.         self.addr = addr
  225.         return self.socket.bind (addr)
  226.  
  227.     def connect (self, address):
  228.         self.connected = 0
  229.         try:
  230.             self.socket.connect (address)
  231.         except socket.error, why:
  232.             if why[0] in (EINPROGRESS, EALREADY, EWOULDBLOCK):
  233.                 return
  234.             else:
  235.                 raise socket.error, why
  236.         self.connected = 1
  237.         self.handle_connect()
  238.  
  239.     def accept (self):
  240.         try:
  241.             conn, addr = self.socket.accept()
  242.             return conn, addr
  243.         except socket.error, why:
  244.             if why[0] == EWOULDBLOCK:
  245.                 pass
  246.             else:
  247.                 raise socket.error, why
  248.  
  249.     def send (self, data):
  250.         try:
  251.             result = self.socket.send (data)
  252.             return result
  253.         except socket.error, why:
  254.             if why[0] == EWOULDBLOCK:
  255.                 return 0
  256.             else:
  257.                 raise socket.error, why
  258.             return 0
  259.  
  260.     def recv (self, buffer_size):
  261.         try:
  262.             data = self.socket.recv (buffer_size)
  263.             if not data:
  264.                 # a closed connection is indicated by signaling
  265.                 # a read condition, and having recv() return 0.
  266.                 self.handle_close()
  267.                 return ''
  268.             else:
  269.                 return data
  270.         except socket.error, why:
  271.             # winsock sometimes throws ENOTCONN
  272.             if why[0] in [ECONNRESET, ENOTCONN, ESHUTDOWN]:
  273.                 self.handle_close()
  274.                 return ''
  275.             else:
  276.                 raise socket.error, why
  277.  
  278.     def close (self):
  279.         self.del_channel()
  280.         self.socket.close()
  281.  
  282.     # cheap inheritance, used to pass all other attribute
  283.     # references to the underlying socket object.
  284.     # NOTE: this may be removed soon for performance reasons.
  285.     def __getattr__ (self, attr):
  286.         return getattr (self.socket, attr)
  287.  
  288.     def log (self, message):
  289.         print 'log:', message
  290.  
  291.     def handle_read_event (self):
  292.         if self.accepting:
  293.             # for an accepting socket, getting a read implies
  294.             # that we are connected
  295.             if not self.connected:
  296.                 self.connected = 1
  297.             self.handle_accept()
  298.         elif not self.connected:
  299.             self.handle_connect()
  300.             self.connected = 1
  301.             self.handle_read()
  302.         else:
  303.             self.handle_read()
  304.  
  305.     def handle_write_event (self):
  306.         # getting a write implies that we are connected
  307.         if not self.connected:
  308.             self.handle_connect()
  309.             self.connected = 1
  310.         self.handle_write()
  311.  
  312.     def handle_expt_event (self):
  313.         self.handle_expt()
  314.  
  315.     def handle_error (self):
  316.         (file,fun,line), t, v, tbinfo = compact_traceback()
  317.  
  318.         # sometimes a user repr method will crash.
  319.         try:
  320.             self_repr = repr (self)
  321.         except:
  322.             self_repr = '<__repr__ (self) failed for object at %0x>' % id(self)
  323.  
  324.         print (
  325.             'uncaptured python exception, closing channel %s (%s:%s %s)' % (
  326.                 self_repr,
  327.                 t,
  328.                 v,
  329.                 tbinfo
  330.                 )
  331.             )
  332.         self.close()
  333.  
  334.     def handle_expt (self):
  335.         if __debug__:
  336.             self.log ('unhandled exception')
  337.  
  338.     def handle_read (self):
  339.         if __debug__:
  340.             self.log ('unhandled read event')
  341.  
  342.     def handle_write (self):
  343.         if __debug__:
  344.             self.log ('unhandled write event')
  345.  
  346.     def handle_connect (self):
  347.         if __debug__:
  348.             self.log ('unhandled connect event')
  349.  
  350.     def handle_accept (self):
  351.         if __debug__:
  352.             self.log ('unhandled accept event')
  353.  
  354.     def handle_close (self):
  355.         if __debug__:
  356.             self.log ('unhandled close event')
  357.         self.close()
  358.  
  359. # ---------------------------------------------------------------------------
  360. # adds simple buffered output capability, useful for simple clients.
  361. # [for more sophisticated usage use asynchat.async_chat]
  362. # ---------------------------------------------------------------------------
  363.  
  364. class dispatcher_with_send (dispatcher):
  365.     def __init__ (self, sock=None):
  366.         dispatcher.__init__ (self, sock)
  367.         self.out_buffer = ''
  368.  
  369.     def initiate_send (self):
  370.         num_sent = 0
  371.         num_sent = dispatcher.send (self, self.out_buffer[:512])
  372.         self.out_buffer = self.out_buffer[num_sent:]
  373.  
  374.     def handle_write (self):
  375.         self.initiate_send()
  376.  
  377.     def writable (self):
  378.         return (not self.connected) or len(self.out_buffer)
  379.  
  380.     def send (self, data):
  381.         if self.debug:
  382.             self.log ('sending %s' % repr(data))
  383.         self.out_buffer = self.out_buffer + data
  384.         self.initiate_send()
  385.  
  386. # ---------------------------------------------------------------------------
  387. # used for debugging.
  388. # ---------------------------------------------------------------------------
  389.  
  390. def compact_traceback ():
  391.     t,v,tb = sys.exc_info()
  392.     tbinfo = []
  393.     while 1:
  394.         tbinfo.append ((
  395.             tb.tb_frame.f_code.co_filename,
  396.             tb.tb_frame.f_code.co_name,
  397.             str(tb.tb_lineno)
  398.             ))
  399.         tb = tb.tb_next
  400.         if not tb:
  401.             break
  402.  
  403.     # just to be safe
  404.     del tb
  405.  
  406.     file, function, line = tbinfo[-1]
  407.     info = '[' + string.join (
  408.         map (
  409.             lambda x: string.join (x, '|'),
  410.             tbinfo
  411.             ),
  412.         '] ['
  413.         ) + ']'
  414.     return (file, function, line), t, v, info
  415.  
  416. def close_all ():
  417.     global socket_map
  418.     for x in socket_map.keys():
  419.         x.socket.close()
  420.     socket_map.clear()
  421.  
  422. # Asynchronous File I/O:
  423. #
  424. # After a little research (reading man pages on various unixen, and
  425. # digging through the linux kernel), I've determined that select()
  426. # isn't meant for doing doing asynchronous file i/o.
  427. # Heartening, though - reading linux/mm/filemap.c shows that linux
  428. # supports asynchronous read-ahead.  So _MOST_ of the time, the data
  429. # will be sitting in memory for us already when we go to read it.
  430. #
  431. # What other OS's (besides NT) support async file i/o?  [VMS?]
  432. #
  433. # Regardless, this is useful for pipes, and stdin/stdout...
  434.  
  435. import os
  436. if os.name == 'posix':
  437.     import fcntl
  438.     import FCNTL
  439.  
  440.     class file_wrapper:
  441.         # here we override just enough to make a file
  442.         # look like a socket for the purposes of asyncore.
  443.         def __init__ (self, fd):
  444.             self.fd = fd
  445.  
  446.         def recv (self, *args):
  447.             return apply (os.read, (self.fd,)+args)
  448.  
  449.         def write (self, *args):
  450.             return apply (os.write, (self.fd,)+args)
  451.  
  452.         def close (self):
  453.             return os.close (self.fd)
  454.  
  455.         def fileno (self):
  456.             return self.fd
  457.  
  458.     class file_dispatcher (dispatcher):
  459.         def __init__ (self, fd):
  460.             dispatcher.__init__ (self)
  461.             self.connected = 1
  462.             # set it to non-blocking mode
  463.             flags = fcntl.fcntl (fd, FCNTL.F_GETFL, 0)
  464.             flags = flags | FCNTL.O_NONBLOCK
  465.             fcntl.fcntl (fd, FCNTL.F_SETFL, flags)
  466.             self.set_file (fd)
  467.  
  468.         def set_file (self, fd):
  469.             self.socket = file_wrapper (fd)
  470.             self.add_channel()
  471.  
  472.