]> git.mxchange.org Git - quix0rs-apt-p2p.git/blob - AptPackages.py
Added the packages.py file (as AptPackages.py) from apt-proxy.
[quix0rs-apt-p2p.git] / AptPackages.py
1 #
2 # Copyright (C) 2002 Manuel Estrada Sainz <ranty@debian.org>
3 #
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of version 2.1 of the GNU Lesser General Public
6 # License as published by the Free Software Foundation.
7 #
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 # Lesser General Public License for more details.
12 #
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17 import apt_pkg, apt_inst, sys, os, stat
18 from os.path import dirname, basename
19 import re, shelve, shutil, fcntl
20 from twisted.internet import process
21 import apt_proxy, copy, UserDict
22 from misc import log
23
24 aptpkg_dir='.apt-proxy'
25 apt_pkg.InitSystem()
26
27 class AptDpkgInfo(UserDict.UserDict):
28     """
29     Gets control fields from a .deb file.
30
31     And then behaves like a regular python dictionary.
32
33     See AptPackages.get_mirror_path
34     """
35
36     def __init__(self, filename):
37         UserDict.UserDict.__init__(self)
38         try:
39             filehandle = open(filename);
40             try:
41                 self.control = apt_inst.debExtractControl(filehandle)
42             finally:
43                 # Make sure that file is always closed.
44                 filehandle.close()
45         except SystemError:
46             log.debug("Had problems reading: %s"%(filename), 'AptDpkgInfo')
47             raise
48         for line in self.control.split('\n'):
49             if line.find(': ') != -1:
50                 key, value = line.split(': ', 1)
51                 self.data[key] = value
52
53 class PackageFileList:
54     """
55     Manages a list of package files belonging to a backend
56     """
57     def __init__(self, backendName, cache_dir):
58         self.cache_dir = cache_dir
59         self.packagedb_dir = cache_dir+'/'+ apt_proxy.status_dir + \
60                            '/backends/' + backendName
61         if not os.path.exists(self.packagedb_dir):
62             os.makedirs(self.packagedb_dir)
63         self.packages = None
64         self.open()
65
66     def open(self):
67         if self.packages is None:
68             self.packages = shelve.open(self.packagedb_dir+'/packages.db')
69     def close(self):
70         if self.packages is not None:
71             self.packages.close()
72
73     def update_file(self, entry):
74         """
75         Called from apt_proxy.py when files get updated so we can update our
76         fake lists/ directory and sources.list.
77
78         @param entry CacheEntry for cached file
79         """
80         if entry.filename=="Packages" or entry.filename=="Release":
81             log.msg("Registering package file: "+entry.cache_path, 'apt_pkg', 4)
82             stat_result = os.stat(entry.file_path)
83             self.packages[entry.cache_path] = stat_result
84
85     def get_files(self):
86         """
87         Get list of files in database.  Each file will be checked that it exists
88         """
89         files = self.packages.keys()
90         #print self.packages.keys()
91         for f in files:
92             if not os.path.exists(self.cache_dir + os.sep + f):
93                 log.debug("File in packages database has been deleted: "+f, 'apt_pkg')
94                 del files[files.index(f)]
95                 del self.packages[f]
96         return files
97
98 class AptPackages:
99     """
100     Uses AptPackagesServer to answer queries about packages.
101
102     Makes a fake configuration for python-apt for each backend.
103     """
104     DEFAULT_APT_CONFIG = {
105         #'APT' : '',
106         'APT::Architecture' : 'i386',  # TODO: Fix this, see bug #436011 and #285360
107         #'APT::Default-Release' : 'unstable',
108    
109         'Dir':'.', # /
110         'Dir::State' : 'apt/', # var/lib/apt/
111         'Dir::State::Lists': 'lists/', # lists/
112         #'Dir::State::cdroms' : 'cdroms.list',
113         'Dir::State::userstatus' : 'status.user',
114         'Dir::State::status': 'dpkg/status', # '/var/lib/dpkg/status'
115         'Dir::Cache' : '.apt/cache/', # var/cache/apt/
116         #'Dir::Cache::archives' : 'archives/',
117         'Dir::Cache::srcpkgcache' : 'srcpkgcache.bin',
118         'Dir::Cache::pkgcache' : 'pkgcache.bin',
119         'Dir::Etc' : 'apt/etc/', # etc/apt/
120         'Dir::Etc::sourcelist' : 'sources.list',
121         'Dir::Etc::vendorlist' : 'vendors.list',
122         'Dir::Etc::vendorparts' : 'vendors.list.d',
123         #'Dir::Etc::main' : 'apt.conf',
124         #'Dir::Etc::parts' : 'apt.conf.d',
125         #'Dir::Etc::preferences' : 'preferences',
126         'Dir::Bin' : '',
127         #'Dir::Bin::methods' : '', #'/usr/lib/apt/methods'
128         'Dir::Bin::dpkg' : '/usr/bin/dpkg',
129         #'DPkg' : '',
130         #'DPkg::Pre-Install-Pkgs' : '',
131         #'DPkg::Tools' : '',
132         #'DPkg::Tools::Options' : '',
133         #'DPkg::Tools::Options::/usr/bin/apt-listchanges' : '',
134         #'DPkg::Tools::Options::/usr/bin/apt-listchanges::Version' : '2',
135         #'DPkg::Post-Invoke' : '',
136         }
137     essential_dirs = ('apt', 'apt/cache', 'apt/dpkg', 'apt/etc', 'apt/lists',
138                       'apt/lists/partial')
139     essential_files = ('apt/dpkg/status', 'apt/etc/sources.list',)
140         
141     def __init__(self, backendName, cache_dir):
142         """
143         Construct new packages manager
144         backend: Name of backend associated with this packages file
145         cache_dir: cache directory from config file
146         """
147         self.backendName = backendName
148         self.cache_dir = cache_dir
149         self.apt_config = copy.deepcopy(self.DEFAULT_APT_CONFIG)
150
151         self.status_dir = (cache_dir+'/'+ aptpkg_dir
152                            +'/backends/'+backendName)
153         for dir in self.essential_dirs:
154             path = self.status_dir+'/'+dir
155             if not os.path.exists(path):
156                 os.makedirs(path)
157         for file in self.essential_files:
158             path = self.status_dir+'/'+file
159             if not os.path.exists(path):
160                 f = open(path,'w')
161                 f.close()
162                 del f
163                 
164         self.apt_config['Dir'] = self.status_dir
165         self.apt_config['Dir::State::status'] = self.status_dir + '/apt/dpkg/status'
166         #os.system('find '+self.status_dir+' -ls ')
167         #print "status:"+self.apt_config['Dir::State::status']
168         self.packages = PackageFileList(backendName, cache_dir)
169         self.loaded = 0
170         #print "Loaded aptPackages [%s] %s " % (self.backendName, self.cache_dir)
171         
172     def __del__(self):
173         self.cleanup()
174         #print "start aptPackages [%s] %s " % (self.backendName, self.cache_dir)
175         self.packages.close()
176         #print "Deleted aptPackages [%s] %s " % (self.backendName, self.cache_dir)
177     def file_updated(self, entry):
178         """
179         A file in the backend has changed.  If this affects us, unload our apt database
180         """
181         if self.packages.update_file(entry):
182             self.unload()
183
184     def __save_stdout(self):
185         self.real_stdout_fd = os.dup(1)
186         os.close(1)
187                 
188     def __restore_stdout(self):
189         os.dup2(self.real_stdout_fd, 1)
190         os.close(self.real_stdout_fd)
191         del self.real_stdout_fd
192
193     def load(self):
194         """
195         Regenerates the fake configuration and load the packages server.
196         """
197         if self.loaded: return True
198         apt_pkg.InitSystem()
199         #print "Load:", self.status_dir
200         shutil.rmtree(self.status_dir+'/apt/lists/')
201         os.makedirs(self.status_dir+'/apt/lists/partial')
202         sources_filename = self.status_dir+'/'+'apt/etc/sources.list'
203         sources = open(sources_filename, 'w')
204         sources_count = 0
205         for file in self.packages.get_files():
206             # we should probably clear old entries from self.packages and
207             # take into account the recorded mtime as optimization
208             filepath = self.cache_dir + file
209             fake_uri='http://apt-proxy/'+file
210             source_line='deb '+dirname(fake_uri)+'/ /'
211             listpath=(self.status_dir+'/apt/lists/'
212                     +apt_pkg.URItoFileName(fake_uri))
213             sources.write(source_line+'\n')
214             log.debug("Sources line: " + source_line, 'apt_pkg')
215             sources_count = sources_count + 1
216
217             try:
218                 #we should empty the directory instead
219                 os.unlink(listpath)
220             except:
221                 pass
222             os.symlink('../../../../../'+file, listpath)
223         sources.close()
224
225         if sources_count == 0:
226             log.msg("No Packages files available for %s backend"%(self.backendName), 'apt_pkg')
227             return False
228
229         log.msg("Loading Packages database for "+self.status_dir,'apt_pkg')
230         #apt_pkg.Config = apt_pkg.newConfiguration(); #-- this causes unit tests to fail!
231         for key, value in self.apt_config.items():
232             apt_pkg.Config[key] = value
233 #         print "apt_pkg config:"
234 #         for I in apt_pkg.Config.keys():
235 #            print "%s \"%s\";"%(I,apt_pkg.Config[I]);
236
237         if log.isEnabled('apt'):
238             self.cache = apt_pkg.GetCache()
239         else:
240             # apt_pkg prints progress messages to stdout, disable
241             self.__save_stdout()
242             try:
243                 self.cache = apt_pkg.GetCache()
244             finally:
245                 self.__restore_stdout()
246
247         self.records = apt_pkg.GetPkgRecords(self.cache)
248         #for p in self.cache.Packages:
249         #    print p
250         #log.debug("%s packages found" % (len(self.cache)),'apt_pkg')
251         self.loaded = 1
252         return True
253
254     def unload(self):
255         "Tries to make the packages server quit."
256         if self.loaded:
257             del self.cache
258             del self.records
259             self.loaded = 0
260
261     def cleanup(self):
262         self.unload()
263
264     def get_mirror_path(self, name, version):
265         "Find the path for version 'version' of package 'name'"
266         if not self.load(): return None
267         try:
268             for pack_vers in self.cache[name].VersionList:
269                 if(pack_vers.VerStr == version):
270                     file, index = pack_vers.FileList[0]
271                     self.records.Lookup((file,index))
272                     path = self.records.FileName
273                     if len(path)>2 and path[0:2] == './': 
274                         path = path[2:] # Remove any leading './'
275                     return path
276
277         except KeyError:
278             pass
279         return None
280       
281
282     def get_mirror_versions(self, package_name):
283         """
284         Find the available versions of the package name given
285         @type package_name: string
286         @param package_name: package name to search for e.g. ;apt'
287         @return: A list of mirror versions available
288
289         """
290         vers = []
291         if not self.load(): return vers
292         try:
293             for pack_vers in self.cache[package_name].VersionList:
294                 vers.append(pack_vers.VerStr)
295         except KeyError:
296             pass
297         return vers
298
299
300 def cleanup(factory):
301     for backend in factory.backends.values():
302         backend.get_packages_db().cleanup()
303
304 def get_mirror_path(factory, file):
305     """
306     Look for the path of 'file' in all backends.
307     """
308     info = AptDpkgInfo(file)
309     paths = []
310     for backend in factory.backends.values():
311         path = backend.get_packages_db().get_mirror_path(info['Package'],
312                                                 info['Version'])
313         if path:
314             paths.append('/'+backend.base+'/'+path)
315     return paths
316
317 def get_mirror_versions(factory, package):
318     """
319     Look for the available version of a package in all backends, given
320     an existing package name
321     """
322     all_vers = []
323     for backend in factory.backends.values():
324         vers = backend.get_packages_db().get_mirror_versions(package)
325         for ver in vers:
326             path = backend.get_packages_db().get_mirror_path(package, ver)
327             all_vers.append((ver, "%s/%s"%(backend.base,path)))
328     return all_vers
329
330 def closest_match(info, others):
331     def compare(a, b):
332         return apt_pkg.VersionCompare(a[0], b[0])
333
334     others.sort(compare)
335     version = info['Version']
336     match = None
337     for ver,path in others:
338         if version <= ver:
339             match = path
340             break
341     if not match:
342         if not others:
343             return None
344         match = others[-1][1]
345
346     dirname=re.sub(r'/[^/]*$', '', match)
347     version=re.sub(r'^[^:]*:', '', info['Version'])
348     if dirname.find('/pool/') != -1:
349         return "/%s/%s_%s_%s.deb"%(dirname, info['Package'],
350                                   version, info['Architecture'])
351     else:
352         return "/%s/%s_%s.deb"%(dirname, info['Package'], version)
353
354 def import_directory(factory, dir, recursive=0):
355     """
356     Import all files in a given directory into the cache
357     This is used by apt-proxy-import to import new files
358     into the cache
359     """
360     imported_count  = 0
361
362     if not os.path.exists(dir):
363         log.err('Directory ' + dir + ' does not exist', 'import')
364         return
365
366     if recursive:    
367         log.msg("Importing packages from directory tree: " + dir, 'import',3)
368         for root, dirs, files in os.walk(dir):
369             for file in files:
370                 imported_count += import_file(factory, root, file)
371     else:
372         log.debug("Importing packages from directory: " + dir, 'import',3)
373         for file in os.listdir(dir):
374             mode = os.stat(dir + '/' + file)[stat.ST_MODE]
375             if not stat.S_ISDIR(mode):
376                 imported_count += import_file(factory, dir, file)
377
378     for backend in factory.backends.values():
379         backend.get_packages_db().unload()
380
381     log.msg("Imported %s files" % (imported_count))
382     return imported_count
383
384 def import_file(factory, dir, file):
385     """
386     Import a .deb or .udeb into cache from given filename
387     """
388     if file[-4:]!='.deb' and file[-5:]!='.udeb':
389         log.msg("Ignoring (unknown file type):"+ file, 'import')
390         return 0
391     
392     log.debug("considering: " + dir + '/' + file, 'import')
393     try:
394         paths = get_mirror_path(factory, dir+'/'+file)
395     except SystemError:
396         log.msg(file + ' skipped - wrong format or corrupted', 'import')
397         return 0
398     if paths:
399         if len(paths) != 1:
400             log.debug("WARNING: multiple ocurrences", 'import')
401             log.debug(str(paths), 'import')
402         cache_path = paths[0]
403     else:
404         log.debug("Not found, trying to guess", 'import')
405         info = AptDpkgInfo(dir+'/'+file)
406         cache_path = closest_match(info,
407                                 get_mirror_versions(factory, info['Package']))
408     if cache_path:
409         log.debug("MIRROR_PATH:"+ cache_path, 'import')
410         src_path = dir+'/'+file
411         dest_path = factory.config.cache_dir+cache_path
412         
413         if not os.path.exists(dest_path):
414             log.debug("IMPORTING:" + src_path, 'import')
415             dest_path = re.sub(r'/\./', '/', dest_path)
416             if not os.path.exists(dirname(dest_path)):
417                 os.makedirs(dirname(dest_path))
418             f = open(dest_path, 'w')
419             fcntl.lockf(f.fileno(), fcntl.LOCK_EX)
420             f.truncate(0)
421             shutil.copy2(src_path, dest_path)
422             f.close()
423             if hasattr(factory, 'access_times'):
424                 atime = os.stat(src_path)[stat.ST_ATIME]
425                 factory.access_times[cache_path] = atime
426             log.msg(file + ' imported', 'import')
427             return 1
428         else:
429             log.msg(file + ' skipped - already in cache', 'import')
430             return 0
431
432     else:
433         log.msg(file + ' skipped - no suitable backend found', 'import')
434         return 0
435             
436 def test(factory, file):
437     "Just for testing purposes, this should probably go to hell soon."
438     for backend in factory.backends:
439         backend.get_packages_db().load()
440
441     info = AptDpkgInfo(file)
442     path = get_mirror_path(factory, file)
443     print "Exact Match:"
444     print "\t%s:%s"%(info['Version'], path)
445
446     vers = get_mirror_versions(factory, info['Package'])
447     print "Other Versions:"
448     for ver in vers:
449         print "\t%s:%s"%(ver)
450     print "Guess:"
451     print "\t%s:%s"%(info['Version'], closest_match(info, vers))
452 if __name__ == '__main__':
453     from apt_proxy_conf import factoryConfig
454     class DummyFactory:
455         def debug(self, msg):
456             pass
457     factory = DummyFactory()
458     factoryConfig(factory)
459     test(factory,
460          '/home/ranty/work/apt-proxy/related/tools/galeon_1.2.5-1_i386.deb')
461     test(factory,
462          '/storage/apt-proxy/debian/dists/potato/main/binary-i386/base/'
463          +'libstdc++2.10_2.95.2-13.deb')
464
465     cleanup(factory)
466