asyncore.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  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 warnings
  49. import os
  50. from errno import EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, EINVAL, \
  51. ENOTCONN, ESHUTDOWN, EISCONN, EBADF, ECONNABORTED, EPIPE, EAGAIN, \
  52. errorcode
  53. _DISCONNECTED = frozenset({ECONNRESET, ENOTCONN, ESHUTDOWN, ECONNABORTED, EPIPE,
  54. EBADF})
  55. try:
  56. socket_map
  57. except NameError:
  58. socket_map = {}
  59. def _strerror(err):
  60. try:
  61. return os.strerror(err)
  62. except (ValueError, OverflowError, NameError):
  63. if err in errorcode:
  64. return errorcode[err]
  65. return "Unknown error %s" %err
  66. class ExitNow(Exception):
  67. pass
  68. _reraised_exceptions = (ExitNow, KeyboardInterrupt, SystemExit)
  69. def read(obj):
  70. try:
  71. obj.handle_read_event()
  72. except _reraised_exceptions:
  73. raise
  74. except:
  75. obj.handle_error()
  76. def write(obj):
  77. try:
  78. obj.handle_write_event()
  79. except _reraised_exceptions:
  80. raise
  81. except:
  82. obj.handle_error()
  83. def _exception(obj):
  84. try:
  85. obj.handle_expt_event()
  86. except _reraised_exceptions:
  87. raise
  88. except:
  89. obj.handle_error()
  90. def readwrite(obj, flags):
  91. try:
  92. if flags & select.POLLIN:
  93. obj.handle_read_event()
  94. if flags & select.POLLOUT:
  95. obj.handle_write_event()
  96. if flags & select.POLLPRI:
  97. obj.handle_expt_event()
  98. if flags & (select.POLLHUP | select.POLLERR | select.POLLNVAL):
  99. obj.handle_close()
  100. except OSError as e:
  101. if e.args[0] not in _DISCONNECTED:
  102. obj.handle_error()
  103. else:
  104. obj.handle_close()
  105. except _reraised_exceptions:
  106. raise
  107. except:
  108. obj.handle_error()
  109. def poll(timeout=0.0, map=None):
  110. if map is None:
  111. map = socket_map
  112. if map:
  113. r = []; w = []; e = []
  114. for fd, obj in list(map.items()):
  115. is_r = obj.readable()
  116. is_w = obj.writable()
  117. if is_r:
  118. r.append(fd)
  119. # accepting sockets should not be writable
  120. if is_w and not obj.accepting:
  121. w.append(fd)
  122. if is_r or is_w:
  123. e.append(fd)
  124. if [] == r == w == e:
  125. time.sleep(timeout)
  126. return
  127. r, w, e = select.select(r, w, e, timeout)
  128. for fd in r:
  129. obj = map.get(fd)
  130. if obj is None:
  131. continue
  132. read(obj)
  133. for fd in w:
  134. obj = map.get(fd)
  135. if obj is None:
  136. continue
  137. write(obj)
  138. for fd in e:
  139. obj = map.get(fd)
  140. if obj is None:
  141. continue
  142. _exception(obj)
  143. def poll2(timeout=0.0, map=None):
  144. # Use the poll() support added to the select module in Python 2.0
  145. if map is None:
  146. map = socket_map
  147. if timeout is not None:
  148. # timeout is in milliseconds
  149. timeout = int(timeout*1000)
  150. pollster = select.poll()
  151. if map:
  152. for fd, obj in list(map.items()):
  153. flags = 0
  154. if obj.readable():
  155. flags |= select.POLLIN | select.POLLPRI
  156. # accepting sockets should not be writable
  157. if obj.writable() and not obj.accepting:
  158. flags |= select.POLLOUT
  159. if flags:
  160. pollster.register(fd, flags)
  161. r = pollster.poll(timeout)
  162. for fd, flags in r:
  163. obj = map.get(fd)
  164. if obj is None:
  165. continue
  166. readwrite(obj, flags)
  167. poll3 = poll2 # Alias for backward compatibility
  168. def loop(timeout=30.0, use_poll=False, map=None, count=None):
  169. if map is None:
  170. map = socket_map
  171. if use_poll and hasattr(select, 'poll'):
  172. poll_fun = poll2
  173. else:
  174. poll_fun = poll
  175. if count is None:
  176. while map:
  177. poll_fun(timeout, map)
  178. else:
  179. while map and count > 0:
  180. poll_fun(timeout, map)
  181. count = count - 1
  182. class dispatcher:
  183. debug = False
  184. connected = False
  185. accepting = False
  186. connecting = 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(False)
  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 OSError as err:
  207. if err.args[0] in (ENOTCONN, EINVAL):
  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__.__qualname__]
  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=socket.AF_INET, type=socket.SOCK_STREAM):
  245. self.family_and_type = family, type
  246. sock = socket.socket(family, type)
  247. sock.setblocking(False)
  248. self.set_socket(sock)
  249. def set_socket(self, sock, map=None):
  250. self.socket = sock
  251. self._fileno = sock.fileno()
  252. self.add_channel(map)
  253. def set_reuse_addr(self):
  254. # try to re-use a server port if possible
  255. try:
  256. self.socket.setsockopt(
  257. socket.SOL_SOCKET, socket.SO_REUSEADDR,
  258. self.socket.getsockopt(socket.SOL_SOCKET,
  259. socket.SO_REUSEADDR) | 1
  260. )
  261. except OSError:
  262. pass
  263. # ==================================================
  264. # predicates for select()
  265. # these are used as filters for the lists of sockets
  266. # to pass to select().
  267. # ==================================================
  268. def readable(self):
  269. return True
  270. def writable(self):
  271. return True
  272. # ==================================================
  273. # socket object methods.
  274. # ==================================================
  275. def listen(self, num):
  276. self.accepting = True
  277. if os.name == 'nt' and num > 5:
  278. num = 5
  279. return self.socket.listen(num)
  280. def bind(self, addr):
  281. self.addr = addr
  282. return self.socket.bind(addr)
  283. def connect(self, address):
  284. self.connected = False
  285. self.connecting = True
  286. err = self.socket.connect_ex(address)
  287. if err in (EINPROGRESS, EALREADY, EWOULDBLOCK) \
  288. or err == EINVAL and os.name == 'nt':
  289. self.addr = address
  290. return
  291. if err in (0, EISCONN):
  292. self.addr = address
  293. self.handle_connect_event()
  294. else:
  295. raise OSError(err, errorcode[err])
  296. def accept(self):
  297. # XXX can return either an address pair or None
  298. try:
  299. conn, addr = self.socket.accept()
  300. except TypeError:
  301. return None
  302. except OSError as why:
  303. if why.args[0] in (EWOULDBLOCK, ECONNABORTED, EAGAIN):
  304. return None
  305. else:
  306. raise
  307. else:
  308. return conn, addr
  309. def send(self, data):
  310. try:
  311. result = self.socket.send(data)
  312. return result
  313. except OSError as why:
  314. if why.args[0] == EWOULDBLOCK:
  315. return 0
  316. elif why.args[0] in _DISCONNECTED:
  317. self.handle_close()
  318. return 0
  319. else:
  320. raise
  321. def recv(self, buffer_size):
  322. try:
  323. data = self.socket.recv(buffer_size)
  324. if not data:
  325. # a closed connection is indicated by signaling
  326. # a read condition, and having recv() return 0.
  327. self.handle_close()
  328. return b''
  329. else:
  330. return data
  331. except OSError as why:
  332. # winsock sometimes raises ENOTCONN
  333. if why.args[0] in _DISCONNECTED:
  334. self.handle_close()
  335. return b''
  336. else:
  337. raise
  338. def close(self):
  339. self.connected = False
  340. self.accepting = False
  341. self.connecting = False
  342. self.del_channel()
  343. if self.socket is not None:
  344. try:
  345. self.socket.close()
  346. except OSError as why:
  347. if why.args[0] not in (ENOTCONN, EBADF):
  348. raise
  349. # log and log_info may be overridden to provide more sophisticated
  350. # logging and warning methods. In general, log is for 'hit' logging
  351. # and 'log_info' is for informational, warning and error logging.
  352. def log(self, message):
  353. sys.stderr.write('log: %s\n' % str(message))
  354. def log_info(self, message, type='info'):
  355. if type not in self.ignore_log_types:
  356. print('%s: %s' % (type, message))
  357. def handle_read_event(self):
  358. if self.accepting:
  359. # accepting sockets are never connected, they "spawn" new
  360. # sockets that are connected
  361. self.handle_accept()
  362. elif not self.connected:
  363. if self.connecting:
  364. self.handle_connect_event()
  365. self.handle_read()
  366. else:
  367. self.handle_read()
  368. def handle_connect_event(self):
  369. err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
  370. if err != 0:
  371. raise OSError(err, _strerror(err))
  372. self.handle_connect()
  373. self.connected = True
  374. self.connecting = False
  375. def handle_write_event(self):
  376. if self.accepting:
  377. # Accepting sockets shouldn't get a write event.
  378. # We will pretend it didn't happen.
  379. return
  380. if not self.connected:
  381. if self.connecting:
  382. self.handle_connect_event()
  383. self.handle_write()
  384. def handle_expt_event(self):
  385. # handle_expt_event() is called if there might be an error on the
  386. # socket, or if there is OOB data
  387. # check for the error condition first
  388. err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
  389. if err != 0:
  390. # we can get here when select.select() says that there is an
  391. # exceptional condition on the socket
  392. # since there is an error, we'll go ahead and close the socket
  393. # like we would in a subclassed handle_read() that received no
  394. # data
  395. self.handle_close()
  396. else:
  397. self.handle_expt()
  398. def handle_error(self):
  399. nil, t, v, tbinfo = compact_traceback()
  400. # sometimes a user repr method will crash.
  401. try:
  402. self_repr = repr(self)
  403. except:
  404. self_repr = '<__repr__(self) failed for object at %0x>' % id(self)
  405. self.log_info(
  406. 'uncaptured python exception, closing channel %s (%s:%s %s)' % (
  407. self_repr,
  408. t,
  409. v,
  410. tbinfo
  411. ),
  412. 'error'
  413. )
  414. self.handle_close()
  415. def handle_expt(self):
  416. self.log_info('unhandled incoming priority event', 'warning')
  417. def handle_read(self):
  418. self.log_info('unhandled read event', 'warning')
  419. def handle_write(self):
  420. self.log_info('unhandled write event', 'warning')
  421. def handle_connect(self):
  422. self.log_info('unhandled connect event', 'warning')
  423. def handle_accept(self):
  424. pair = self.accept()
  425. if pair is not None:
  426. self.handle_accepted(*pair)
  427. def handle_accepted(self, sock, addr):
  428. sock.close()
  429. self.log_info('unhandled accepted event', 'warning')
  430. def handle_close(self):
  431. self.log_info('unhandled close event', 'warning')
  432. self.close()
  433. # ---------------------------------------------------------------------------
  434. # adds simple buffered output capability, useful for simple clients.
  435. # [for more sophisticated usage use asynchat.async_chat]
  436. # ---------------------------------------------------------------------------
  437. class dispatcher_with_send(dispatcher):
  438. def __init__(self, sock=None, map=None):
  439. dispatcher.__init__(self, sock, map)
  440. self.out_buffer = b''
  441. def initiate_send(self):
  442. num_sent = 0
  443. num_sent = dispatcher.send(self, self.out_buffer[:65536])
  444. self.out_buffer = self.out_buffer[num_sent:]
  445. def handle_write(self):
  446. self.initiate_send()
  447. def writable(self):
  448. return (not self.connected) or len(self.out_buffer)
  449. def send(self, data):
  450. if self.debug:
  451. self.log_info('sending %s' % repr(data))
  452. self.out_buffer = self.out_buffer + data
  453. self.initiate_send()
  454. # ---------------------------------------------------------------------------
  455. # used for debugging.
  456. # ---------------------------------------------------------------------------
  457. def compact_traceback():
  458. t, v, tb = sys.exc_info()
  459. tbinfo = []
  460. if not tb: # Must have a traceback
  461. raise AssertionError("traceback does not exist")
  462. while tb:
  463. tbinfo.append((
  464. tb.tb_frame.f_code.co_filename,
  465. tb.tb_frame.f_code.co_name,
  466. str(tb.tb_lineno)
  467. ))
  468. tb = tb.tb_next
  469. # just to be safe
  470. del tb
  471. file, function, line = tbinfo[-1]
  472. info = ' '.join(['[%s|%s|%s]' % x for x in tbinfo])
  473. return (file, function, line), t, v, info
  474. def close_all(map=None, ignore_all=False):
  475. if map is None:
  476. map = socket_map
  477. for x in list(map.values()):
  478. try:
  479. x.close()
  480. except OSError as x:
  481. if x.args[0] == EBADF:
  482. pass
  483. elif not ignore_all:
  484. raise
  485. except _reraised_exceptions:
  486. raise
  487. except:
  488. if not ignore_all:
  489. raise
  490. map.clear()
  491. # Asynchronous File I/O:
  492. #
  493. # After a little research (reading man pages on various unixen, and
  494. # digging through the linux kernel), I've determined that select()
  495. # isn't meant for doing asynchronous file i/o.
  496. # Heartening, though - reading linux/mm/filemap.c shows that linux
  497. # supports asynchronous read-ahead. So _MOST_ of the time, the data
  498. # will be sitting in memory for us already when we go to read it.
  499. #
  500. # What other OS's (besides NT) support async file i/o? [VMS?]
  501. #
  502. # Regardless, this is useful for pipes, and stdin/stdout...
  503. if os.name == 'posix':
  504. class file_wrapper:
  505. # Here we override just enough to make a file
  506. # look like a socket for the purposes of asyncore.
  507. # The passed fd is automatically os.dup()'d
  508. def __init__(self, fd):
  509. self.fd = os.dup(fd)
  510. def __del__(self):
  511. if self.fd >= 0:
  512. warnings.warn("unclosed file %r" % self, ResourceWarning,
  513. source=self)
  514. self.close()
  515. def recv(self, *args):
  516. return os.read(self.fd, *args)
  517. def send(self, *args):
  518. return os.write(self.fd, *args)
  519. def getsockopt(self, level, optname, buflen=None):
  520. if (level == socket.SOL_SOCKET and
  521. optname == socket.SO_ERROR and
  522. not buflen):
  523. return 0
  524. raise NotImplementedError("Only asyncore specific behaviour "
  525. "implemented.")
  526. read = recv
  527. write = send
  528. def close(self):
  529. if self.fd < 0:
  530. return
  531. fd = self.fd
  532. self.fd = -1
  533. os.close(fd)
  534. def fileno(self):
  535. return self.fd
  536. class file_dispatcher(dispatcher):
  537. def __init__(self, fd, map=None):
  538. dispatcher.__init__(self, None, map)
  539. self.connected = True
  540. try:
  541. fd = fd.fileno()
  542. except AttributeError:
  543. pass
  544. self.set_file(fd)
  545. # set it to non-blocking mode
  546. os.set_blocking(fd, False)
  547. def set_file(self, fd):
  548. self.socket = file_wrapper(fd)
  549. self._fileno = self.socket.fileno()
  550. self.add_channel()