2 from urlparse import urlparse
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
11 from AptPackages import AptPackages
13 aptpkg_dir='apt-packages'
15 class MirrorError(Exception):
16 """Exception raised when there's a problem with the mirror."""
19 """Manages all requests for mirror objects."""
21 def __init__(self, cache_dir):
22 self.cache_dir = cache_dir
25 def extractPath(self, url):
26 parsed = urlparse(url)
27 host, port = splitHostPort(parsed[0], parsed[1])
28 site = host + ":" + str(port)
31 i = max(path.rfind('/dists/'), path.rfind('/pool/'))
36 # Uh oh, this is not good
37 log.msg("Couldn't find a good base directory for path: %s" % (site + path))
39 if site in self.apt_caches:
41 for base in self.apt_caches[site]:
43 for dirs in path.split('/'):
44 if base.startswith(base_match + '/' + dirs):
45 base_match += '/' + dirs
48 if len(base_match) > longest_match:
49 longest_match = len(base_match)
51 log.msg("Settled on baseDir: %s" % baseDir)
53 return site, baseDir, path
55 def init(self, site, baseDir):
56 if site not in self.apt_caches:
57 self.apt_caches[site] = {}
59 if baseDir not in self.apt_caches[site]:
60 site_cache = self.cache_dir.child(aptpkg_dir).child('mirrors').child(site + baseDir.replace('/', '_'))
62 self.apt_caches[site][baseDir] = AptPackages(site_cache)
64 def updatedFile(self, url, file_path):
65 site, baseDir, path = self.extractPath(url)
66 self.init(site, baseDir)
67 self.apt_caches[site][baseDir].file_updated(path, file_path)
69 def findHash(self, url):
70 site, baseDir, path = self.extractPath(url)
71 if site in self.apt_caches and baseDir in self.apt_caches[site]:
72 return self.apt_caches[site][baseDir].findHash(path)
74 d.errback(MirrorError("Site Not Found"))
77 class TestMirrorManager(unittest.TestCase):
78 """Unit tests for the mirror manager."""
85 self.client = MirrorManager(FilePath('/tmp/.apt-dht'))
87 def test_extractPath(self):
88 site, baseDir, path = self.client.extractPath('http://ftp.us.debian.org/debian/dists/unstable/Release')
89 self.failUnless(site == "ftp.us.debian.org:80", "no match: %s" % site)
90 self.failUnless(baseDir == "/debian", "no match: %s" % baseDir)
91 self.failUnless(path == "/dists/unstable/Release", "no match: %s" % path)
93 site, baseDir, path = self.client.extractPath('http://ftp.us.debian.org:16999/debian/pool/d/dpkg/dpkg_1.2.1-1.tar.gz')
94 self.failUnless(site == "ftp.us.debian.org:16999", "no match: %s" % site)
95 self.failUnless(baseDir == "/debian", "no match: %s" % baseDir)
96 self.failUnless(path == "/pool/d/dpkg/dpkg_1.2.1-1.tar.gz", "no match: %s" % path)
98 site, baseDir, path = self.client.extractPath('http://debian.camrdale.org/dists/unstable/Release')
99 self.failUnless(site == "debian.camrdale.org:80", "no match: %s" % site)
100 self.failUnless(baseDir == "", "no match: %s" % baseDir)
101 self.failUnless(path == "/dists/unstable/Release", "no match: %s" % path)
103 def verifyHash(self, found_hash, path, true_hash):
104 self.failUnless(found_hash.hexexpected() == true_hash,
105 "%s hashes don't match: %s != %s" % (path, found_hash.hexexpected(), true_hash))
107 def test_findHash(self):
108 self.packagesFile = os.popen('ls -Sr /var/lib/apt/lists/ | grep -E "_main_.*Packages$" | tail -n 1').read().rstrip('\n')
109 self.sourcesFile = os.popen('ls -Sr /var/lib/apt/lists/ | grep -E "_main_.*Sources$" | tail -n 1').read().rstrip('\n')
110 for f in os.walk('/var/lib/apt/lists').next()[2]:
111 if f[-7:] == "Release" and self.packagesFile.startswith(f[:-7]):
115 self.client.updatedFile('http://' + self.releaseFile.replace('_','/'),
116 FilePath('/var/lib/apt/lists/' + self.releaseFile))
117 self.client.updatedFile('http://' + self.releaseFile[:self.releaseFile.find('_dists_')+1].replace('_','/') +
118 self.packagesFile[self.packagesFile.find('_dists_')+1:].replace('_','/'),
119 FilePath('/var/lib/apt/lists/' + self.packagesFile))
120 self.client.updatedFile('http://' + self.releaseFile[:self.releaseFile.find('_dists_')+1].replace('_','/') +
121 self.sourcesFile[self.sourcesFile.find('_dists_')+1:].replace('_','/'),
122 FilePath('/var/lib/apt/lists/' + self.sourcesFile))
124 lastDefer = defer.Deferred()
126 idx_hash = os.popen('grep -A 3000 -E "^SHA1:" ' +
127 '/var/lib/apt/lists/' + self.releaseFile +
128 ' | grep -E " main/binary-i386/Packages.bz2$"'
129 ' | head -n 1 | cut -d\ -f 2').read().rstrip('\n')
130 idx_path = 'http://' + self.releaseFile.replace('_','/')[:-7] + 'main/binary-i386/Packages.bz2'
132 d = self.client.findHash(idx_path)
133 d.addCallback(self.verifyHash, idx_path, idx_hash)
135 pkg_hash = os.popen('grep -A 30 -E "^Package: dpkg$" ' +
136 '/var/lib/apt/lists/' + self.packagesFile +
137 ' | grep -E "^SHA1:" | head -n 1' +
138 ' | cut -d\ -f 2').read().rstrip('\n')
139 pkg_path = 'http://' + self.releaseFile[:self.releaseFile.find('_dists_')+1].replace('_','/') + \
140 os.popen('grep -A 30 -E "^Package: dpkg$" ' +
141 '/var/lib/apt/lists/' + self.packagesFile +
142 ' | grep -E "^Filename:" | head -n 1' +
143 ' | cut -d\ -f 2').read().rstrip('\n')
145 d = self.client.findHash(pkg_path)
146 d.addCallback(self.verifyHash, pkg_path, pkg_hash)
148 src_dir = os.popen('grep -A 30 -E "^Package: dpkg$" ' +
149 '/var/lib/apt/lists/' + self.sourcesFile +
150 ' | grep -E "^Directory:" | head -n 1' +
151 ' | cut -d\ -f 2').read().rstrip('\n')
152 src_hashes = os.popen('grep -A 20 -E "^Package: dpkg$" ' +
153 '/var/lib/apt/lists/' + self.sourcesFile +
154 ' | grep -A 4 -E "^Files:" | grep -E "^ " ' +
155 ' | cut -d\ -f 2').read().split('\n')[:-1]
156 src_paths = os.popen('grep -A 20 -E "^Package: dpkg$" ' +
157 '/var/lib/apt/lists/' + self.sourcesFile +
158 ' | grep -A 4 -E "^Files:" | grep -E "^ " ' +
159 ' | cut -d\ -f 4').read().split('\n')[:-1]
161 for i in range(len(src_hashes)):
162 src_path = 'http://' + self.releaseFile[:self.releaseFile.find('_dists_')+1].replace('_','/') + src_dir + '/' + src_paths[i]
163 d = self.client.findHash(src_path)
164 d.addCallback(self.verifyHash, src_path, src_hashes[i])
166 idx_hash = os.popen('grep -A 3000 -E "^SHA1:" ' +
167 '/var/lib/apt/lists/' + self.releaseFile +
168 ' | grep -E " main/source/Sources.bz2$"'
169 ' | head -n 1 | cut -d\ -f 2').read().rstrip('\n')
170 idx_path = 'http://' + self.releaseFile.replace('_','/')[:-7] + 'main/source/Sources.bz2'
172 d = self.client.findHash(idx_path)
173 d.addCallback(self.verifyHash, idx_path, idx_hash)
175 d.addBoth(lastDefer.callback)
179 for p in self.pending_calls: