Add an option to not error out when only a local IP address can be found.
[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):
22         self.cache_dir = cache_dir
23         self.apt_caches = {}
24     
25     def extractPath(self, url):
26         parsed = urlparse(url)
27         host, port = splitHostPort(parsed[0], parsed[1])
28         site = host + ":" + str(port)
29         path = parsed[2]
30             
31         i = max(path.rfind('/dists/'), path.rfind('/pool/'))
32         if i >= 0:
33             baseDir = path[:i]
34             path = path[i:]
35         else:
36             # Uh oh, this is not good
37             log.msg("Couldn't find a good base directory for path: %s" % (site + path))
38             baseDir = ''
39             if site in self.apt_caches:
40                 longest_match = 0
41                 for base in self.apt_caches[site]:
42                     base_match = ''
43                     for dirs in path.split('/'):
44                         if base.startswith(base_match + '/' + dirs):
45                             base_match += '/' + dirs
46                         else:
47                             break
48                     if len(base_match) > longest_match:
49                         longest_match = len(base_match)
50                         baseDir = base_match
51             log.msg("Settled on baseDir: %s" % baseDir)
52         
53         return site, baseDir, path
54         
55     def init(self, site, baseDir):
56         if site not in self.apt_caches:
57             self.apt_caches[site] = {}
58             
59         if baseDir not in self.apt_caches[site]:
60             site_cache = self.cache_dir.child(aptpkg_dir).child('mirrors').child(site + baseDir.replace('/', '_'))
61             site_cache.makedirs
62             self.apt_caches[site][baseDir] = AptPackages(site_cache)
63     
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)
68
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)
73         d = defer.Deferred()
74         d.errback(MirrorError("Site Not Found"))
75         return d
76     
77 class TestMirrorManager(unittest.TestCase):
78     """Unit tests for the mirror manager."""
79     
80     timeout = 20
81     pending_calls = []
82     client = None
83     
84     def setUp(self):
85         self.client = MirrorManager(FilePath('/tmp/.apt-dht'))
86         
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)
92
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)
97
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)
102
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))
106
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]):
112                 self.releaseFile = f
113                 break
114         
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))
123
124         lastDefer = defer.Deferred()
125         
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'
131
132         d = self.client.findHash(idx_path)
133         d.addCallback(self.verifyHash, idx_path, idx_hash)
134
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')
144
145         d = self.client.findHash(pkg_path)
146         d.addCallback(self.verifyHash, pkg_path, pkg_hash)
147
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]
160
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])
165             
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'
171
172         d = self.client.findHash(idx_path)
173         d.addCallback(self.verifyHash, idx_path, idx_hash)
174
175         d.addBoth(lastDefer.callback)
176         return lastDefer
177
178     def tearDown(self):
179         for p in self.pending_calls:
180             if p.active():
181                 p.cancel()
182         self.client = None
183