blob: e79593a7c6f05489630b922c4ad000dde084cf95 [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
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000063class ExitNow (exceptions.Exception):
Fred Drake526a1822000-09-11 04:00:46 +000064 pass
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000065
66DEBUG = 0
67
68def poll (timeout=0.0, map=None):
Fred Drake526a1822000-09-11 04:00:46 +000069 if map is None:
70 map = socket_map
71 if map:
72 r = []; w = []; e = []
73 for fd, obj in map.items():
74 if obj.readable():
75 r.append (fd)
76 if obj.writable():
77 w.append (fd)
Jeremy Hyltonfbd57972001-10-29 16:32:19 +000078 try:
79 r,w,e = select.select (r,w,e, timeout)
80 except select.error, err:
81 if err[0] != EINTR:
82 raise
Guido van Rossum0039d7b1999-01-12 20:19:27 +000083
Fred Drake526a1822000-09-11 04:00:46 +000084 if DEBUG:
85 print r,w,e
Guido van Rossum0039d7b1999-01-12 20:19:27 +000086
Fred Drake526a1822000-09-11 04:00:46 +000087 for fd in r:
88 try:
89 obj = map[fd]
Fred Drake526a1822000-09-11 04:00:46 +000090 except KeyError:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +000091 continue
92
93 try:
94 obj.handle_read_event()
95 except ExitNow:
96 raise ExitNow
97 except:
98 obj.handle_error()
Guido van Rossum0039d7b1999-01-12 20:19:27 +000099
Fred Drake526a1822000-09-11 04:00:46 +0000100 for fd in w:
101 try:
102 obj = map[fd]
Fred Drake526a1822000-09-11 04:00:46 +0000103 except KeyError:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000104 continue
105
106 try:
107 obj.handle_write_event()
108 except ExitNow:
109 raise ExitNow
110 except:
111 obj.handle_error()
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000112
113def poll2 (timeout=0.0, map=None):
Fred Drake526a1822000-09-11 04:00:46 +0000114 import poll
115 if map is None:
116 map=socket_map
Martin v. Löwisf6cc07c2001-09-19 17:31:47 +0000117 if timeout is not None:
118 # timeout is in milliseconds
119 timeout = int(timeout*1000)
Fred Drake526a1822000-09-11 04:00:46 +0000120 if map:
121 l = []
122 for fd, obj in map.items():
123 flags = 0
124 if obj.readable():
125 flags = poll.POLLIN
126 if obj.writable():
127 flags = flags | poll.POLLOUT
128 if flags:
129 l.append ((fd, flags))
130 r = poll.poll (l, timeout)
131 for fd, flags in r:
132 try:
133 obj = map[fd]
Fred Drake526a1822000-09-11 04:00:46 +0000134 except KeyError:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000135 continue
136
137 try:
138 if (flags & poll.POLLIN):
139 obj.handle_read_event()
140 if (flags & poll.POLLOUT):
141 obj.handle_write_event()
142 except ExitNow:
143 raise ExitNow
144 except:
145 obj.handle_error()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000146
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000147def poll3 (timeout=0.0, map=None):
148 # Use the poll() support added to the select module in Python 2.0
149 if map is None:
150 map=socket_map
Martin v. Löwisf6cc07c2001-09-19 17:31:47 +0000151 if timeout is not None:
152 # timeout is in milliseconds
153 timeout = int(timeout*1000)
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000154 pollster = select.poll()
155 if map:
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000156 for fd, obj in map.items():
157 flags = 0
158 if obj.readable():
159 flags = select.POLLIN
160 if obj.writable():
161 flags = flags | select.POLLOUT
162 if flags:
163 pollster.register(fd, flags)
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000164 try:
165 r = pollster.poll (timeout)
166 except select.error, err:
167 if err[0] != EINTR:
168 raise
169 r = []
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000170 for fd, flags in r:
171 try:
172 obj = map[fd]
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000173 except KeyError:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000174 continue
175
176 try:
177 if (flags & select.POLLIN):
178 obj.handle_read_event()
179 if (flags & select.POLLOUT):
180 obj.handle_write_event()
181 except ExitNow:
182 raise ExitNow
183 except:
184 obj.handle_error()
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000185
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000186def loop (timeout=30.0, use_poll=0, map=None):
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000187
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000188 if map is None:
189 map=socket_map
190
Fred Drake526a1822000-09-11 04:00:46 +0000191 if use_poll:
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000192 if hasattr (select, 'poll'):
193 poll_fun = poll3
194 else:
195 poll_fun = poll2
Fred Drake526a1822000-09-11 04:00:46 +0000196 else:
197 poll_fun = poll
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000198
Fred Drake526a1822000-09-11 04:00:46 +0000199 while map:
200 poll_fun (timeout, map)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000201
202class dispatcher:
Fred Drake526a1822000-09-11 04:00:46 +0000203 debug = 0
204 connected = 0
205 accepting = 0
206 closing = 0
207 addr = None
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000208
Fred Drake526a1822000-09-11 04:00:46 +0000209 def __init__ (self, sock=None, map=None):
210 if sock:
211 self.set_socket (sock, map)
212 # I think it should inherit this anyway
213 self.socket.setblocking (0)
214 self.connected = 1
Jeremy Hylton2a05bc72001-12-14 16:15:11 +0000215 # XXX Does the constructor require that the socket passed
216 # be connected?
217 try:
218 self.addr = sock.getpeername()
219 except socket.error:
220 # The addr isn't crucial
221 pass
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000222 else:
223 self.socket = None
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000224
Fred Drake526a1822000-09-11 04:00:46 +0000225 def __repr__ (self):
Martin v. Löwis29103c72001-10-18 17:33:19 +0000226 status = [self.__class__.__module__+"."+self.__class__.__name__]
227 if self.accepting and self.addr:
228 status.append ('listening')
229 elif self.connected:
230 status.append ('connected')
231 if self.addr is not None:
232 try:
233 status.append ('%s:%d' % self.addr)
234 except TypeError:
235 status.append (repr(self.addr))
236 return '<%s at %#x>' % (' '.join (status), id (self))
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000237
Fred Drake526a1822000-09-11 04:00:46 +0000238 def add_channel (self, map=None):
239 #self.log_info ('adding channel %s' % self)
240 if map is None:
241 map=socket_map
242 map [self._fileno] = self
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000243
Fred Drake526a1822000-09-11 04:00:46 +0000244 def del_channel (self, map=None):
245 fd = self._fileno
246 if map is None:
247 map=socket_map
248 if map.has_key (fd):
249 #self.log_info ('closing channel %d:%s' % (fd, self))
250 del map [fd]
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000251
Fred Drake526a1822000-09-11 04:00:46 +0000252 def create_socket (self, family, type):
253 self.family_and_type = family, type
254 self.socket = socket.socket (family, type)
255 self.socket.setblocking(0)
256 self._fileno = self.socket.fileno()
257 self.add_channel()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000258
Fred Drake526a1822000-09-11 04:00:46 +0000259 def set_socket (self, sock, map=None):
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000260 self.socket = sock
261## self.__dict__['socket'] = sock
Fred Drake526a1822000-09-11 04:00:46 +0000262 self._fileno = sock.fileno()
263 self.add_channel (map)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000264
Fred Drake526a1822000-09-11 04:00:46 +0000265 def set_reuse_addr (self):
266 # try to re-use a server port if possible
267 try:
268 self.socket.setsockopt (
269 socket.SOL_SOCKET, socket.SO_REUSEADDR,
Jeremy Hyltona8b5f7d2001-08-10 14:30:35 +0000270 self.socket.getsockopt (socket.SOL_SOCKET,
271 socket.SO_REUSEADDR) | 1
Fred Drake526a1822000-09-11 04:00:46 +0000272 )
Fred Drake9f9b5932001-05-11 18:28:54 +0000273 except socket.error:
Fred Drake526a1822000-09-11 04:00:46 +0000274 pass
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000275
Fred Drake526a1822000-09-11 04:00:46 +0000276 # ==================================================
277 # predicates for select()
278 # these are used as filters for the lists of sockets
279 # to pass to select().
280 # ==================================================
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000281
Fred Drake526a1822000-09-11 04:00:46 +0000282 def readable (self):
283 return 1
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000284
Fred Drake526a1822000-09-11 04:00:46 +0000285 if os.name == 'mac':
286 # The macintosh will select a listening socket for
287 # write if you let it. What might this mean?
288 def writable (self):
289 return not self.accepting
290 else:
291 def writable (self):
292 return 1
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000293
Fred Drake526a1822000-09-11 04:00:46 +0000294 # ==================================================
295 # socket object methods.
296 # ==================================================
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000297
Fred Drake526a1822000-09-11 04:00:46 +0000298 def listen (self, num):
299 self.accepting = 1
300 if os.name == 'nt' and num > 5:
301 num = 1
302 return self.socket.listen (num)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000303
Fred Drake526a1822000-09-11 04:00:46 +0000304 def bind (self, addr):
305 self.addr = addr
306 return self.socket.bind (addr)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000307
Fred Drake526a1822000-09-11 04:00:46 +0000308 def connect (self, address):
309 self.connected = 0
Jeremy Hyltone16e54f2001-10-29 16:44:37 +0000310 err = self.socket.connect_ex(address)
311 if err in (EINPROGRESS, EALREADY, EWOULDBLOCK):
312 return
313 if err in (0, EISCONN):
314 self.addr = address
315 self.connected = 1
316 self.handle_connect()
Jeremy Hyltonf24339f2001-10-30 14:16:17 +0000317 else:
318 raise socket.error, err
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000319
Fred Drake526a1822000-09-11 04:00:46 +0000320 def accept (self):
321 try:
322 conn, addr = self.socket.accept()
323 return conn, addr
324 except socket.error, why:
325 if why[0] == EWOULDBLOCK:
326 pass
327 else:
328 raise socket.error, why
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000329
Fred Drake526a1822000-09-11 04:00:46 +0000330 def send (self, data):
331 try:
332 result = self.socket.send (data)
333 return result
334 except socket.error, why:
335 if why[0] == EWOULDBLOCK:
336 return 0
337 else:
338 raise socket.error, why
339 return 0
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000340
Fred Drake526a1822000-09-11 04:00:46 +0000341 def recv (self, buffer_size):
342 try:
343 data = self.socket.recv (buffer_size)
344 if not data:
345 # a closed connection is indicated by signaling
346 # a read condition, and having recv() return 0.
347 self.handle_close()
348 return ''
349 else:
350 return data
351 except socket.error, why:
352 # winsock sometimes throws ENOTCONN
353 if why[0] in [ECONNRESET, ENOTCONN, ESHUTDOWN]:
354 self.handle_close()
355 return ''
356 else:
357 raise socket.error, why
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000358
Fred Drake526a1822000-09-11 04:00:46 +0000359 def close (self):
360 self.del_channel()
361 self.socket.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000362
Fred Drake526a1822000-09-11 04:00:46 +0000363 # cheap inheritance, used to pass all other attribute
364 # references to the underlying socket object.
365 def __getattr__ (self, attr):
366 return getattr (self.socket, attr)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000367
Fred Drake526a1822000-09-11 04:00:46 +0000368 # log and log_info maybe overriden to provide more sophisitcated
369 # logging and warning methods. In general, log is for 'hit' logging
Tim Peters146965a2001-01-14 18:09:23 +0000370 # and 'log_info' is for informational, warning and error logging.
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000371
Fred Drake526a1822000-09-11 04:00:46 +0000372 def log (self, message):
373 sys.stderr.write ('log: %s\n' % str(message))
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000374
Fred Drake526a1822000-09-11 04:00:46 +0000375 def log_info (self, message, type='info'):
376 if __debug__ or type != 'info':
377 print '%s: %s' % (type, message)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000378
Fred Drake526a1822000-09-11 04:00:46 +0000379 def handle_read_event (self):
380 if self.accepting:
381 # for an accepting socket, getting a read implies
382 # that we are connected
383 if not self.connected:
384 self.connected = 1
385 self.handle_accept()
386 elif not self.connected:
387 self.handle_connect()
388 self.connected = 1
389 self.handle_read()
390 else:
391 self.handle_read()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000392
Fred Drake526a1822000-09-11 04:00:46 +0000393 def handle_write_event (self):
394 # getting a write implies that we are connected
395 if not self.connected:
396 self.handle_connect()
397 self.connected = 1
398 self.handle_write()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000399
Fred Drake526a1822000-09-11 04:00:46 +0000400 def handle_expt_event (self):
401 self.handle_expt()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000402
Fred Drake526a1822000-09-11 04:00:46 +0000403 def handle_error (self):
Jeremy Hyltona8b5f7d2001-08-10 14:30:35 +0000404 nil, t, v, tbinfo = compact_traceback()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000405
Fred Drake526a1822000-09-11 04:00:46 +0000406 # sometimes a user repr method will crash.
407 try:
408 self_repr = repr (self)
409 except:
410 self_repr = '<__repr__ (self) failed for object at %0x>' % id(self)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000411
Fred Drake526a1822000-09-11 04:00:46 +0000412 self.log_info (
413 'uncaptured python exception, closing channel %s (%s:%s %s)' % (
414 self_repr,
415 t,
416 v,
417 tbinfo
418 ),
419 'error'
420 )
421 self.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000422
Fred Drake526a1822000-09-11 04:00:46 +0000423 def handle_expt (self):
424 self.log_info ('unhandled exception', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000425
Fred Drake526a1822000-09-11 04:00:46 +0000426 def handle_read (self):
427 self.log_info ('unhandled read event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000428
Fred Drake526a1822000-09-11 04:00:46 +0000429 def handle_write (self):
430 self.log_info ('unhandled write event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000431
Fred Drake526a1822000-09-11 04:00:46 +0000432 def handle_connect (self):
433 self.log_info ('unhandled connect event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000434
Fred Drake526a1822000-09-11 04:00:46 +0000435 def handle_accept (self):
436 self.log_info ('unhandled accept event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000437
Fred Drake526a1822000-09-11 04:00:46 +0000438 def handle_close (self):
439 self.log_info ('unhandled close event', 'warning')
440 self.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000441
442# ---------------------------------------------------------------------------
443# adds simple buffered output capability, useful for simple clients.
444# [for more sophisticated usage use asynchat.async_chat]
445# ---------------------------------------------------------------------------
446
447class dispatcher_with_send (dispatcher):
Fred Drake526a1822000-09-11 04:00:46 +0000448 def __init__ (self, sock=None):
449 dispatcher.__init__ (self, sock)
450 self.out_buffer = ''
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000451
Fred Drake526a1822000-09-11 04:00:46 +0000452 def initiate_send (self):
453 num_sent = 0
454 num_sent = dispatcher.send (self, self.out_buffer[:512])
455 self.out_buffer = self.out_buffer[num_sent:]
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000456
Fred Drake526a1822000-09-11 04:00:46 +0000457 def handle_write (self):
458 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000459
Fred Drake526a1822000-09-11 04:00:46 +0000460 def writable (self):
461 return (not self.connected) or len(self.out_buffer)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000462
Fred Drake526a1822000-09-11 04:00:46 +0000463 def send (self, data):
464 if self.debug:
465 self.log_info ('sending %s' % repr(data))
466 self.out_buffer = self.out_buffer + data
467 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000468
469# ---------------------------------------------------------------------------
470# used for debugging.
471# ---------------------------------------------------------------------------
472
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000473def compact_traceback ():
Fred Drake526a1822000-09-11 04:00:46 +0000474 t,v,tb = sys.exc_info()
475 tbinfo = []
476 while 1:
477 tbinfo.append ((
478 tb.tb_frame.f_code.co_filename,
Tim Peters146965a2001-01-14 18:09:23 +0000479 tb.tb_frame.f_code.co_name,
Fred Drake526a1822000-09-11 04:00:46 +0000480 str(tb.tb_lineno)
481 ))
482 tb = tb.tb_next
483 if not tb:
484 break
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000485
Fred Drake526a1822000-09-11 04:00:46 +0000486 # just to be safe
487 del tb
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000488
Fred Drake526a1822000-09-11 04:00:46 +0000489 file, function, line = tbinfo[-1]
Eric S. Raymondb49f4a42001-02-09 05:07:04 +0000490 info = '[' + '] ['.join(map(lambda x: '|'.join(x), tbinfo)) + ']'
Fred Drake526a1822000-09-11 04:00:46 +0000491 return (file, function, line), t, v, info
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000492
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000493def close_all (map=None):
Fred Drake526a1822000-09-11 04:00:46 +0000494 if map is None:
495 map=socket_map
496 for x in map.values():
497 x.socket.close()
498 map.clear()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000499
500# Asynchronous File I/O:
501#
502# After a little research (reading man pages on various unixen, and
503# digging through the linux kernel), I've determined that select()
504# isn't meant for doing doing asynchronous file i/o.
505# Heartening, though - reading linux/mm/filemap.c shows that linux
506# supports asynchronous read-ahead. So _MOST_ of the time, the data
507# will be sitting in memory for us already when we go to read it.
508#
509# What other OS's (besides NT) support async file i/o? [VMS?]
510#
511# Regardless, this is useful for pipes, and stdin/stdout...
512
513import os
514if os.name == 'posix':
Fred Drake526a1822000-09-11 04:00:46 +0000515 import fcntl
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000516
Fred Drake526a1822000-09-11 04:00:46 +0000517 class file_wrapper:
518 # here we override just enough to make a file
519 # look like a socket for the purposes of asyncore.
520 def __init__ (self, fd):
521 self.fd = fd
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000522
Fred Drake526a1822000-09-11 04:00:46 +0000523 def recv (self, *args):
524 return apply (os.read, (self.fd,)+args)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000525
Fred Drake526a1822000-09-11 04:00:46 +0000526 def send (self, *args):
527 return apply (os.write, (self.fd,)+args)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000528
Fred Drake526a1822000-09-11 04:00:46 +0000529 read = recv
530 write = send
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000531
Fred Drake526a1822000-09-11 04:00:46 +0000532 def close (self):
533 return os.close (self.fd)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000534
Fred Drake526a1822000-09-11 04:00:46 +0000535 def fileno (self):
536 return self.fd
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000537
Fred Drake526a1822000-09-11 04:00:46 +0000538 class file_dispatcher (dispatcher):
539 def __init__ (self, fd):
540 dispatcher.__init__ (self)
541 self.connected = 1
542 # set it to non-blocking mode
Fred Drakea94414a2001-05-10 15:33:31 +0000543 flags = fcntl.fcntl (fd, fcntl.F_GETFL, 0)
544 flags = flags | os.O_NONBLOCK
545 fcntl.fcntl (fd, fcntl.F_SETFL, flags)
Fred Drake526a1822000-09-11 04:00:46 +0000546 self.set_file (fd)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000547
Fred Drake526a1822000-09-11 04:00:46 +0000548 def set_file (self, fd):
549 self._fileno = fd
550 self.socket = file_wrapper (fd)
551 self.add_channel()