Use the version number in the Khashmir node ID.
[quix0rs-apt-p2p.git] / apt_p2p_Khashmir / DHT.py
index f11eefc8305f87f12c10a85b5703d942ee3ed08e..dbaf6836ec327c249fb2301c822efa7268f1ea90 100644 (file)
@@ -16,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
@@ -105,15 +106,16 @@ 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:
@@ -146,23 +148,35 @@ class DHT:
         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.
         
@@ -172,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):
@@ -184,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) > 1:
+        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
@@ -218,34 +232,24 @@ 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}."""
-        d = defer.Deferred()
-
         if self.config is None:
-            d.errback(DHTError("configuration not loaded"))
-            return d
+            return defer.fail(DHTError("configuration not loaded"))
         if not self.joined:
-            d.errback(DHTError("have not joined a network yet"))
-            return d
+            return defer.fail(DHTError("have not joined a network yet"))
         
+        d = defer.Deferred()
         key = self._normKey(key)
 
         if key not in self.retrieving:
@@ -271,15 +275,12 @@ class DHT:
 
     def storeValue(self, key, value):
         """See L{apt_p2p.interfaces.IDHT}."""
-        d = defer.Deferred()
-
         if self.config is None:
-            d.errback(DHTError("configuration not loaded"))
-            return d
+            return defer.fail(DHTError("configuration not loaded"))
         if not self.joined:
-            d.errback(DHTError("have not joined a network yet"))
-            return d
+            return defer.fail(DHTError("have not joined a network yet"))
 
+        d = defer.Deferred()
         key = self._normKey(key)
         bvalue = bencode(value)
 
@@ -331,12 +332,13 @@ class TestSimpleDHT(unittest.TestCase):
     """Simple 2-node unit tests for the DHT."""
     
     timeout = 50
-    DHT_DEFAULTS = {'PORT': 9977, 'K': 8, 'HASH_LENGTH': 160,
-                    'CHECKPOINT_INTERVAL': 300, 'CONCURRENT_REQS': 4,
-                    'STORE_REDUNDANCY': 3, 'RETRIEVE_VALUES': -10000,
-                    'MAX_FAILURES': 3,
+    DHT_DEFAULTS = {'VERSION': 'A000', 'PORT': 9977,
+                    'CHECKPOINT_INTERVAL': 300, 'CONCURRENT_REQS': 8,
+                    'STORE_REDUNDANCY': 6, 'RETRIEVE_VALUES': -10000,
+                    'MAX_FAILURES': 3, 'LOCAL_OK': True,
                     'MIN_PING_INTERVAL': 900,'BUCKET_STALENESS': 3600,
-                    'KEY_EXPIRE': 3600, 'SPEW': False, }
+                    'KRPC_TIMEOUT': 9, 'KRPC_INITIAL_DELAY': 2,
+                    'KEY_EXPIRE': 3600, 'SPEW': True, }
 
     def setUp(self):
         self.a = DHT()
@@ -355,14 +357,15 @@ class TestSimpleDHT(unittest.TestCase):
         d = self.a.join()
         return d
 
-    def test_failed_join(self):
+    def no_krpc_errors(self, result):
         from krpc import KrpcError
+        self.flushLoggedErrors(KrpcError)
+        return result
+
+    def test_failed_join(self):
         d = self.b.join()
         reactor.callLater(30, self.a.join)
-        def no_errors(result, self = self):
-            self.flushLoggedErrors(KrpcError)
-            return result
-        d.addCallback(no_errors)
+        d.addCallback(self.no_krpc_errors)
         return d
         
     def node_join(self, result):
@@ -370,11 +373,14 @@ class TestSimpleDHT(unittest.TestCase):
         return d
     
     def test_join(self):
-        self.lastDefer = defer.Deferred()
         d = self.a.join()
         d.addCallback(self.node_join)
-        d.addCallback(self.lastDefer.callback)
-        return self.lastDefer
+        return d
+
+    def test_timeout_retransmit(self):
+        d = self.b.join()
+        reactor.callLater(4, self.a.join)
+        return d
 
     def test_normKey(self):
         h = self.a._normKey('12345678901234567890')
@@ -445,14 +451,15 @@ class TestSimpleDHT(unittest.TestCase):
 class TestMultiDHT(unittest.TestCase):
     """More complicated 20-node tests for the DHT."""
     
-    timeout = 80
+    timeout = 200
     num = 20
-    DHT_DEFAULTS = {'PORT': 9977, 'K': 8, 'HASH_LENGTH': 160,
-                    'CHECKPOINT_INTERVAL': 300, 'CONCURRENT_REQS': 4,
-                    'STORE_REDUNDANCY': 3, 'RETRIEVE_VALUES': -10000,
-                    'MAX_FAILURES': 3,
+    DHT_DEFAULTS = {'VERSION': 'A000', 'PORT': 9977,
+                    'CHECKPOINT_INTERVAL': 300, 'CONCURRENT_REQS': 8,
+                    'STORE_REDUNDANCY': 6, 'RETRIEVE_VALUES': -10000,
+                    'MAX_FAILURES': 3, 'LOCAL_OK': True,
                     'MIN_PING_INTERVAL': 900,'BUCKET_STALENESS': 3600,
-                    'KEY_EXPIRE': 3600, 'SPEW': False, }
+                    'KRPC_TIMEOUT': 9, 'KRPC_INITIAL_DELAY': 2,
+                    'KEY_EXPIRE': 3600, 'SPEW': True, }
 
     def setUp(self):
         self.l = []
@@ -470,7 +477,7 @@ class TestMultiDHT(unittest.TestCase):
         if next_node + 1 < len(self.l):
             d.addCallback(self.node_join, next_node + 1)
         else:
-            d.addCallback(self.lastDefer.callback)
+            reactor.callLater(1, d.addCallback, self.lastDefer.callback)
     
     def test_join(self):
         self.timeout = 2