Unload the AptPackages caches after a period of inactivity.
[quix0rs-apt-p2p.git] / apt_dht / MirrorManager.py
1
2 from urlparse import urlparse
3 import os
4
5 from twisted.python import log
6 from twisted.python.filepath import FilePath
7 from twisted.internet import defer
8 from twisted.trial import unittest
9 from twisted.web2.http import splitHostPort
10
11 from AptPackages import AptPackages
12
13 aptpkg_dir='apt-packages'
14
15 class MirrorError(Exception):
16     """Exception raised when there's a problem with the mirror."""
17
18 class MirrorManager:
19     """Manages all requests for mirror objects."""
20     
21     def __init__(self, cache_dir, unload_delay):
22         self.cache_dir = cache_dir
23         self.unload_delay = unload_delay
24         self.apt_caches = {}
25     
26     def extractPath(self, url):
27         parsed = urlparse(url)
28         host, port = splitHostPort(parsed[0], parsed[1])
29         site = host + ":" + str(port)
30         path = parsed[2]
31             
32         i = max(path.rfind('/dists/'), path.rfind('/pool/'))
33         if i >= 0:
34             baseDir = path[:i]
35             path = path[i:]
36         else:
37             # Uh oh, this is not good
38             log.msg("Couldn't find a good base directory for path: %s" % (site + path))
39             baseDir = ''
40             if site in self.apt_caches:
41                 longest_match = 0
42                 for base in self.apt_caches[site]:
43                     base_match = ''
44                     for dirs in path.split('/'):
45                         if base.startswith(base_match + '/' + dirs):
46                             base_match += '/' + dirs
47                         else:
48                             break
49                     if len(base_match) > longest_match:
50                         longest_match = len(base_match)
51                         baseDir = base_match
52             log.msg("Settled on baseDir: %s" % baseDir)
53         
54         return site, baseDir, path
55         
56     def init(self, site, baseDir):
57         if site not in self.apt_caches:
58             self.apt_caches[site] = {}
59             
60         if baseDir not in self.apt_caches[site]:
61             site_cache = self.cache_dir.child(aptpkg_dir).child('mirrors').child(site + baseDir.replace('/', '_'))
62             site_cache.makedirs
63             self.apt_caches[site][baseDir] = AptPackages(site_cache, self.unload_delay)
64     
65     def updatedFile(self, url, file_path):
66         site, baseDir, path = self.extractPath(url)
67         self.init(site, baseDir)
68         self.apt_caches[site][baseDir].file_updated(path, file_path)
69
70     def findHash(self, url):
71         site, baseDir, path = self.extractPath(url)
72         if site in self.apt_caches and baseDir in self.apt_caches[site]:
73             return self.apt_caches[site][baseDir].findHash(path)
74         d = defer.Deferred()
75         d.errback(MirrorError("Site Not Found"))
76         return d
77     
78 class TestMirrorManager(unittest.TestCase):
79     """Unit tests for the mirror manager."""
80     
81     timeout = 20
82     pending_calls = []
83     client = None
84     
85     def setUp(self):
86         self.client = MirrorManager(FilePath('/tmp/.apt-dht'), 300)
87         
88     def test_extractPath(self):
89         site, baseDir, path = self.client.extractPath('http://ftp.us.debian.org/debian/dists/unstable/Release')
90         self.failUnless(site == "ftp.us.debian.org:80", "no match: %s" % site)
91         self.failUnless(baseDir == "/debian", "no match: %s" % baseDir)
92         self.failUnless(path == "/dists/unstable/Release", "no match: %s" % path)
93
94         site, baseDir, path = self.client.extractPath('http://ftp.us.debian.org:16999/debian/pool/d/dpkg/dpkg_1.2.1-1.tar.gz')
95         self.failUnless(site == "ftp.us.debian.org:16999", "no match: %s" % site)
96         self.failUnless(baseDir == "/debian", "no match: %s" % baseDir)
97         self.failUnless(path == "/pool/d/dpkg/dpkg_1.2.1-1.tar.gz", "no match: %s" % path)
98
99         site, baseDir, path = self.client.extractPath('http://debian.camrdale.org/dists/unstable/Release')
100         self.failUnless(site == "debian.camrdale.org:80", "no match: %s" % site)
101         self.failUnless(baseDir == "", "no match: %s" % baseDir)
102         self.failUnless(path == "/dists/unstable/Release", "no match: %s" % path)
103
104     def verifyHash(self, found_hash, path, true_hash):
105         self.failUnless(found_hash.hexexpected() == true_hash, 
106                     "%s hashes don't match: %s != %s" % (path, found_hash.hexexpected(), true_hash))
107
108     def test_findHash(self):
109         self.packagesFile = os.popen('ls -Sr /var/lib/apt/lists/ | grep -E "_main_.*Packages$" | tail -n 1').read().rstrip('\n')
110         self.sourcesFile = os.popen('ls -Sr /var/lib/apt/lists/ | grep -E "_main_.*Sources$" | tail -n 1').read().rstrip('\n')
111         for f in os.walk('/var/lib/apt/lists').next()[2]:
112             if f[-7:] == "Release" and self.packagesFile.startswith(f[:-7]):
113                 self.releaseFile = f
114                 break
115         
116         self.client.updatedFile('http://' + self.releaseFile.replace('_','/'), 
117                                 FilePath('/var/lib/apt/lists/' + self.releaseFile))
118         self.client.updatedFile('http://' + self.releaseFile[:self.releaseFile.find('_dists_')+1].replace('_','/') +
119                                 self.packagesFile[self.packagesFile.find('_dists_')+1:].replace('_','/'), 
120                                 FilePath('/var/lib/apt/lists/' + self.packagesFile))
121         self.client.updatedFile('http://' + self.releaseFile[:self.releaseFile.find('_dists_')+1].replace('_','/') +
122                                 self.sourcesFile[self.sourcesFile.find('_dists_')+1:].replace('_','/'), 
123                                 FilePath('/var/lib/apt/lists/' + self.sourcesFile))
124
125         lastDefer = defer.Deferred()
126         
127         idx_hash = os.popen('grep -A 3000 -E "^SHA1:" ' + 
128                             '/var/lib/apt/lists/' + self.releaseFile + 
129                             ' | grep -E " main/binary-i386/Packages.bz2$"'
130                             ' | head -n 1 | cut -d\  -f 2').read().rstrip('\n')
131         idx_path = 'http://' + self.releaseFile.replace('_','/')[:-7] + 'main/binary-i386/Packages.bz2'
132
133         d = self.client.findHash(idx_path)
134         d.addCallback(self.verifyHash, idx_path, idx_hash)
135
136         pkg_hash = os.popen('grep -A 30 -E "^Package: dpkg$" ' + 
137                             '/var/lib/apt/lists/' + self.packagesFile + 
138                             ' | grep -E "^SHA1:" | head -n 1' + 
139                             ' | cut -d\  -f 2').read().rstrip('\n')
140         pkg_path = 'http://' + self.releaseFile[:self.releaseFile.find('_dists_')+1].replace('_','/') + \
141                    os.popen('grep -A 30 -E "^Package: dpkg$" ' + 
142                             '/var/lib/apt/lists/' + self.packagesFile + 
143                             ' | grep -E "^Filename:" | head -n 1' + 
144                             ' | cut -d\  -f 2').read().rstrip('\n')
145
146         d = self.client.findHash(pkg_path)
147         d.addCallback(self.verifyHash, pkg_path, pkg_hash)
148
149         src_dir = os.popen('grep -A 30 -E "^Package: dpkg$" ' + 
150                             '/var/lib/apt/lists/' + self.sourcesFile + 
151                             ' | grep -E "^Directory:" | head -n 1' + 
152                             ' | cut -d\  -f 2').read().rstrip('\n')
153         src_hashes = os.popen('grep -A 20 -E "^Package: dpkg$" ' + 
154                             '/var/lib/apt/lists/' + self.sourcesFile + 
155                             ' | grep -A 4 -E "^Files:" | grep -E "^ " ' + 
156                             ' | cut -d\  -f 2').read().split('\n')[:-1]
157         src_paths = os.popen('grep -A 20 -E "^Package: dpkg$" ' + 
158                             '/var/lib/apt/lists/' + self.sourcesFile + 
159                             ' | grep -A 4 -E "^Files:" | grep -E "^ " ' + 
160                             ' | cut -d\  -f 4').read().split('\n')[:-1]
161
162         for i in range(len(src_hashes)):
163             src_path = 'http://' + self.releaseFile[:self.releaseFile.find('_dists_')+1].replace('_','/') + src_dir + '/' + src_paths[i]
164             d = self.client.findHash(src_path)
165             d.addCallback(self.verifyHash, src_path, src_hashes[i])
166             
167         idx_hash = os.popen('grep -A 3000 -E "^SHA1:" ' + 
168                             '/var/lib/apt/lists/' + self.releaseFile + 
169                             ' | grep -E " main/source/Sources.bz2$"'
170                             ' | head -n 1 | cut -d\  -f 2').read().rstrip('\n')
171         idx_path = 'http://' + self.releaseFile.replace('_','/')[:-7] + 'main/source/Sources.bz2'
172
173         d = self.client.findHash(idx_path)
174         d.addCallback(self.verifyHash, idx_path, idx_hash)
175
176         d.addBoth(lastDefer.callback)
177         return lastDefer
178
179     def tearDown(self):
180         for p in self.pending_calls:
181             if p.active():
182                 p.cancel()
183         self.client = None
184