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