Modify khashmir's config system to not use the const module.
[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_parser = config
21         self.section = section
22         self.config = []
23         for k in self.config_parser.options(section):
24             if k in ['K', 'HASH_LENGTH', 'CONCURRENT_REQS', 'STORE_REDUNDANCY', 
25                      'MAX_FAILURES', 'PORT']:
26                 self.config[k] = self.config_parser.getint(section, k)
27             elif k in ['CHECKPOINT_INTERVAL', 'MIN_PING_INTERVAL', 
28                        'BUCKET_STALENESS', 'KEINITIAL_DELAY', 'KE_DELAY', 'KE_AGE']:
29                 self.config[k] = self.config_parser.gettime(section, k)
30             else:
31                 self.config[k] = self.config_parser.get(section, k)
32         if 'PORT' not in self.config:
33             self.config['PORT'] = self.config_parser.getint('DEFAULT', 'PORT')
34     
35     def join(self):
36         """See L{apt_dht.interfaces.IDHT}."""
37         if self.config is None:
38             raise DHTError, "configuration not loaded"
39
40         self.khashmir = Khashmir(self.config, self.config_parser.get('DEFAULT', 'cache_dir'))
41         
42         for node in self.config_parser.get(self.section, 'BOOTSTRAP'):
43             host, port = node.rsplit(':', 1)
44             self.khashmir.addContact(host, port)
45             
46         self.khashmir.findCloseNodes()
47         
48     def leave(self):
49         """See L{apt_dht.interfaces.IDHT}."""
50         if self.config is None:
51             raise DHTError, "configuration not loaded"
52
53         self.khashmir.listenport.stopListening()
54         
55     def getValue(self, key):
56         """See L{apt_dht.interfaces.IDHT}."""
57         if self.config is None:
58             raise DHTError, "configuration not loaded"
59
60         d = defer.Deferred()
61         self.khashmir.valueForKey(key, d.callback)
62         return d
63         
64     def storeValue(self, key, value):
65         """See L{apt_dht.interfaces.IDHT}."""
66         if self.config is None:
67             raise DHTError, "configuration not loaded"
68
69         self.khashmir.storeValueForKey(key, value)