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