]> git.mxchange.org Git - quix0rs-apt-p2p.git/blob - apt_dht_Khashmir/DHT.py
Add more to khashmir's DHT implementation.
[quix0rs-apt-p2p.git] / apt_dht_Khashmir / DHT.py
1
2 from twisted.internet import defer
3 from zope.interface import implements
4
5 from apt_dht.interfaces import IDHT
6 from khashmir import Khashmir
7
8 class DHTError(Exception):
9     """Represents errors that occur in the DHT."""
10
11 class DHT:
12     
13     implements(IDHT)
14     
15     def __init__(self):
16         self.config = None
17     
18     def loadConfig(self, config, section):
19         """See L{apt_dht.interfaces.IDHT}."""
20         self.config = config
21         self.section = section
22         if self.config.has_option(section, 'port'):
23             self.port = self.config.get(section, 'port')
24         else:
25             self.port = self.config.get('DEFAULT', 'port')
26     
27     def join(self):
28         """See L{apt_dht.interfaces.IDHT}."""
29         if self.config is None:
30             raise DHTError, "configuration not loaded"
31
32         self.khashmir = Khashmir('', self.port)
33         
34         for node in self.config.get(self.section, 'bootstrap'):
35             host, port = node.rsplit(':', 1)
36             self.khashmir.addContact(host, port)
37             
38         self.khashmir.findCloseNodes()
39         
40     def leave(self):
41         """See L{apt_dht.interfaces.IDHT}."""
42         if self.config is None:
43             raise DHTError, "configuration not loaded"
44
45         self.khashmir.listenport.stopListening()
46         
47     def getValue(self, key):
48         """See L{apt_dht.interfaces.IDHT}."""
49         if self.config is None:
50             raise DHTError, "configuration not loaded"
51
52         d = defer.Deferred()
53         self.khashmir.valueForKey(key, d.callback)
54         return d
55         
56     def storeValue(self, key, value):
57         """See L{apt_dht.interfaces.IDHT}."""
58         if self.config is None:
59             raise DHTError, "configuration not loaded"
60
61         self.khashmir.storeValueForKey(key, value)