X-Git-Url: https://git.mxchange.org/?p=quix0rs-apt-p2p.git;a=blobdiff_plain;f=apt_p2p_Khashmir%2FDHT.py;h=4280f17c3e89a4e1cd9f376af7750acc0e685390;hp=d0a40ee708ad074a9cce9049c966aa51f312f4d3;hb=a5dd904be839e2b2896483724d6238b5a970b5de;hpb=146f1044e3661716ec4689d3ea7e6ab4ab38ae77 diff --git a/apt_p2p_Khashmir/DHT.py b/apt_p2p_Khashmir/DHT.py index d0a40ee..4280f17 100644 --- a/apt_p2p_Khashmir/DHT.py +++ b/apt_p2p_Khashmir/DHT.py @@ -5,7 +5,6 @@ """ from datetime import datetime -from StringIO import StringIO import os, sha, random from twisted.internet import defer, reactor @@ -17,6 +16,7 @@ from zope.interface import implements from apt_p2p.interfaces import IDHT, IDHTStats, IDHTStatsFactory from khashmir import Khashmir from bencode import bencode, bdecode +from khash import HASH_LENGTH try: from twisted.web2 import channel, server, resource, http, http_headers @@ -46,6 +46,8 @@ class DHT: @ivar joined: whether the DHT network has been successfully joined @type outstandingJoins: C{int} @ivar outstandingJoins: the number of bootstrap nodes that have yet to respond + @type next_rejoin: C{int} + @ivar next_rejoin: the number of seconds before retrying the next join @type foundAddrs: C{list} of (C{string}, C{int}) @ivar foundAddrs: the IP address an port that were returned by bootstrap nodes @type storing: C{dictionary} @@ -80,8 +82,10 @@ class DHT: self.bootstrap = [] self.bootstrap_node = False self.joining = None + self.khashmir = None self.joined = False self.outstandingJoins = 0 + self.next_rejoin = 20 self.foundAddrs = [] self.storing = {} self.retrieving = {} @@ -102,48 +106,77 @@ class DHT: self.bootstrap_node = self.config_parser.getboolean(section, 'BOOTSTRAP_NODE') for k in self.config_parser.options(section): # The numbers in the config file - if k in ['K', 'HASH_LENGTH', 'CONCURRENT_REQS', 'STORE_REDUNDANCY', + if k in ['CONCURRENT_REQS', 'STORE_REDUNDANCY', 'RETRIEVE_VALUES', 'MAX_FAILURES', 'PORT']: self.config[k] = self.config_parser.getint(section, k) # The times in the config file elif k in ['CHECKPOINT_INTERVAL', 'MIN_PING_INTERVAL', - 'BUCKET_STALENESS', 'KEY_EXPIRE']: + 'BUCKET_STALENESS', 'KEY_EXPIRE', + 'KRPC_TIMEOUT', 'KRPC_INITIAL_DELAY']: self.config[k] = self.config_parser.gettime(section, k) # The booleans in the config file - elif k in ['SPEW']: + elif k in ['SPEW', 'LOCAL_OK']: self.config[k] = self.config_parser.getboolean(section, k) # Everything else is a string else: self.config[k] = self.config_parser.get(section, k) - def join(self): - """See L{apt_p2p.interfaces.IDHT}.""" - if self.config is None: - raise DHTError, "configuration not loaded" + def join(self, deferred = None): + """See L{apt_p2p.interfaces.IDHT}. + + @param deferred: the deferred to callback when the join is complete + (optional, defaults to creating a new deferred and returning it) + """ + # Check for multiple simultaneous joins if self.joining: - raise DHTError, "a join is already in progress" + if deferred: + deferred.errback(DHTError("a join is already in progress")) + return + else: + raise DHTError, "a join is already in progress" + + if deferred: + self.joining = deferred + else: + self.joining = defer.Deferred() + + if self.config is None: + self.joining.errback(DHTError("configuration not loaded")) + return self.joining # Create the new khashmir instance - self.khashmir = Khashmir(self.config, self.cache_dir) - - self.joining = defer.Deferred() + if not self.khashmir: + self.khashmir = Khashmir(self.config, self.cache_dir) + + self.outstandingJoins = 0 for node in self.bootstrap: host, port = node.rsplit(':', 1) port = int(port) + self.outstandingJoins += 1 # Translate host names into IP addresses if isIPAddress(host): self._join_gotIP(host, port) else: - reactor.resolve(host).addCallback(self._join_gotIP, port) + reactor.resolve(host).addCallbacks(self._join_gotIP, + self._join_resolveFailed, + callbackArgs = (port, ), + errbackArgs = (host, port)) return self.joining def _join_gotIP(self, ip, port): """Join the DHT using a single bootstrap nodes IP address.""" - self.outstandingJoins += 1 self.khashmir.addContact(ip, port, self._join_single, self._join_error) + def _join_resolveFailed(self, err, host, port): + """Failed to lookup the IP address of the bootstrap node.""" + log.msg('Failed to find an IP address for host: (%r, %r)' % (host, port)) + log.err(err) + self.outstandingJoins -= 1 + if self.outstandingJoins <= 0: + self.khashmir.findCloseNodes(self._join_complete) + def _join_single(self, addr): """Process the response from the bootstrap node. @@ -153,7 +186,7 @@ class DHT: if addr: self.foundAddrs.append(addr) if addr or self.outstandingJoins <= 0: - self.khashmir.findCloseNodes(self._join_complete, self._join_complete) + self.khashmir.findCloseNodes(self._join_complete) log.msg('Got back from bootstrap node: %r' % (addr,)) def _join_error(self, failure = None): @@ -165,11 +198,11 @@ class DHT: self.outstandingJoins -= 1 log.msg("bootstrap node could not be reached") if self.outstandingJoins <= 0: - self.khashmir.findCloseNodes(self._join_complete, self._join_complete) + self.khashmir.findCloseNodes(self._join_complete) def _join_complete(self, result): """End the joining process and return the addresses found for this node.""" - if not self.joined and len(result) > 0: + if not self.joined and isinstance(result, list) and len(result) > 1: self.joined = True if self.joining and self.outstandingJoins <= 0: df = self.joining @@ -178,7 +211,10 @@ class DHT: self.joined = True df.callback(self.foundAddrs) else: - df.errback(DHTError('could not find any nodes to bootstrap to')) + # Try to join later using exponential backoff delays + log.msg('Join failed, retrying in %d seconds' % self.next_rejoin) + reactor.callLater(self.next_rejoin, self.join, df) + self.next_rejoin *= 2 def getAddrs(self): """Get the list of addresses returned by bootstrap nodes for this node.""" @@ -196,33 +232,26 @@ class DHT: self.joined = False self.khashmir.shutdown() - def _normKey(self, key, bits=None, bytes=None): + def _normKey(self, key): """Normalize the length of keys used in the DHT.""" - bits = self.config["HASH_LENGTH"] - if bits is not None: - bytes = (bits - 1) // 8 + 1 - else: - if bytes is None: - raise DHTError, "you must specify one of bits or bytes for normalization" - # Extend short keys with null bytes - if len(key) < bytes: - key = key + '\000'*(bytes - len(key)) + if len(key) < HASH_LENGTH: + key = key + '\000'*(HASH_LENGTH - len(key)) # Truncate long keys - elif len(key) > bytes: - key = key[:bytes] + elif len(key) > HASH_LENGTH: + key = key[:HASH_LENGTH] return key def getValue(self, key): """See L{apt_p2p.interfaces.IDHT}.""" if self.config is None: - raise DHTError, "configuration not loaded" + return defer.fail(DHTError("configuration not loaded")) if not self.joined: - raise DHTError, "have not joined a network yet" + return defer.fail(DHTError("have not joined a network yet")) + d = defer.Deferred() key = self._normKey(key) - d = defer.Deferred() if key not in self.retrieving: self.khashmir.valueForKey(key, self._getValue) self.retrieving.setdefault(key, []).append(d) @@ -247,17 +276,17 @@ class DHT: def storeValue(self, key, value): """See L{apt_p2p.interfaces.IDHT}.""" if self.config is None: - raise DHTError, "configuration not loaded" + return defer.fail(DHTError("configuration not loaded")) if not self.joined: - raise DHTError, "have not joined a network yet" + return defer.fail(DHTError("have not joined a network yet")) + d = defer.Deferred() key = self._normKey(key) bvalue = bencode(value) if key in self.storing and bvalue in self.storing[key]: raise DHTError, "already storing that key with the same value" - d = defer.Deferred() self.khashmir.storeValueForKey(key, bvalue, self._storeValue) self.storing.setdefault(key, {})[bvalue] = d return d @@ -276,33 +305,7 @@ class DHT: def getStats(self): """See L{apt_p2p.interfaces.IDHTStats}.""" - stats = self.khashmir.getStats() - out = StringIO() - out.write('
Statistic | Value | ||||
---|---|---|---|---|---|
Action | Sent | OK | Failed | Received | Error |
" + stat['desc'] + ' | ' + str(stat['value']) + ' | ||||
" + action + " | ") - for i in xrange(5): - out.write("" + str(stat['value'][action][i]) + " | ") - out.write('