1 ## Copyright 2002 Andrew Loewenstern, All Rights Reserved
3 from const import reactor
5 from pickle import loads, dumps
8 from ktable import KTable, K
9 from knode import KNode as Node
11 from hash import newID
13 from actions import FindNode, GetValue, KeyExpirer
14 from twisted.web import xmlrpc
15 from twisted.internet.defer import Deferred
16 from twisted.python import threadable
17 from twisted.internet.app import Application
18 from twisted.web import server
21 from bsddb3 import db ## find this at http://pybsddb.sf.net/
22 from bsddb3._db import DBNotFoundError
24 # don't ping unless it's been at least this many seconds since we've heard from a peer
25 MAX_PING_INTERVAL = 60 * 15 # fifteen minutes
29 # this is the main class!
30 class Khashmir(xmlrpc.XMLRPC):
31 __slots__ = ['listener', 'node', 'table', 'store', 'itime', 'kw', 'app']
32 def __init__(self, host, port):
33 self.node = Node(newID(), host, port)
34 self.table = KTable(self.node)
35 self.app = Application("xmlrpc")
36 self.app.listenTCP(port, server.Site(self))
38 ## these databases may be more suited to on-disk rather than in-memory
39 # h((key, value)) -> (key, value, time) mappings
41 self.store.open(None, None, db.DB_BTREE)
43 # <insert time> -> h((key, value))
45 self.itime.set_flags(db.DB_DUP)
46 self.itime.open(None, None, db.DB_BTREE)
48 # key -> h((key, value))
50 self.kw.set_flags(db.DB_DUP)
51 self.kw.open(None, None, db.DB_BTREE)
53 KeyExpirer(store=self.store, itime=self.itime, kw=self.kw)
55 def render(self, request):
57 Override the built in render so we can have access to the request object!
58 note, crequest is probably only valid on the initial call (not after deferred!)
60 self.crequest = request
61 return xmlrpc.XMLRPC.render(self, request)
65 ####### LOCAL INTERFACE - use these methods!
66 def addContact(self, host, port):
68 ping this node and add the contact info to the table on pong!
70 n =Node(" "*20, host, port) # note, we
74 ## this call is async!
75 def findNode(self, id, callback, errback=None):
76 """ returns the contact info for node, or the k closest nodes, from the global table """
77 # get K nodes out of local table/cache, or the node we want
78 nodes = self.table.findNodes(id)
80 d.addCallbacks(callback, errback)
81 if len(nodes) == 1 and nodes[0].id == id :
84 # create our search state
85 state = FindNode(self, id, d.callback)
86 reactor.callFromThread(state.goWithNodes, nodes)
90 def valueForKey(self, key, callback):
91 """ returns the values found for key in global table """
92 nodes = self.table.findNodes(key)
93 # create our search state
94 state = GetValue(self, key, callback)
95 reactor.callFromThread(state.goWithNodes, nodes)
99 ## async, but in the current implementation there is no guarantee a store does anything so there is no callback right now
100 def storeValueForKey(self, key, value, callback=None):
101 """ stores the value for key in the global table, returns immediately, no status
102 in this implementation, peers respond but don't indicate status to storing values
103 values are stored in peers on a first-come first-served basis
104 this will probably change so more than one value can be stored under a key
106 def _storeValueForKey(nodes, key=key, value=value, response=callback , default= lambda t: "didn't respond"):
108 # default callback - this will get called for each successful store value
109 def _storedValueHandler(sender):
111 response=_storedValueHandler
113 if node.id != self.node.id:
114 df = node.storeValue(key, value, self.node.senderDict())
115 df.addCallbacks(response, default)
116 # this call is asynch
117 self.findNode(key, _storeValueForKey)
120 def insertNode(self, n):
122 insert a node in our local table, pinging oldest contact in bucket, if necessary
124 If all you have is a host/port, then use addContact, which calls this method after
125 receiving the PONG from the remote node. The reason for the seperation is we can't insert
126 a node into the table without it's peer-ID. That means of course the node passed into this
127 method needs to be a properly formed Node object with a valid ID.
129 old = self.table.insertNode(n)
130 if old and (time.time() - old.lastSeen) > MAX_PING_INTERVAL and old.id != self.node.id:
131 # the bucket is full, check to see if old node is still around and if so, replace it
133 ## these are the callbacks used when we ping the oldest node in a bucket
134 def _staleNodeHandler(oldnode=old, newnode = n):
135 """ called if the pinged node never responds """
136 self.table.replaceStaleNode(old, newnode)
138 def _notStaleNodeHandler(sender, old=old):
139 """ called when we get a ping from the remote node """
140 if sender['id'] == old.id:
141 self.table.insertNode(old)
143 df = old.ping(self.node.senderDict())
144 df.addCallbacks(_notStaleNodeHandler, _staleNodeHandler)
147 def sendPing(self, node):
151 df = node.ping(self.node.senderDict())
152 ## these are the callbacks we use when we issue a PING
153 def _pongHandler(sender, id=node.id, host=node.host, port=node.port, table=self.table):
154 if id != 20 * ' ' and id != sender['id']:
155 # whoah, got response from different peer than we were expecting
158 #print "Got PONG from %s at %s:%s" % (`msg['id']`, t.target.host, t.target.port)
159 n = Node(sender['id'], host, port)
162 def _defaultPong(err):
163 # this should probably increment a failed message counter and dump the node if it gets over a threshold
166 df.addCallbacks(_pongHandler,_defaultPong)
169 def findCloseNodes(self):
171 This does a findNode on the ID one away from our own.
172 This will allow us to populate our table with nodes on our network closest to our own.
173 This is called as soon as we start up with an empty table
175 id = self.node.id[:-1] + chr((ord(self.node.id[-1]) + 1) % 256)
178 self.findNode(id, callback)
180 def refreshTable(self):
187 for bucket in self.table.buckets:
188 if time.time() - bucket.lastAccessed >= 60 * 60:
189 id = randRange(bucket.min, bucket.max)
190 self.findNode(id, callback)
194 ##### INCOMING MESSAGE HANDLERS
196 def xmlrpc_ping(self, sender):
198 takes sender dict = {'id', <id>, 'port', port} optional keys = 'ip'
201 ip = self.crequest.getClientIP()
202 n = Node(sender['id'], ip, sender['port'])
204 return self.node.senderDict()
206 def xmlrpc_find_node(self, target, sender):
207 nodes = self.table.findNodes(target)
208 nodes = map(lambda node: node.senderDict(), nodes)
209 ip = self.crequest.getClientIP()
210 n = Node(sender['id'], ip, sender['port'])
212 return nodes, self.node.senderDict()
214 def xmlrpc_store_value(self, key, value, sender):
215 h1 = sha(key+value).digest()
217 if not self.store.has_key(h1):
218 v = dumps((key, value, t))
219 self.store.put(h1, v)
220 self.itime.put(t, h1)
223 # update last insert time
224 tup = loads(self.store[h1])
225 self.store[h1] = dumps((tup[0], tup[1], t))
226 self.itime.put(t, h1)
228 ip = self.crequest.getClientIP()
229 n = Node(sender['id'], ip, sender['port'])
231 return self.node.senderDict()
233 def xmlrpc_find_value(self, key, sender):
234 ip = self.crequest.getClientIP()
235 n = Node(sender['id'], ip, sender['port'])
237 if self.kw.has_key(key):
243 v = loads(self.store[h1])[1]
246 return {'values' : l}, self.node.senderDict()
248 nodes = self.table.findNodes(key)
249 nodes = map(lambda node: node.senderDict(), nodes)
250 return {'nodes' : nodes}, self.node.senderDict()
258 def test_build_net(quiet=0, peers=8, pause=1):
259 from whrandom import randrange
265 print "Building %s peer table." % peers
267 for i in xrange(peers):
268 a = Khashmir('localhost', port + i)
272 thread.start_new_thread(l[0].app.run, ())
278 print "adding contacts...."
281 n = l[randrange(0, len(l))].node
282 peer.addContact(n.host, n.port)
283 n = l[randrange(0, len(l))].node
284 peer.addContact(n.host, n.port)
285 n = l[randrange(0, len(l))].node
286 peer.addContact(n.host, n.port)
291 print "finding close nodes...."
294 peer.findCloseNodes()
300 # peer.refreshTable()
303 def test_find_nodes(l, quiet=0):
304 import threading, sys
305 from whrandom import randrange
306 flag = threading.Event()
310 a = l[randrange(0,n)]
311 b = l[randrange(0,n)]
313 def callback(nodes, flag=flag):
314 if (len(nodes) >0) and (nodes[0].id == b.node.id):
315 print "test_find_nodes PASSED"
317 print "test_find_nodes FAILED"
319 a.findNode(b.node.id, callback)
322 def test_find_value(l, quiet=0):
323 from whrandom import randrange
325 from hash import newID
326 import time, threading, sys
328 fa = threading.Event()
329 fb = threading.Event()
330 fc = threading.Event()
333 a = l[randrange(0,n)]
334 b = l[randrange(0,n)]
335 c = l[randrange(0,n)]
336 d = l[randrange(0,n)]
341 print "inserting value..."
343 a.storeValueForKey(key, value)
349 def __init__(self, flag, value=value):
353 def callback(self, values):
355 if(len(values) == 0):
363 if self.val in values:
368 b.valueForKey(key, cb(fa).callback)
370 c.valueForKey(key, cb(fb).callback)
372 d.valueForKey(key, cb(fc).callback)
377 k = Khashmir('localhost', port)
378 thread.start_new_thread(k.app.run, ())
381 if __name__ == "__main__":
384 print "finding nodes..."
387 print "inserting and fetching values..."