/Lib/asyncore.py

http://unladen-swallow.googlecode.com/ · Python · 618 lines · 430 code · 88 blank · 100 comment · 122 complexity · 658962db16e38f24a8884f5e6e2deaf4 MD5 · raw file

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