1 ## Copyright 2002-2003 Andrew Loewenstern, All Rights Reserved
2 # see LICENSE.txt for license information
4 from bencode import bencode, bdecode
5 from time import asctime
7 from traceback import format_exception
9 from twisted.internet.defer import Deferred
10 from twisted.internet import protocol, reactor
11 from twisted.trial import unittest
16 KRPC_ERROR_METHOD_UNKNOWN = 2
17 KRPC_ERROR_RECEIVED_UNKNOWN = 3
18 KRPC_ERROR_TIMEOUT = 4
28 class ProtocolError(Exception):
31 class hostbroker(protocol.DatagramProtocol):
32 def __init__(self, server):
34 # this should be changed to storage that drops old entries
37 def datagramReceived(self, datagram, addr):
38 #print `addr`, `datagram`
39 #if addr != self.addr:
40 c = self.connectionForAddr(addr)
41 c.datagramReceived(datagram, addr)
43 # del self.connections[addr]
45 def connectionForAddr(self, addr):
48 if not self.connections.has_key(addr):
49 conn = self.protocol(addr, self.server, self.transport)
50 self.connections[addr] = conn
52 conn = self.connections[addr]
55 def makeConnection(self, transport):
56 protocol.DatagramProtocol.makeConnection(self, transport)
57 tup = transport.getHost()
58 self.addr = (tup.host, tup.port)
60 def stopProtocol(self):
61 for conn in self.connections.values():
63 protocol.DatagramProtocol.stopProtocol(self)
68 def __init__(self, addr, server, transport):
69 self.transport = transport
76 def datagramReceived(self, str, addr):
79 print "stopped, dropping message from", addr, str
85 print "response decode error: " + `e`
93 # tell factory to handle
94 f = getattr(self.factory ,"krpc_" + msg[REQ], None)
95 msg[ARG]['_krpc_sender'] = self.addr
98 ret = apply(f, (), msg[ARG])
101 out = bencode({TID:msg[TID], TYP:ERR, ERR :`format_exception(type(e), e, sys.exc_info()[2])`})
103 self.transport.write(out, addr)
107 out = bencode({TID : msg[TID], TYP : RSP, RSP : ret})
109 out = bencode({TID : msg[TID], TYP : RSP, RSP : {}})
112 self.transport.write(out, addr)
116 print "don't know about method %s" % msg[REQ]
118 out = bencode({TID:msg[TID], TYP:ERR, ERR : KRPC_ERROR_METHOD_UNKNOWN})
120 self.transport.write(out, addr)
122 print "%s %s >>> %s - %s %s %s" % (asctime(), addr, self.factory.node.port,
123 ilen, msg[REQ], olen)
124 elif msg[TYP] == RSP:
127 if self.tids.has_key(msg[TID]):
128 df = self.tids[msg[TID]]
130 del(self.tids[msg[TID]])
131 df.callback({'rsp' : msg[RSP], '_krpc_sender': addr})
133 print 'timeout ' + `msg[RSP]['id']`
134 # no tid, this transaction timed out already...
135 elif msg[TYP] == ERR:
138 if self.tids.has_key(msg[TID]):
139 df = self.tids[msg[TID]]
142 del(self.tids[msg[TID]])
144 # day late and dollar short
147 print "unknown message type " + `msg`
148 # unknown message type
149 df = self.tids[msg[TID]]
151 df.errback(KRPC_ERROR_RECEIVED_UNKNOWN)
152 del(self.tids[msg[TID]])
154 def sendRequest(self, method, args):
156 raise ProtocolError, "connection has been stopped"
159 msg = {TID : chr(self.mtid), TYP : REQ, REQ : method, ARG : args}
160 self.mtid = (self.mtid + 1) % 256
163 self.tids[msg[TID]] = d
164 def timeOut(tids = self.tids, id = msg[TID], msg = msg):
168 print ">>>>>> KRPC_ERROR_TIMEOUT"
169 df.errback(ProtocolError('timeout waiting for %r' % msg))
170 later = reactor.callLater(KRPC_TIMEOUT, timeOut)
171 def dropTimeOut(dict, later_call = later):
172 if later_call.active():
175 d.addBoth(dropTimeOut)
176 self.transport.write(str, self.addr)
180 """Timeout all pending requests."""
181 for df in self.tids.values():
182 df.errback(ProtocolError('connection has been closed'))
186 def connectionForAddr(host, port):
189 class Receiver(protocol.Factory):
193 def krpc_store(self, msg, _krpc_sender):
195 def krpc_echo(self, msg, _krpc_sender):
202 p = reactor.listenUDP(port, a)
205 class KRPCTests(unittest.TestCase):
208 self.af, self.a, self.ap = make(1180)
209 self.bf, self.b, self.bp = make(1181)
212 self.ap.stopListening()
213 self.bp.stopListening()
215 def bufEquals(self, result, value):
216 self.assertEqual(self.bf.buf, value)
218 def testSimpleMessage(self):
219 d = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('store', {'msg' : "This is a test."})
220 d.addCallback(self.bufEquals, ["This is a test."])
223 def testMessageBlast(self):
225 d = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('store', {'msg' : "This is a test."})
226 d.addCallback(self.bufEquals, ["This is a test."] * 100)
230 df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is a test."})
231 df.addCallback(self.gotMsg, "This is a test.")
234 def gotMsg(self, dict, should_be):
235 _krpc_sender = dict['_krpc_sender']
237 self.assertEqual(msg, should_be)
239 def testManyEcho(self):
240 for i in xrange(100):
241 df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is a test."})
242 df.addCallback(self.gotMsg, "This is a test.")
245 def testMultiEcho(self):
246 df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is a test."})
247 df.addCallback(self.gotMsg, "This is a test.")
249 df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is another test."})
250 df.addCallback(self.gotMsg, "This is another test.")
252 df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is yet another test."})
253 df.addCallback(self.gotMsg, "This is yet another test.")
257 def testEchoReset(self):
258 df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is a test."})
259 df.addCallback(self.gotMsg, "This is a test.")
261 df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is another test."})
262 df.addCallback(self.gotMsg, "This is another test.")
263 df.addCallback(self.echoReset)
266 def echoReset(self, dict):
267 del(self.a.connections[('127.0.0.1', 1181)])
268 df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is yet another test."})
269 df.addCallback(self.gotMsg, "This is yet another test.")
272 def testUnknownMeth(self):
273 df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('blahblah', {'msg' : "This is a test."})
274 df.addErrback(self.gotErr, KRPC_ERROR_METHOD_UNKNOWN)
277 def gotErr(self, err, should_be):
278 self.assertEqual(err.value, should_be)