Add timeouts to some unittests.
[quix0rs-apt-p2p.git] / apt_dht / MirrorManager.py
1
2 import os
3
4 from twisted.python import log
5 from twisted.internet import defer
6 from twisted.trial import unittest
7
8 from AptPackages import AptPackages
9
10 aptpkg_dir='.apt-dht'
11
12 class MirrorError(Exception):
13     """Exception raised when there's a problem with the mirror."""
14
15 class MirrorManager:
16     """Manages all requests for mirror objects."""
17     
18     def __init__(self, cache_dir):
19         self.cache_dir = cache_dir
20         self.apt_caches = {}
21     
22     def extractPath(self, path):
23         site, path = path.split('/',1)
24         if not site:
25             site, path = path.split('/',1)
26         path = '/'+path
27         
28         # Make sure a port is included for consistency
29         if site.find(':') < 0:
30             site = site + ":80"
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 = os.path.join(self.cache_dir, aptpkg_dir, 'mirrors', site + baseDir.replace('/', '_'))
62             self.apt_caches[site][baseDir] = AptPackages(site_cache)
63     
64     def updatedFile(self, path, file_path):
65         site, baseDir, path = self.extractPath(path)
66         self.init(site, baseDir)
67         self.apt_caches[site][baseDir].file_updated(path, file_path)
68     
69     def findHash(self, path):
70         site, baseDir, path = self.extractPath(path)
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('/tmp')
86         
87     def test_extractPath(self):
88         site, baseDir, path = self.client.extractPath('/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('/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     def verifyHash(self, found_hash, path, true_hash):
99         self.failUnless(found_hash[0] == true_hash, 
100                     "%s hashes don't match: %s != %s" % (path, found_hash[0], true_hash))
101
102     def test_findHash(self):
103         self.packagesFile = os.popen('ls -Sr /var/lib/apt/lists/ | grep -E "_main_.*Packages$" | tail -n 1').read().rstrip('\n')
104         self.sourcesFile = os.popen('ls -Sr /var/lib/apt/lists/ | grep -E "_main_.*Sources$" | tail -n 1').read().rstrip('\n')
105         for f in os.walk('/var/lib/apt/lists').next()[2]:
106             if f[-7:] == "Release" and self.packagesFile.startswith(f[:-7]):
107                 self.releaseFile = f
108                 break
109         
110         self.client.updatedFile('/' + self.releaseFile.replace('_','/'), 
111                                 '/var/lib/apt/lists/' + self.releaseFile)
112         self.client.updatedFile('/' + self.releaseFile[:self.releaseFile.find('_dists_')+1].replace('_','/') +
113                                 self.packagesFile[self.packagesFile.find('_dists_')+1:].replace('_','/'), 
114                                 '/var/lib/apt/lists/' + self.packagesFile)
115         self.client.updatedFile('/' + self.releaseFile[:self.releaseFile.find('_dists_')+1].replace('_','/') +
116                                 self.sourcesFile[self.sourcesFile.find('_dists_')+1:].replace('_','/'), 
117                                 '/var/lib/apt/lists/' + self.sourcesFile)
118
119         lastDefer = defer.Deferred()
120         
121         idx_hash = os.popen('grep -A 3000 -E "^SHA1:" ' + 
122                             '/var/lib/apt/lists/' + self.releaseFile + 
123                             ' | grep -E " main/binary-i386/Packages.bz2$"'
124                             ' | head -n 1 | cut -d\  -f 2').read().rstrip('\n')
125         idx_path = '/' + self.releaseFile.replace('_','/')[:-7] + 'main/binary-i386/Packages.bz2'
126
127         d = self.client.findHash(idx_path)
128         d.addCallback(self.verifyHash, idx_path, idx_hash)
129
130         pkg_hash = os.popen('grep -A 30 -E "^Package: dpkg$" ' + 
131                             '/var/lib/apt/lists/' + self.packagesFile + 
132                             ' | grep -E "^SHA1:" | head -n 1' + 
133                             ' | cut -d\  -f 2').read().rstrip('\n')
134         pkg_path = '/' + self.releaseFile[:self.releaseFile.find('_dists_')+1].replace('_','/') + \
135                    os.popen('grep -A 30 -E "^Package: dpkg$" ' + 
136                             '/var/lib/apt/lists/' + self.packagesFile + 
137                             ' | grep -E "^Filename:" | head -n 1' + 
138                             ' | cut -d\  -f 2').read().rstrip('\n')
139
140         d = self.client.findHash(pkg_path)
141         d.addCallback(self.verifyHash, pkg_path, pkg_hash)
142
143         src_dir = os.popen('grep -A 30 -E "^Package: dpkg$" ' + 
144                             '/var/lib/apt/lists/' + self.sourcesFile + 
145                             ' | grep -E "^Directory:" | head -n 1' + 
146                             ' | cut -d\  -f 2').read().rstrip('\n')
147         src_hashes = os.popen('grep -A 20 -E "^Package: dpkg$" ' + 
148                             '/var/lib/apt/lists/' + self.sourcesFile + 
149                             ' | grep -A 4 -E "^Files:" | grep -E "^ " ' + 
150                             ' | cut -d\  -f 2').read().split('\n')[:-1]
151         src_paths = os.popen('grep -A 20 -E "^Package: dpkg$" ' + 
152                             '/var/lib/apt/lists/' + self.sourcesFile + 
153                             ' | grep -A 4 -E "^Files:" | grep -E "^ " ' + 
154                             ' | cut -d\  -f 4').read().split('\n')[:-1]
155
156         for i in range(len(src_hashes)):
157             src_path = '/' + self.releaseFile[:self.releaseFile.find('_dists_')+1].replace('_','/') + src_dir + '/' + src_paths[i]
158             d = self.client.findHash(src_path)
159             d.addCallback(self.verifyHash, src_path, src_hashes[i])
160             
161         idx_hash = os.popen('grep -A 3000 -E "^SHA1:" ' + 
162                             '/var/lib/apt/lists/' + self.releaseFile + 
163                             ' | grep -E " main/source/Sources.bz2$"'
164                             ' | head -n 1 | cut -d\  -f 2').read().rstrip('\n')
165         idx_path = '/' + self.releaseFile.replace('_','/')[:-7] + 'main/source/Sources.bz2'
166
167         d = self.client.findHash(idx_path)
168         d.addCallback(self.verifyHash, idx_path, idx_hash)
169
170         d.addBoth(lastDefer.callback)
171         return lastDefer
172
173     def tearDown(self):
174         for p in self.pending_calls:
175             if p.active():
176                 p.cancel()
177         self.client = None
178