]> git.mxchange.org Git - quix0rs-apt-p2p.git/blobdiff - apt_p2p/apt_p2p.py
Switch the user name on startup.
[quix0rs-apt-p2p.git] / apt_p2p / apt_p2p.py
index 887f136a52c1453c5b3e35751cfae6c7823a1ff4..4200f6299b78377593ce17cd6ad7b6973de7578e 100644 (file)
@@ -6,11 +6,12 @@
 @var TORRENT_PIECES: the maximum number of pieces to store as a separate entry
     in the DHT
 @var download_dir: the name of the directory to use for downloaded files
-
+@var peer_dir: the name of the directory to use for peer downloads
 """
 
 from binascii import b2a_hex
 from urlparse import urlunparse
+from urllib import unquote
 import os, re, sha
 
 from twisted.internet import defer, reactor
@@ -26,12 +27,14 @@ from MirrorManager import MirrorManager
 from CacheManager import CacheManager
 from Hash import HashObject
 from db import DB
+from stats import StatsLogger
 from util import findMyIPAddr, compact
 
 DHT_PIECES = 4
 TORRENT_PIECES = 70
 
 download_dir = 'cache'
+peer_dir = 'peers'
 
 class AptP2P:
     """The main code object that does all of the work.
@@ -47,6 +50,8 @@ class AptP2P:
     @ivar db: the database to use for tracking files and hashes
     @type dht: L{interfaces.IDHT}
     @ivar dht: the DHT instance
+    @type stats: L{stats.StatsLogger}
+    @ivar stats: the statistics logger to record sent data to
     @type http_server: L{HTTPServer.TopLevel}
     @ivar http_server: the web server that will handle all requests from apt
         and from other peers
@@ -65,28 +70,34 @@ class AptP2P:
     def __init__(self, dhtClass):
         """Initialize all the sub-components.
         
-        @type dht: L{interfaces.IDHT}
-        @param dht: the DHT class to use
+        @type dhtClass: L{interfaces.IDHT}
+        @param dhtClass: the DHT class to use
         """
         log.msg('Initializing the main apt_p2p application')
         self.dhtClass = dhtClass
         self.cache_dir = FilePath(config.get('DEFAULT', 'CACHE_DIR'))
         if not self.cache_dir.child(download_dir).exists():
             self.cache_dir.child(download_dir).makedirs()
+        if not self.cache_dir.child(peer_dir).exists():
+            self.cache_dir.child(peer_dir).makedirs()
         self.db = DB(self.cache_dir.child('apt-p2p.db'))
         self.dht = dhtClass()
         self.dht.loadConfig(config, config.get('DEFAULT', 'DHT'))
         self.dht.join().addCallbacks(self.joinComplete, self.joinError)
-        self.http_server = TopLevel(self.cache_dir.child(download_dir), self.db, self,
-                                    config.getint('DEFAULT', 'UPLOAD_LIMIT'))
+        self.stats = StatsLogger(self.db)
+        self.http_server = TopLevel(self.cache_dir.child(download_dir), self.db, self)
         self.getHTTPFactory = self.http_server.getHTTPFactory
-        self.peers = PeerManager()
-        self.mirrors = MirrorManager(self.cache_dir, config.gettime('DEFAULT', 'UNLOAD_PACKAGES_CACHE'))
-        other_dirs = [FilePath(f) for f in config.getstringlist('DEFAULT', 'OTHER_DIRS')]
-        self.cache = CacheManager(self.cache_dir.child(download_dir), self.db, other_dirs, self)
+        self.peers = PeerManager(self.cache_dir.child(peer_dir), self.dht, self.stats)
+        self.mirrors = MirrorManager(self.cache_dir)
+        self.cache = CacheManager(self.cache_dir.child(download_dir), self.db, self)
         self.my_contact = None
+        reactor.addSystemEventTrigger('before', 'shutdown', self.shutdown)
 
-    #{ DHT maintenance
+    #{ Maintenance
+    def shutdown(self):
+        self.stats.save()
+        self.db.close()
+        
     def joinComplete(self, result):
         """Complete the DHT join process and determine our download information.
         
@@ -137,6 +148,8 @@ class AptP2P:
         @return: the formatted HTML page containing the statistics
         """
         out = '<html><body>\n\n'
