blob: 180a189426679f7e6e62c55e7d31027793821740 [file] [log] [blame]
Fred Drake526a1822000-09-11 04:00:46 +00001# -*- Mode: Python -*-
Tim Peters146965a2001-01-14 18:09:23 +00002# Id: asyncore.py,v 2.51 2000/09/07 22:29:26 rushing Exp
Fred Drake526a1822000-09-11 04:00:46 +00003# Author: Sam Rushing <rushing@nightmare.com>
Guido van Rossum0039d7b1999-01-12 20:19:27 +00004
5# ======================================================================
6# Copyright 1996 by Sam Rushing
Tim Peters146965a2001-01-14 18:09:23 +00007#
Guido van Rossum0039d7b1999-01-12 20:19:27 +00008# All Rights Reserved
Tim Peters146965a2001-01-14 18:09:23 +00009#
Guido van Rossum0039d7b1999-01-12 20:19:27 +000010# 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.
Tim Peters146965a2001-01-14 18:09:23 +000018#
Guido van Rossum0039d7b1999-01-12 20:19:27 +000019# 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
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +000028"""Basic infrastructure for asynchronous socket service clients and servers.
29
30There are only two ways to have a program on a single processor do "more
Tim Peters146965a2001-01-14 18:09:23 +000031than one thing at a time". Multi-threaded programming is the simplest and
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +000032most popular way to do it, but there is another very different technique,
33that lets you have nearly all the advantages of multi-threading, without
34actually using multiple threads. it's really only practical if your program
35is largely I/O bound. If your program is CPU bound, then pre-emptive
36scheduled threads are probably what you really need. Network servers are
Tim Peters146965a2001-01-14 18:09:23 +000037rarely CPU-bound, however.
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +000038
Tim Peters146965a2001-01-14 18:09:23 +000039If your operating system supports the select() system call in its I/O
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +000040library (and nearly all do), then you can use it to juggle multiple
41communication channels at once; doing other work while your I/O is taking
42place in the "background." Although this strategy can seem strange and
43complex, especially at first, it is in many ways easier to understand and
44control than multi-threaded programming. The module documented here solves
45many of the difficult problems for you, making the task of building
Tim Peters146965a2001-01-14 18:09:23 +000046sophisticated high-performance network servers and clients a snap.
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +000047"""
48
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000049import exceptions
Guido van Rossum0039d7b1999-01-12 20:19:27 +000050import select
51import socket
Guido van Rossum0039d7b1999-01-12 20:19:27 +000052import sys
53
54import os
Jeremy Hyltona8b5f7d2001-08-10 14:30:35 +000055from errno import EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, \
Jeremy Hyltone16e54f2001-10-29 16:44:37 +000056 ENOTCONN, ESHUTDOWN, EINTR, EISCONN
Guido van Rossum0039d7b1999-01-12 20:19:27 +000057
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000058try:
Fred Drake526a1822000-09-11 04:00:46 +000059 socket_map
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000060except NameError:
Fred Drake526a1822000-09-11 04:00:46 +000061 socket_map = {}
Guido van Rossum0039d7b1999-01-12 20:19:27 +000062
Jeremy Hyltond7500362002-09-08 00:14:54 +000063class ExitNow(exceptions.Exception):
Fred Drake526a1822000-09-11 04:00:46 +000064 pass
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000065
Jeremy Hyltond7500362002-09-08 00:14:54 +000066def read(obj):
67 try:
68 obj.handle_read_event()
69 except ExitNow:
70 raise
71 except:
72 obj.handle_error()
73
74def write(obj):
75 try:
76 obj.handle_write_event()
77 except ExitNow:
78 raise
79 except:
80 obj.handle_error()
81
82def readwrite(obj, flags):
83 try:
84 if flags & select.POLLIN:
85 obj.handle_read_event()
86 if flags & select.POLLOUT:
87 obj.handle_write_event()
88 except ExitNow:
89 raise
90 except:
91 obj.handle_error()
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000092
93def poll (timeout=0.0, map=None):
Fred Drake526a1822000-09-11 04:00:46 +000094 if map is None:
95 map = socket_map
96 if map:
97 r = []; w = []; e = []
Jeremy Hyltond7500362002-09-08 00:14:54 +000098 for fd, obj in map.iteritems():
Fred Drake526a1822000-09-11 04:00:46 +000099 if obj.readable():
Jeremy Hyltond7500362002-09-08 00:14:54 +0000100 r.append(fd)
Fred Drake526a1822000-09-11 04:00:46 +0000101 if obj.writable():
Jeremy Hyltond7500362002-09-08 00:14:54 +0000102 w.append(fd)
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000103 try:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000104 r, w, e = select.select(r, w, e, timeout)
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000105 except select.error, err:
106 if err[0] != EINTR:
107 raise
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000108
Fred Drake526a1822000-09-11 04:00:46 +0000109 for fd in r:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000110 obj = map.get(fd)
111 if obj is None:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000112 continue
Jeremy Hyltond7500362002-09-08 00:14:54 +0000113 read(obj)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000114
Fred Drake526a1822000-09-11 04:00:46 +0000115 for fd in w:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000116 obj = map.get(fd)
117 if obj is None:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000118 continue
Jeremy Hyltond7500362002-09-08 00:14:54 +0000119 write(obj)
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000120
121def poll2 (timeout=0.0, map=None):
Fred Drake526a1822000-09-11 04:00:46 +0000122 import poll
123 if map is None:
124 map=socket_map
Martin v. Löwisf6cc07c2001-09-19 17:31:47 +0000125 if timeout is not None:
126 # timeout is in milliseconds
127 timeout = int(timeout*1000)
Fred Drake526a1822000-09-11 04:00:46 +0000128 if map:
129 l = []
Jeremy Hyltond7500362002-09-08 00:14:54 +0000130 for fd, obj in map.iteritems():
Fred Drake526a1822000-09-11 04:00:46 +0000131 flags = 0
132 if obj.readable():
133 flags = poll.POLLIN
134 if obj.writable():
135 flags = flags | poll.POLLOUT
136 if flags:
137 l.append ((fd, flags))
138 r = poll.poll (l, timeout)
139 for fd, flags in r:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000140 obj = map.get(fd)
141 if obj is None:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000142 continue
Jeremy Hyltond7500362002-09-08 00:14:54 +0000143 readwrite(obj, flags)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000144
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000145def poll3 (timeout=0.0, map=None):
146 # Use the poll() support added to the select module in Python 2.0
147 if map is None:
148 map=socket_map
Martin v. Löwisf6cc07c2001-09-19 17:31:47 +0000149 if timeout is not None:
150 # timeout is in milliseconds
151 timeout = int(timeout*1000)
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000152 pollster = select.poll()
153 if map:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000154 for fd, obj in map.iteritems():
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000155 flags = 0
156 if obj.readable():
157 flags = select.POLLIN
158 if obj.writable():
159 flags = flags | select.POLLOUT
160 if flags:
161 pollster.register(fd, flags)
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000162 try:
163 r = pollster.poll (timeout)
164 except select.error, err:
165 if err[0] != EINTR:
166 raise
167 r = []
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000168 for fd, flags in r:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000169 obj = map.get(fd)
170 if obj is None:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000171 continue
Jeremy Hyltond7500362002-09-08 00:14:54 +0000172 readwrite(obj, flags)
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000173
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000174def loop (timeout=30.0, use_poll=0, map=None):
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000175 if map is None:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000176 map = socket_map
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000177
Fred Drake526a1822000-09-11 04:00:46 +0000178 if use_poll:
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000179 if hasattr (select, 'poll'):
180 poll_fun = poll3
181 else:
182 poll_fun = poll2
Fred Drake526a1822000-09-11 04:00:46 +0000183 else:
184 poll_fun = poll
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000185
Fred Drake526a1822000-09-11 04:00:46 +0000186 while map:
187 poll_fun (timeout, map)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000188
189class dispatcher:
Fred Drake526a1822000-09-11 04:00:46 +0000190 debug = 0
191 connected = 0
192 accepting = 0
193 closing = 0
194 addr = None
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000195
Fred Drake526a1822000-09-11 04:00:46 +0000196 def __init__ (self, sock=None, map=None):
197 if sock:
198 self.set_socket (sock, map)
199 # I think it should inherit this anyway
200 self.socket.setblocking (0)
201 self.connected = 1
Jeremy Hylton2a05bc72001-12-14 16:15:11 +0000202 # XXX Does the constructor require that the socket passed
203 # be connected?
204 try:
205 self.addr = sock.getpeername()
206 except socket.error:
207 # The addr isn't crucial
208 pass
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000209 else:
210 self.socket = None
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000211
Fred Drake526a1822000-09-11 04:00:46 +0000212 def __repr__ (self):
Martin v. Löwis29103c72001-10-18 17:33:19 +0000213 status = [self.__class__.__module__+"."+self.__class__.__name__]
214 if self.accepting and self.addr:
215 status.append ('listening')
216 elif self.connected:
217 status.append ('connected')
218 if self.addr is not None:
219 try:
220 status.append ('%s:%d' % self.addr)
221 except TypeError:
222 status.append (repr(self.addr))
223 return '<%s at %#x>' % (' '.join (status), id (self))
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000224
Fred Drake526a1822000-09-11 04:00:46 +0000225 def add_channel (self, map=None):
226 #self.log_info ('adding channel %s' % self)
227 if map is None:
228 map=socket_map
229 map [self._fileno] = self
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000230
Fred Drake526a1822000-09-11 04:00:46 +0000231 def del_channel (self, map=None):
232 fd = self._fileno
233 if map is None:
234 map=socket_map
235 if map.has_key (fd):
236 #self.log_info ('closing channel %d:%s' % (fd, self))
237 del map [fd]
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000238
Fred Drake526a1822000-09-11 04:00:46 +0000239 def create_socket (self, family, type):
240 self.family_and_type = family, type
241 self.socket = socket.socket (family, type)
242 self.socket.setblocking(0)
243 self._fileno = self.socket.fileno()
244 self.add_channel()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000245
Fred Drake526a1822000-09-11 04:00:46 +0000246 def set_socket (self, sock, map=None):
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000247 self.socket = sock
248## self.__dict__['socket'] = sock
Fred Drake526a1822000-09-11 04:00:46 +0000249 self._fileno = sock.fileno()
250 self.add_channel (map)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000251
Fred Drake526a1822000-09-11 04:00:46 +0000252 def set_reuse_addr (self):
253 # try to re-use a server port if possible
254 try:
255 self.socket.setsockopt (
256 socket.SOL_SOCKET, socket.SO_REUSEADDR,
Jeremy Hyltona8b5f7d2001-08-10 14:30:35 +0000257 self.socket.getsockopt (socket.SOL_SOCKET,
258 socket.SO_REUSEADDR) | 1
Fred Drake526a1822000-09-11 04:00:46 +0000259 )
Fred Drake9f9b5932001-05-11 18:28:54 +0000260 except socket.error:
Fred Drake526a1822000-09-11 04:00:46 +0000261 pass
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000262
Fred Drake526a1822000-09-11 04:00:46 +0000263 # ==================================================
264 # predicates for select()
265 # these are used as filters for the lists of sockets
266 # to pass to select().
267 # ==================================================
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000268
Fred Drake526a1822000-09-11 04:00:46 +0000269 def readable (self):
Tim Petersbc0e9102002-04-04 22:55:58 +0000270 return True
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000271
Fred Drake526a1822000-09-11 04:00:46 +0000272 if os.name == 'mac':
273 # The macintosh will select a listening socket for
274 # write if you let it. What might this mean?
275 def writable (self):
276 return not self.accepting
277 else:
278 def writable (self):
Tim Petersbc0e9102002-04-04 22:55:58 +0000279 return True
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000280
Fred Drake526a1822000-09-11 04:00:46 +0000281 # ==================================================
282 # socket object methods.
283 # ==================================================
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000284
Fred Drake526a1822000-09-11 04:00:46 +0000285 def listen (self, num):
286 self.accepting = 1
287 if os.name == 'nt' and num > 5:
288 num = 1
289 return self.socket.listen (num)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000290
Fred Drake526a1822000-09-11 04:00:46 +0000291 def bind (self, addr):
292 self.addr = addr
293 return self.socket.bind (addr)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000294
Fred Drake526a1822000-09-11 04:00:46 +0000295 def connect (self, address):
296 self.connected = 0
Jeremy Hyltone16e54f2001-10-29 16:44:37 +0000297 err = self.socket.connect_ex(address)
298 if err in (EINPROGRESS, EALREADY, EWOULDBLOCK):
299 return
300 if err in (0, EISCONN):
301 self.addr = address
302 self.connected = 1
303 self.handle_connect()
Jeremy Hyltonf24339f2001-10-30 14:16:17 +0000304 else:
305 raise socket.error, err
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000306
Fred Drake526a1822000-09-11 04:00:46 +0000307 def accept (self):
Jeremy Hyltonf32e4592002-04-04 21:02:24 +0000308 # XXX can return either an address pair or None
Fred Drake526a1822000-09-11 04:00:46 +0000309 try:
310 conn, addr = self.socket.accept()
311 return conn, addr
312 except socket.error, why:
313 if why[0] == EWOULDBLOCK:
314 pass
315 else:
316 raise socket.error, why
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000317
Fred Drake526a1822000-09-11 04:00:46 +0000318 def send (self, data):
319 try:
320 result = self.socket.send (data)
321 return result
322 except socket.error, why:
323 if why[0] == EWOULDBLOCK:
324 return 0
325 else:
326 raise socket.error, why
327 return 0
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000328
Fred Drake526a1822000-09-11 04:00:46 +0000329 def recv (self, buffer_size):
330 try:
331 data = self.socket.recv (buffer_size)
332 if not data:
333 # a closed connection is indicated by signaling
334 # a read condition, and having recv() return 0.
335 self.handle_close()
336 return ''
337 else:
338 return data
339 except socket.error, why:
340 # winsock sometimes throws ENOTCONN
341 if why[0] in [ECONNRESET, ENOTCONN, ESHUTDOWN]:
342 self.handle_close()
343 return ''
344 else:
345 raise socket.error, why
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000346
Fred Drake526a1822000-09-11 04:00:46 +0000347 def close (self):
348 self.del_channel()
349 self.socket.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000350
Fred Drake526a1822000-09-11 04:00:46 +0000351 # cheap inheritance, used to pass all other attribute
352 # references to the underlying socket object.
353 def __getattr__ (self, attr):
354 return getattr (self.socket, attr)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000355
Fred Drake526a1822000-09-11 04:00:46 +0000356 # log and log_info maybe overriden to provide more sophisitcated
357 # logging and warning methods. In general, log is for 'hit' logging
Tim Peters146965a2001-01-14 18:09:23 +0000358 # and 'log_info' is for informational, warning and error logging.
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000359
Fred Drake526a1822000-09-11 04:00:46 +0000360 def log (self, message):
361 sys.stderr.write ('log: %s\n' % str(message))
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000362
Fred Drake526a1822000-09-11 04:00:46 +0000363 def log_info (self, message, type='info'):
364 if __debug__ or type != 'info':
365 print '%s: %s' % (type, message)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000366
Fred Drake526a1822000-09-11 04:00:46 +0000367 def handle_read_event (self):
368 if self.accepting:
369 # for an accepting socket, getting a read implies
370 # that we are connected
371 if not self.connected:
372 self.connected = 1
373 self.handle_accept()
374 elif not self.connected:
375 self.handle_connect()
376 self.connected = 1
377 self.handle_read()
378 else:
379 self.handle_read()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000380
Fred Drake526a1822000-09-11 04:00:46 +0000381 def handle_write_event (self):
382 # getting a write implies that we are connected
383 if not self.connected:
384 self.handle_connect()
385 self.connected = 1
386 self.handle_write()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000387
Fred Drake526a1822000-09-11 04:00:46 +0000388 def handle_expt_event (self):
389 self.handle_expt()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000390
Fred Drake526a1822000-09-11 04:00:46 +0000391 def handle_error (self):
Jeremy Hyltona8b5f7d2001-08-10 14:30:35 +0000392 nil, t, v, tbinfo = compact_traceback()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000393
Fred Drake526a1822000-09-11 04:00:46 +0000394 # sometimes a user repr method will crash.
395 try:
396 self_repr = repr (self)
397 except:
398 self_repr = '<__repr__ (self) failed for object at %0x>' % id(self)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000399
Fred Drake526a1822000-09-11 04:00:46 +0000400 self.log_info (
401 'uncaptured python exception, closing channel %s (%s:%s %s)' % (
402 self_repr,
403 t,
404 v,
405 tbinfo
406 ),
407 'error'
408 )
409 self.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000410
Fred Drake526a1822000-09-11 04:00:46 +0000411 def handle_expt (self):
412 self.log_info ('unhandled exception', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000413
Fred Drake526a1822000-09-11 04:00:46 +0000414 def handle_read (self):
415 self.log_info ('unhandled read event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000416
Fred Drake526a1822000-09-11 04:00:46 +0000417 def handle_write (self):
418 self.log_info ('unhandled write event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000419
Fred Drake526a1822000-09-11 04:00:46 +0000420 def handle_connect (self):
421 self.log_info ('unhandled connect event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000422
Fred Drake526a1822000-09-11 04:00:46 +0000423 def handle_accept (self):
424 self.log_info ('unhandled accept event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000425
Fred Drake526a1822000-09-11 04:00:46 +0000426 def handle_close (self):
427 self.log_info ('unhandled close event', 'warning')
428 self.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000429
430# ---------------------------------------------------------------------------
431# adds simple buffered output capability, useful for simple clients.
432# [for more sophisticated usage use asynchat.async_chat]
433# ---------------------------------------------------------------------------
434
435class dispatcher_with_send (dispatcher):
Fred Drake526a1822000-09-11 04:00:46 +0000436 def __init__ (self, sock=None):
437 dispatcher.__init__ (self, sock)
438 self.out_buffer = ''
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000439
Fred Drake526a1822000-09-11 04:00:46 +0000440 def initiate_send (self):
441 num_sent = 0
442 num_sent = dispatcher.send (self, self.out_buffer[:512])
443 self.out_buffer = self.out_buffer[num_sent:]
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000444
Fred Drake526a1822000-09-11 04:00:46 +0000445 def handle_write (self):
446 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000447
Fred Drake526a1822000-09-11 04:00:46 +0000448 def writable (self):
449 return (not self.connected) or len(self.out_buffer)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000450
Fred Drake526a1822000-09-11 04:00:46 +0000451 def send (self, data):
452 if self.debug:
453 self.log_info ('sending %s' % repr(data))
454 self.out_buffer = self.out_buffer + data
455 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000456
457# ---------------------------------------------------------------------------
458# used for debugging.
459# ---------------------------------------------------------------------------
460
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000461def compact_traceback ():
Fred Drake526a1822000-09-11 04:00:46 +0000462 t,v,tb = sys.exc_info()
463 tbinfo = []
464 while 1:
465 tbinfo.append ((
466 tb.tb_frame.f_code.co_filename,
Tim Peters146965a2001-01-14 18:09:23 +0000467 tb.tb_frame.f_code.co_name,
Fred Drake526a1822000-09-11 04:00:46 +0000468 str(tb.tb_lineno)
469 ))
470 tb = tb.tb_next
471 if not tb:
472 break
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000473
Fred Drake526a1822000-09-11 04:00:46 +0000474 # just to be safe
475 del tb
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000476
Fred Drake526a1822000-09-11 04:00:46 +0000477 file, function, line = tbinfo[-1]
Eric S. Raymondb49f4a42001-02-09 05:07:04 +0000478 info = '[' + '] ['.join(map(lambda x: '|'.join(x), tbinfo)) + ']'
Fred Drake526a1822000-09-11 04:00:46 +0000479 return (file, function, line), t, v, info
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000480
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000481def close_all (map=None):
Fred Drake526a1822000-09-11 04:00:46 +0000482 if map is None:
483 map=socket_map
484 for x in map.values():
485 x.socket.close()
486 map.clear()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000487
488# Asynchronous File I/O:
489#
490# After a little research (reading man pages on various unixen, and
491# digging through the linux kernel), I've determined that select()
492# isn't meant for doing doing asynchronous file i/o.
493# Heartening, though - reading linux/mm/filemap.c shows that linux
494# supports asynchronous read-ahead. So _MOST_ of the time, the data
495# will be sitting in memory for us already when we go to read it.
496#
497# What other OS's (besides NT) support async file i/o? [VMS?]
498#
499# Regardless, this is useful for pipes, and stdin/stdout...
500
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000501if os.name == 'posix':
Fred Drake526a1822000-09-11 04:00:46 +0000502 import fcntl
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000503
Fred Drake526a1822000-09-11 04:00:46 +0000504 class file_wrapper:
505 # here we override just enough to make a file
506 # look like a socket for the purposes of asyncore.
507 def __init__ (self, fd):
508 self.fd = fd
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000509
Fred Drake526a1822000-09-11 04:00:46 +0000510 def recv (self, *args):
Jeremy Hyltonf32e4592002-04-04 21:02:24 +0000511 return os.read(self.fd, *args)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000512
Fred Drake526a1822000-09-11 04:00:46 +0000513 def send (self, *args):
Jeremy Hyltonf32e4592002-04-04 21:02:24 +0000514 return os.write(self.fd, *args)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000515
Fred Drake526a1822000-09-11 04:00:46 +0000516 read = recv
517 write = send
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000518
Fred Drake526a1822000-09-11 04:00:46 +0000519 def close (self):
520 return os.close (self.fd)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000521
Fred Drake526a1822000-09-11 04:00:46 +0000522 def fileno (self):
523 return self.fd
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000524
Fred Drake526a1822000-09-11 04:00:46 +0000525 class file_dispatcher (dispatcher):
526 def __init__ (self, fd):
527 dispatcher.__init__ (self)
528 self.connected = 1
529 # set it to non-blocking mode
Fred Drakea94414a2001-05-10 15:33:31 +0000530 flags = fcntl.fcntl (fd, fcntl.F_GETFL, 0)
531 flags = flags | os.O_NONBLOCK
532 fcntl.fcntl (fd, fcntl.F_SETFL, flags)
Fred Drake526a1822000-09-11 04:00:46 +0000533 self.set_file (fd)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000534
Fred Drake526a1822000-09-11 04:00:46 +0000535 def set_file (self, fd):
536 self._fileno = fd
537 self.socket = file_wrapper (fd)
538 self.add_channel()