blob: 00b02e300f301f04e7d37e8a0cc89d4e9ed61bad [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
Jeremy Hylton12e73bb2001-04-20 19:04:55 +000053import types
Guido van Rossum0039d7b1999-01-12 20:19:27 +000054
55import os
Jeremy Hyltona8b5f7d2001-08-10 14:30:35 +000056from errno import EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, \
Tim Peters7c005af2001-08-20 21:48:00 +000057 ENOTCONN, ESHUTDOWN
Guido van Rossum0039d7b1999-01-12 20:19:27 +000058
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000059try:
Fred Drake526a1822000-09-11 04:00:46 +000060 socket_map
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000061except NameError:
Fred Drake526a1822000-09-11 04:00:46 +000062 socket_map = {}
Guido van Rossum0039d7b1999-01-12 20:19:27 +000063
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000064class ExitNow (exceptions.Exception):
Fred Drake526a1822000-09-11 04:00:46 +000065 pass
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000066
67DEBUG = 0
68
69def poll (timeout=0.0, map=None):
Fred Drake526a1822000-09-11 04:00:46 +000070 global DEBUG
71 if map is None:
72 map = socket_map
73 if map:
74 r = []; w = []; e = []
75 for fd, obj in map.items():
76 if obj.readable():
77 r.append (fd)
78 if obj.writable():
79 w.append (fd)
80 r,w,e = select.select (r,w,e, timeout)
Guido van Rossum0039d7b1999-01-12 20:19:27 +000081
Fred Drake526a1822000-09-11 04:00:46 +000082 if DEBUG:
83 print r,w,e
Guido van Rossum0039d7b1999-01-12 20:19:27 +000084
Fred Drake526a1822000-09-11 04:00:46 +000085 for fd in r:
86 try:
87 obj = map[fd]
Fred Drake526a1822000-09-11 04:00:46 +000088 except KeyError:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +000089 continue
90
91 try:
92 obj.handle_read_event()
93 except ExitNow:
94 raise ExitNow
95 except:
96 obj.handle_error()
Guido van Rossum0039d7b1999-01-12 20:19:27 +000097
Fred Drake526a1822000-09-11 04:00:46 +000098 for fd in w:
99 try:
100 obj = map[fd]
Fred Drake526a1822000-09-11 04:00:46 +0000101 except KeyError:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000102 continue
103
104 try:
105 obj.handle_write_event()
106 except ExitNow:
107 raise ExitNow
108 except:
109 obj.handle_error()
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000110
111def poll2 (timeout=0.0, map=None):
Fred Drake526a1822000-09-11 04:00:46 +0000112 import poll
113 if map is None:
114 map=socket_map
Martin v. Löwisf6cc07c2001-09-19 17:31:47 +0000115 if timeout is not None:
116 # timeout is in milliseconds
117 timeout = int(timeout*1000)
Fred Drake526a1822000-09-11 04:00:46 +0000118 if map:
119 l = []
120 for fd, obj in map.items():
121 flags = 0
122 if obj.readable():
123 flags = poll.POLLIN
124 if obj.writable():
125 flags = flags | poll.POLLOUT
126 if flags:
127 l.append ((fd, flags))
128 r = poll.poll (l, timeout)
129 for fd, flags in r:
130 try:
131 obj = map[fd]
Fred Drake526a1822000-09-11 04:00:46 +0000132 except KeyError:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000133 continue
134
135 try:
136 if (flags & poll.POLLIN):
137 obj.handle_read_event()
138 if (flags & poll.POLLOUT):
139 obj.handle_write_event()
140 except ExitNow:
141 raise ExitNow
142 except:
143 obj.handle_error()
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:
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000154 for fd, obj in map.items():
155 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)
162 r = pollster.poll (timeout)
163 for fd, flags in r:
164 try:
165 obj = map[fd]
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000166 except KeyError:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000167 continue
168
169 try:
170 if (flags & select.POLLIN):
171 obj.handle_read_event()
172 if (flags & select.POLLOUT):
173 obj.handle_write_event()
174 except ExitNow:
175 raise ExitNow
176 except:
177 obj.handle_error()
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000178
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000179def loop (timeout=30.0, use_poll=0, map=None):
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000180
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000181 if map is None:
182 map=socket_map
183
Fred Drake526a1822000-09-11 04:00:46 +0000184 if use_poll:
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000185 if hasattr (select, 'poll'):
186 poll_fun = poll3
187 else:
188 poll_fun = poll2
Fred Drake526a1822000-09-11 04:00:46 +0000189 else:
190 poll_fun = poll
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000191
Fred Drake526a1822000-09-11 04:00:46 +0000192 while map:
193 poll_fun (timeout, map)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000194
195class dispatcher:
Fred Drake526a1822000-09-11 04:00:46 +0000196 debug = 0
197 connected = 0
198 accepting = 0
199 closing = 0
200 addr = None
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000201
Fred Drake526a1822000-09-11 04:00:46 +0000202 def __init__ (self, sock=None, map=None):
203 if sock:
204 self.set_socket (sock, map)
205 # I think it should inherit this anyway
206 self.socket.setblocking (0)
207 self.connected = 1
Andrew M. Kuchling4602c1b2001-10-03 17:07:25 +0000208 self.addr = sock.getpeername()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000209
Fred Drake526a1822000-09-11 04:00:46 +0000210 def __repr__ (self):
211 try:
212 status = []
213 if self.accepting and self.addr:
214 status.append ('listening')
215 elif self.connected:
216 status.append ('connected')
217 if self.addr:
Martin v. Löwis1efbe422001-09-11 15:11:27 +0000218 if type(self.addr) == types.TupleType:
Jeremy Hylton12e73bb2001-04-20 19:04:55 +0000219 status.append ('%s:%d' % self.addr)
220 else:
221 status.append (self.addr)
222 return '<%s %s at %x>' % (self.__class__.__name__,
223 ' '.join (status), id (self))
Fred Drake526a1822000-09-11 04:00:46 +0000224 except:
Jeremy Hylton12e73bb2001-04-20 19:04:55 +0000225 pass
Tim Peters8ae2df42001-05-02 05:54:44 +0000226
Jeremy Hylton12e73bb2001-04-20 19:04:55 +0000227 try:
228 ar = repr (self.addr)
229 except AttributeError:
230 ar = 'no self.addr!'
Tim Peters146965a2001-01-14 18:09:23 +0000231
Jeremy Hylton12e73bb2001-04-20 19:04:55 +0000232 return '<__repr__() failed for %s instance at %x (addr=%s)>' % \
233 (self.__class__.__name__, id (self), ar)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000234
Fred Drake526a1822000-09-11 04:00:46 +0000235 def add_channel (self, map=None):
236 #self.log_info ('adding channel %s' % self)
237 if map is None:
238 map=socket_map
239 map [self._fileno] = self
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000240
Fred Drake526a1822000-09-11 04:00:46 +0000241 def del_channel (self, map=None):
242 fd = self._fileno
243 if map is None:
244 map=socket_map
245 if map.has_key (fd):
246 #self.log_info ('closing channel %d:%s' % (fd, self))
247 del map [fd]
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000248
Fred Drake526a1822000-09-11 04:00:46 +0000249 def create_socket (self, family, type):
250 self.family_and_type = family, type
251 self.socket = socket.socket (family, type)
252 self.socket.setblocking(0)
253 self._fileno = self.socket.fileno()
254 self.add_channel()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000255
Fred Drake526a1822000-09-11 04:00:46 +0000256 def set_socket (self, sock, map=None):
257 self.__dict__['socket'] = sock
258 self._fileno = sock.fileno()
259 self.add_channel (map)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000260
Fred Drake526a1822000-09-11 04:00:46 +0000261 def set_reuse_addr (self):
262 # try to re-use a server port if possible
263 try:
264 self.socket.setsockopt (
265 socket.SOL_SOCKET, socket.SO_REUSEADDR,
Jeremy Hyltona8b5f7d2001-08-10 14:30:35 +0000266 self.socket.getsockopt (socket.SOL_SOCKET,
267 socket.SO_REUSEADDR) | 1
Fred Drake526a1822000-09-11 04:00:46 +0000268 )
Fred Drake9f9b5932001-05-11 18:28:54 +0000269 except socket.error:
Fred Drake526a1822000-09-11 04:00:46 +0000270 pass
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000271
Fred Drake526a1822000-09-11 04:00:46 +0000272 # ==================================================
273 # predicates for select()
274 # these are used as filters for the lists of sockets
275 # to pass to select().
276 # ==================================================
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000277
Fred Drake526a1822000-09-11 04:00:46 +0000278 def readable (self):
279 return 1
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000280
Fred Drake526a1822000-09-11 04:00:46 +0000281 if os.name == 'mac':
282 # The macintosh will select a listening socket for
283 # write if you let it. What might this mean?
284 def writable (self):
285 return not self.accepting
286 else:
287 def writable (self):
288 return 1
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000289
Fred Drake526a1822000-09-11 04:00:46 +0000290 # ==================================================
291 # socket object methods.
292 # ==================================================
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000293
Fred Drake526a1822000-09-11 04:00:46 +0000294 def listen (self, num):
295 self.accepting = 1
296 if os.name == 'nt' and num > 5:
297 num = 1
298 return self.socket.listen (num)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000299
Fred Drake526a1822000-09-11 04:00:46 +0000300 def bind (self, addr):
301 self.addr = addr
302 return self.socket.bind (addr)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000303
Fred Drake526a1822000-09-11 04:00:46 +0000304 def connect (self, address):
305 self.connected = 0
Jeremy Hylton12e73bb2001-04-20 19:04:55 +0000306 # XXX why not use connect_ex?
Fred Drake526a1822000-09-11 04:00:46 +0000307 try:
308 self.socket.connect (address)
309 except socket.error, why:
310 if why[0] in (EINPROGRESS, EALREADY, EWOULDBLOCK):
311 return
312 else:
313 raise socket.error, why
Andrew M. Kuchling4602c1b2001-10-03 17:07:25 +0000314 self.addr = address
Fred Drake526a1822000-09-11 04:00:46 +0000315 self.connected = 1
316 self.handle_connect()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000317
Fred Drake526a1822000-09-11 04:00:46 +0000318 def accept (self):
319 try:
320 conn, addr = self.socket.accept()
321 return conn, addr
322 except socket.error, why:
323 if why[0] == EWOULDBLOCK:
324 pass
325 else:
326 raise socket.error, why
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000327
Fred Drake526a1822000-09-11 04:00:46 +0000328 def send (self, data):
329 try:
330 result = self.socket.send (data)
331 return result
332 except socket.error, why:
333 if why[0] == EWOULDBLOCK:
334 return 0
335 else:
336 raise socket.error, why
337 return 0
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000338
Fred Drake526a1822000-09-11 04:00:46 +0000339 def recv (self, buffer_size):
340 try:
341 data = self.socket.recv (buffer_size)
342 if not data:
343 # a closed connection is indicated by signaling
344 # a read condition, and having recv() return 0.
345 self.handle_close()
346 return ''
347 else:
348 return data
349 except socket.error, why:
350 # winsock sometimes throws ENOTCONN
351 if why[0] in [ECONNRESET, ENOTCONN, ESHUTDOWN]:
352 self.handle_close()
353 return ''
354 else:
355 raise socket.error, why
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000356
Fred Drake526a1822000-09-11 04:00:46 +0000357 def close (self):
358 self.del_channel()
359 self.socket.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000360
Fred Drake526a1822000-09-11 04:00:46 +0000361 # cheap inheritance, used to pass all other attribute
362 # references to the underlying socket object.
363 def __getattr__ (self, attr):
364 return getattr (self.socket, attr)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000365
Fred Drake526a1822000-09-11 04:00:46 +0000366 # log and log_info maybe overriden to provide more sophisitcated
367 # logging and warning methods. In general, log is for 'hit' logging
Tim Peters146965a2001-01-14 18:09:23 +0000368 # and 'log_info' is for informational, warning and error logging.
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000369
Fred Drake526a1822000-09-11 04:00:46 +0000370 def log (self, message):
371 sys.stderr.write ('log: %s\n' % str(message))
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000372
Fred Drake526a1822000-09-11 04:00:46 +0000373 def log_info (self, message, type='info'):
374 if __debug__ or type != 'info':
375 print '%s: %s' % (type, message)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000376
Fred Drake526a1822000-09-11 04:00:46 +0000377 def handle_read_event (self):
378 if self.accepting:
379 # for an accepting socket, getting a read implies
380 # that we are connected
381 if not self.connected:
382 self.connected = 1
383 self.handle_accept()
384 elif not self.connected:
385 self.handle_connect()
386 self.connected = 1
387 self.handle_read()
388 else:
389 self.handle_read()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000390
Fred Drake526a1822000-09-11 04:00:46 +0000391 def handle_write_event (self):
392 # getting a write implies that we are connected
393 if not self.connected:
394 self.handle_connect()
395 self.connected = 1
396 self.handle_write()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000397
Fred Drake526a1822000-09-11 04:00:46 +0000398 def handle_expt_event (self):
399 self.handle_expt()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000400
Fred Drake526a1822000-09-11 04:00:46 +0000401 def handle_error (self):
Jeremy Hyltona8b5f7d2001-08-10 14:30:35 +0000402 nil, t, v, tbinfo = compact_traceback()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000403
Fred Drake526a1822000-09-11 04:00:46 +0000404 # sometimes a user repr method will crash.
405 try:
406 self_repr = repr (self)
407 except:
408 self_repr = '<__repr__ (self) failed for object at %0x>' % id(self)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000409
Fred Drake526a1822000-09-11 04:00:46 +0000410 self.log_info (
411 'uncaptured python exception, closing channel %s (%s:%s %s)' % (
412 self_repr,
413 t,
414 v,
415 tbinfo
416 ),
417 'error'
418 )
419 self.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000420
Fred Drake526a1822000-09-11 04:00:46 +0000421 def handle_expt (self):
422 self.log_info ('unhandled exception', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000423
Fred Drake526a1822000-09-11 04:00:46 +0000424 def handle_read (self):
425 self.log_info ('unhandled read event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000426
Fred Drake526a1822000-09-11 04:00:46 +0000427 def handle_write (self):
428 self.log_info ('unhandled write event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000429
Fred Drake526a1822000-09-11 04:00:46 +0000430 def handle_connect (self):
431 self.log_info ('unhandled connect event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000432
Fred Drake526a1822000-09-11 04:00:46 +0000433 def handle_accept (self):
434 self.log_info ('unhandled accept event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000435
Fred Drake526a1822000-09-11 04:00:46 +0000436 def handle_close (self):
437 self.log_info ('unhandled close event', 'warning')
438 self.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000439
440# ---------------------------------------------------------------------------
441# adds simple buffered output capability, useful for simple clients.
442# [for more sophisticated usage use asynchat.async_chat]
443# ---------------------------------------------------------------------------
444
445class dispatcher_with_send (dispatcher):
Fred Drake526a1822000-09-11 04:00:46 +0000446 def __init__ (self, sock=None):
447 dispatcher.__init__ (self, sock)
448 self.out_buffer = ''
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000449
Fred Drake526a1822000-09-11 04:00:46 +0000450 def initiate_send (self):
451 num_sent = 0
452 num_sent = dispatcher.send (self, self.out_buffer[:512])
453 self.out_buffer = self.out_buffer[num_sent:]
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000454
Fred Drake526a1822000-09-11 04:00:46 +0000455 def handle_write (self):
456 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000457
Fred Drake526a1822000-09-11 04:00:46 +0000458 def writable (self):
459 return (not self.connected) or len(self.out_buffer)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000460
Fred Drake526a1822000-09-11 04:00:46 +0000461 def send (self, data):
462 if self.debug:
463 self.log_info ('sending %s' % repr(data))
464 self.out_buffer = self.out_buffer + data
465 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000466
467# ---------------------------------------------------------------------------
468# used for debugging.
469# ---------------------------------------------------------------------------
470
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000471def compact_traceback ():
Fred Drake526a1822000-09-11 04:00:46 +0000472 t,v,tb = sys.exc_info()
473 tbinfo = []
474 while 1:
475 tbinfo.append ((
476 tb.tb_frame.f_code.co_filename,
Tim Peters146965a2001-01-14 18:09:23 +0000477 tb.tb_frame.f_code.co_name,
Fred Drake526a1822000-09-11 04:00:46 +0000478 str(tb.tb_lineno)
479 ))
480 tb = tb.tb_next
481 if not tb:
482 break
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000483
Fred Drake526a1822000-09-11 04:00:46 +0000484 # just to be safe
485 del tb
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000486
Fred Drake526a1822000-09-11 04:00:46 +0000487 file, function, line = tbinfo[-1]
Eric S. Raymondb49f4a42001-02-09 05:07:04 +0000488 info = '[' + '] ['.join(map(lambda x: '|'.join(x), tbinfo)) + ']'
Fred Drake526a1822000-09-11 04:00:46 +0000489 return (file, function, line), t, v, info
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000490
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000491def close_all (map=None):
Fred Drake526a1822000-09-11 04:00:46 +0000492 if map is None:
493 map=socket_map
494 for x in map.values():
495 x.socket.close()
496 map.clear()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000497
498# Asynchronous File I/O:
499#
500# After a little research (reading man pages on various unixen, and
501# digging through the linux kernel), I've determined that select()
502# isn't meant for doing doing asynchronous file i/o.
503# Heartening, though - reading linux/mm/filemap.c shows that linux
504# supports asynchronous read-ahead. So _MOST_ of the time, the data
505# will be sitting in memory for us already when we go to read it.
506#
507# What other OS's (besides NT) support async file i/o? [VMS?]
508#
509# Regardless, this is useful for pipes, and stdin/stdout...
510
511import os
512if os.name == 'posix':
Fred Drake526a1822000-09-11 04:00:46 +0000513 import fcntl
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000514
Fred Drake526a1822000-09-11 04:00:46 +0000515 class file_wrapper:
516 # here we override just enough to make a file
517 # look like a socket for the purposes of asyncore.
518 def __init__ (self, fd):
519 self.fd = fd
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000520
Fred Drake526a1822000-09-11 04:00:46 +0000521 def recv (self, *args):
522 return apply (os.read, (self.fd,)+args)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000523
Fred Drake526a1822000-09-11 04:00:46 +0000524 def send (self, *args):
525 return apply (os.write, (self.fd,)+args)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000526
Fred Drake526a1822000-09-11 04:00:46 +0000527 read = recv
528 write = send
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000529
Fred Drake526a1822000-09-11 04:00:46 +0000530 def close (self):
531 return os.close (self.fd)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000532
Fred Drake526a1822000-09-11 04:00:46 +0000533 def fileno (self):
534 return self.fd
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000535
Fred Drake526a1822000-09-11 04:00:46 +0000536 class file_dispatcher (dispatcher):
537 def __init__ (self, fd):
538 dispatcher.__init__ (self)
539 self.connected = 1
540 # set it to non-blocking mode
Fred Drakea94414a2001-05-10 15:33:31 +0000541 flags = fcntl.fcntl (fd, fcntl.F_GETFL, 0)
542 flags = flags | os.O_NONBLOCK
543 fcntl.fcntl (fd, fcntl.F_SETFL, flags)
Fred Drake526a1822000-09-11 04:00:46 +0000544 self.set_file (fd)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000545
Fred Drake526a1822000-09-11 04:00:46 +0000546 def set_file (self, fd):
547 self._fileno = fd
548 self.socket = file_wrapper (fd)
549 self.add_channel()