+        out += self.stats.formatHTML(self.my_contact)
+        out += '\n\n'
         if IDHTStats.implementedBy(self.dhtClass):
             out += self.dht.getStats()
         out += '\n</body></html>\n'
@@ -158,7 +171,8 @@ class AptP2P:
         """
         log.msg('Checking if %s is still fresh' % url)
         d = self.peers.get('', url, method = "HEAD", modtime = modtime)
-        d.addCallback(self.check_freshness_done, req, url, resp)
+        d.addCallbacks(self.check_freshness_done, self.check_freshness_error,
+                       callbackArgs = (req, url, resp), errbackArgs = (req, url))
         return d
     
     def check_freshness_done(self, resp, req, url, orig_resp):
@@ -179,6 +193,17 @@ class AptP2P:
             log.msg('Stale, need to redownload: %s' % url)
             return self.get_resp(req, url)
     
+    def check_freshness_error(self, err, req, url):
+        """Mirror request failed, continue with download.
+        
+        @param err: the response from the mirror to the HEAD request
+        @type req: L{twisted.web2.http.Request}
+        @param req: the initial request sent to the HTTP server by apt
+        @param url: the URI of the actual mirror request
+        """
+        log.err(err)
+        return self.get_resp(req, url)
+    
     def get_resp(self, req, url):
         """Lookup a hash for the file in the local mirror info.
         
@@ -193,7 +218,7 @@ class AptP2P:
         d = defer.Deferred()
         
         log.msg('Trying to find hash for %s' % url)
-        findDefer = self.mirrors.findHash(url)
+        findDefer = self.mirrors.findHash(unquote(url))
         
         findDefer.addCallbacks(self.findHash_done, self.findHash_error, 
                                callbackArgs=(req, url, d), errbackArgs=(req, url, d))
@@ -270,7 +295,7 @@ class AptP2P:
         log.msg('Looking up hash in DHT for file: %s' % url)
         key = hash.expected()
         lookupDefer = self.dht.getValue(key)
-        lookupDefer.addCallback(self.lookupHash_done, hash, url, d)
+        lookupDefer.addBoth(self.lookupHash_done, hash, url, d)
 
     def lookupHash_done(self, values, hash, url, d):
         """Start the download of the file.
@@ -282,8 +307,11 @@ class AptP2P:
         @param values: the returned values from the DHT containing peer
             download information
         """
-        if not values:
-            log.msg('Peers for %s were not found' % url)
+        if not isinstance(values, list) or not values:
+            if not isinstance(values, list):
+                log.msg('DHT lookup for %s failed with error %r' % (url, values))
+            else:
+                log.msg('Peers for %s were not found' % url)
             getDefer = self.peers.get(hash, url)
             getDefer.addCallback(self.cache.save_file, hash, url)
             getDefer.addErrback(self.cache.save_error, url)
@@ -359,7 +387,8 @@ class AptP2P:
             value['l'] = sha.new(''.join(pieces)).digest()
 
         storeDefer = self.dht.storeValue(key, value)
-        storeDefer.addCallback(self.store_done, hash)
+        storeDefer.addCallbacks(self.store_done, self.store_error,
+                                callbackArgs = (hash, ), errbackArgs = (hash.digest(), ))
         return storeDefer
 
     def store_done(self, result, hash):
@@ -372,7 +401,8 @@ class AptP2P:
             value = {'t': ''.join(pieces)}
 
             storeDefer = self.dht.storeValue(key, value)
-            storeDefer.addCallback(self.store_torrent_done, key)
+            storeDefer.addCallbacks(self.store_torrent_done, self.store_error,
+                                    callbackArgs = (key, ), errbackArgs = (key, ))
             return storeDefer
         return result
 
@@ -380,4 +410,9 @@ class AptP2P:
         """Adding the file to the DHT is complete, and so is the workflow."""
         log.msg('Added torrent string %s to the DHT: %r' % (b2a_hex(key), result))
         return result
+
+    def store_error(self, err, key):
+        """Adding to the DHT failed."""
+        log.msg('An error occurred adding %s to the DHT: %r' % (b2a_hex(key), err))
+        return err
     
\ No newline at end of file