Moved common caching code into new CachedDistribution class
[zeroinstall/zeroinstall-rsl.git] / zeroinstall / injector / distro.py
blobd2cc61658303ead8a58407363b55a2dcd991711d
1 """
2 Integration with native distribution package managers.
3 @since: 0.28
4 """
6 # Copyright (C) 2007, Thomas Leonard
7 # See the README file for details, or visit http://0install.net.
9 import os, re
10 from logging import warn, info
11 from zeroinstall.injector import namespaces, model
12 from zeroinstall.support import basedir
14 _dotted_ints = '[0-9]+(\.[0-9]+)*'
15 _version_regexp = '(%s)(-(pre|rc|post|)%s)*' % (_dotted_ints, _dotted_ints)
17 def try_cleanup_distro_version(version):
18 """Try to turn a distribution version string into one readable by Zero Install.
19 We do this by stripping off anything we can't parse.
20 @return: the part we understood, or None if we couldn't parse anything
21 @rtype: str"""
22 match = re.match(_version_regexp, version)
23 if match:
24 return match.group(0)
25 return None
27 class Distribution(object):
28 """Represents a distribution with which we can integrate.
29 Sub-classes should specialise this to integrate with the package managers of
30 particular distributions. This base class ignores the native package manager.
31 @since: 0.28
32 """
34 def get_package_info(self, package, factory):
35 """Get information about the given package.
36 Add zero or more implementations using the factory (typically at most two
37 will be added; the currently installed version and the latest available).
38 @param package: package name (e.g. "gimp")
39 @type package: str
40 @param factory: function for creating new DistributionImplementation objects from IDs
41 @type factory: str -> L{model.DistributionImplementation}
42 """
43 return
45 class CachedDistribution(Distribution):
46 """For distributions where querying the package database is slow (e.g. requires running
47 an external command), we cache the results.
48 """
50 def __init__(self, db_status_file):
51 """@param status_file: update the cache when the timestamp of this file changes"""
52 self._status_details = os.stat(db_status_file)
54 self.versions = {}
55 self.cache_dir = basedir.save_cache_path(namespaces.config_site,
56 namespaces.config_prog)
58 try:
59 self._load_cache()
60 except Exception, ex:
61 info("Failed to load distribution database cache (%s). Regenerating...", ex)
62 try:
63 self.generate_cache()
64 self._load_cache()
65 except Exception, ex:
66 warn("Failed to regenerate distribution database cache: %s", ex)
68 def _load_cache(self):
69 """Load {cache_leaf} cache file into self.versions if it is available and up-to-date.
70 Throws an exception if the cache should be (re)created."""
71 stream = file(os.path.join(self.cache_dir, self.cache_leaf))
73 cache_version = None
74 for line in stream:
75 if line == '\n':
76 break
77 name, value = line.split(': ')
78 if name == 'mtime' and int(value) != int(self._status_details.st_mtime):
79 raise Exception("Modification time of package database file has changed")
80 if name == 'size' and int(value) != self._status_details.st_size:
81 raise Exception("Size of package database file has changed")
82 if name == 'version':
83 cache_version = int(value)
84 else:
85 raise Exception('Invalid cache format (bad header)')
87 if cache_version is None:
88 raise Exception('Old cache format')
90 versions = self.versions
91 for line in stream:
92 package, version, zi_arch = line[:-1].split('\t')
93 versions[package] = (version, intern(zi_arch))
95 def _write_cache(self, cache):
96 #cache.sort() # Might be useful later; currently we don't care
97 import tempfile
98 fd, tmpname = tempfile.mkstemp(prefix = 'zeroinstall-cache-tmp',
99 dir = self.cache_dir)
100 try:
101 stream = os.fdopen(fd, 'wb')
102 stream.write('version: 2\n')
103 stream.write('mtime: %d\n' % int(self._status_details.st_mtime))
104 stream.write('size: %d\n' % self._status_details.st_size)
105 stream.write('\n')
106 for line in cache:
107 stream.write(line + '\n')
108 stream.close()
110 os.rename(tmpname,
111 os.path.join(self.cache_dir,
112 self.cache_leaf))
113 except:
114 os.unlink(tmpname)
115 raise
117 class DebianDistribution(CachedDistribution):
118 """A dpkg-based distribution."""
120 cache_leaf = 'dpkg-status.cache'
122 def generate_cache(self):
123 cache = []
125 for line in os.popen("dpkg-query -W --showformat='${Package}\t${Version}\t${Architecture}\n'"):
126 package, version, debarch = line.split('\t', 2)
127 if ':' in version:
128 # Debian's 'epoch' system
129 version = version.split(':', 1)[1]
130 if debarch == 'amd64\n':
131 zi_arch = 'x86_64'
132 else:
133 zi_arch = '*'
134 clean_version = try_cleanup_distro_version(version)
135 if clean_version:
136 cache.append('%s\t%s\t%s' % (package, clean_version, zi_arch))
137 else:
138 warn("Can't parse distribution version '%s' for package '%s'", version, package)
140 self._write_cache(cache)
142 def get_package_info(self, package, factory):
143 try:
144 version, machine = self.versions[package]
145 except KeyError:
146 return
148 impl = factory('package:deb:%s:%s' % (package, version))
149 impl.version = model.parse_version(version)
150 if machine != '*':
151 impl.machine = machine
153 class RPMDistribution(CachedDistribution):
154 """An RPM-based distribution."""
156 cache_leaf = 'rpm-status.cache'
158 def generate_cache(self):
159 cache = []
161 for line in os.popen("rpm -qa --qf='%{NAME}\t%{VERSION}-%{RELEASE}\t%{ARCH}\n'"):
162 package, version, rpmarch = line.split('\t', 2)
163 if package == 'gpg-pubkey':
164 continue
165 if rpmarch == 'amd64\n':
166 zi_arch = 'x86_64'
167 elif rpmarch == 'noarch\n' or rpmarch == "(none)\n":
168 zi_arch = '*'
169 else:
170 zi_arch = rpmarch.strip()
171 clean_version = try_cleanup_distro_version(version)
172 if clean_version:
173 cache.append('%s\t%s\t%s' % (package, clean_version, zi_arch))
174 else:
175 warn("Can't parse distribution version '%s' for package '%s'", version, package)
177 self._write_cache(cache)
179 def get_package_info(self, package, factory):
180 try:
181 version, machine = self.versions[package]
182 except KeyError:
183 return
185 impl = factory('package:rpm:%s:%s' % (package, version))
186 impl.version = model.parse_version(version)
187 if machine != '*':
188 impl.machine = machine
190 _host_distribution = None
191 def get_host_distribution():
192 """Get a Distribution suitable for the host operating system.
193 Calling this twice will return the same object.
194 @rtype: L{Distribution}"""
195 global _host_distribution
196 if not _host_distribution:
197 _dpkg_db_status = '/var/lib/dpkg/status'
198 _rpm_db = '/var/lib/rpm/Packages'
200 if os.access(_dpkg_db_status, os.R_OK):
201 _host_distribution = DebianDistribution(_dpkg_db_status)
202 elif os.path.isfile(_rpm_db):
203 _host_distribution = RPMDistribution(_rpm_db)
204 else:
205 _host_distribution = Distribution()
207 return _host_distribution