Extra debugging
[zeroinstall.git] / zeroinstall / injector / packagekit.py
blob4f19444912059b5d1c38a1040e233a182b47f712
1 """
2 PackageKit integration.
3 """
5 # Copyright (C) 2010, Aleksey Lim
6 # See the README file for details, or visit http://0install.net.
8 import os, sys
9 import locale
10 import logging
11 from zeroinstall import _, SafeException
13 from zeroinstall.support import tasks, unicode
14 from zeroinstall.injector import download, model
16 _logger_pk = logging.getLogger('0install.packagekit')
18 try:
19 import dbus
20 import dbus.mainloop.glib
21 dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
22 except Exception as ex:
23 _logger_pk.info("D-BUS not available: %s", ex)
24 dbus = None
26 MAX_PACKAGE_KIT_TRANSACTION_SIZE = 100
28 class PackageKit(object):
29 def __init__(self):
30 self._pk = False
32 self._candidates = {} # { package_name : [ (version, arch, size) ] | Blocker }
34 # PackageKit is really slow at handling separate queries, so we use this to
35 # batch them up.
36 self._next_batch = set()
38 @property
39 def available(self):
40 return self.pk is not None
42 @property
43 def pk(self):
44 if self._pk is False:
45 if dbus is None:
46 self._pk = None
47 else:
48 try:
49 self._pk = dbus.Interface(dbus.SystemBus().get_object(
50 'org.freedesktop.PackageKit',
51 '/org/freedesktop/PackageKit', False),
52 'org.freedesktop.PackageKit')
53 _logger_pk.info(_('PackageKit dbus service found'))
54 except Exception as ex:
55 _logger_pk.info(_('PackageKit dbus service not found: %s'), ex)
56 self._pk = None
57 return self._pk
59 def get_candidates(self, package_name, factory, prefix):
60 """Add any cached candidates.
61 The candidates are those discovered by a previous call to L{fetch_candidates}.
62 @param package_name: the distribution's name for the package
63 @param factory: a function to add a new implementation to the feed
64 @param prefix: the prefix for the implementation's ID
65 """
66 candidates = self._candidates.get(package_name, None)
67 if candidates is None:
68 return
70 if isinstance(candidates, tasks.Blocker):
71 return # Fetch still in progress
73 for candidate in candidates:
74 impl_name = '%s:%s:%s:%s' % (prefix, package_name, candidate['version'], candidate['arch'])
76 impl = factory(impl_name, only_if_missing = True, installed = candidate['installed'])
77 if impl is None:
78 # (checking this way because the cached candidate['installed'] may be stale)
79 return # Already installed
81 impl.version = model.parse_version(candidate['version'])
82 if candidate['arch'] != '*':
83 impl.machine = candidate['arch']
85 def install(handler, packagekit_id = candidate['packagekit_id']):
86 dl = PackageKitDownload('packagekit:' + packagekit_id, hint = impl, pk = self.pk, packagekit_id = packagekit_id, expected_size = candidate['size'])
87 handler.monitor_download(dl)
88 return dl.downloaded
89 impl.download_sources.append(model.DistributionSource(package_name, candidate['size'], install))
91 @tasks.async
92 def fetch_candidates(self, package_names):
93 assert self.pk
95 # Batch requests up
96 self._next_batch |= set(package_names)
97 yield
98 package_names = self._next_batch
99 self._next_batch = set()
100 # The first fetch_candidates instance will now have all the packages
101 # For the others, package_names will now be empty
103 known = [self._candidates[p] for p in package_names if p in self._candidates]
104 # (use set because a single task may be checking multiple packages and we need
105 # to avoid duplicates).
106 in_progress = list(set([b for b in known if isinstance(b, tasks.Blocker)]))
107 _logger_pk.debug('Already downloading: %s', in_progress)
109 # Filter out the ones we've already fetched
110 package_names = [p for p in package_names if p not in self._candidates]
112 def do_batch(package_names):
113 #_logger_pk.info("sending %d packages in batch", len(package_names))
114 versions = {}
116 blocker = None
118 def error_cb(sender):
119 # Note: probably just means the package wasn't found
120 _logger_pk.info(_('Transaction failed: %s(%s)'), sender.error_code, sender.error_details)
121 blocker.trigger()
123 def details_cb(sender):
124 # The key can be a dbus.String sometimes, so convert to a Python
125 # string to be sure we get a match.
126 details = {}
127 for packagekit_id, d in sender.details.items():
128 details[unicode(packagekit_id)] = d
130 for packagekit_id in details:
131 if packagekit_id not in versions:
132 _logger_pk.warn("Unexpected package info for '%s'; was expecting one of %r", packagekit_id, list(versions.keys()))
133 _logger_pk.debug("Got: %r", details)
134 _logger_pk.debug("Expecting: %r", versions)
136 for packagekit_id, info in versions.items():
137 if packagekit_id in details:
138 info.update(details[packagekit_id])
139 info['packagekit_id'] = packagekit_id
140 if (info['name'] not in self._candidates or
141 isinstance(self._candidates[info['name']], tasks.Blocker)):
142 self._candidates[info['name']] = [info]
143 else:
144 self._candidates[info['name']].append(info)
145 else:
146 _logger_pk.info(_('Empty details for %s'), packagekit_id)
147 blocker.trigger()
149 def resolve_cb(sender):
150 if sender.package:
151 _logger_pk.debug(_('Resolved %r'), sender.package)
152 for packagekit_id, info in sender.package.items():
153 packagekit_id = unicode(packagekit_id) # Can be a dbus.String sometimes
154 parts = packagekit_id.split(';', 3)
155 if ':' in parts[3]:
156 parts[3] = parts[3].split(':', 1)[0]
157 packagekit_id = ';'.join(parts)
158 versions[packagekit_id] = info
159 tran = _PackageKitTransaction(self.pk, details_cb, error_cb)
160 tran.proxy.GetDetails(list(versions.keys()))
161 else:
162 _logger_pk.info(_('Empty resolve for %s'), package_names)
163 blocker.trigger()
165 # Send queries
166 blocker = tasks.Blocker('PackageKit %s' % package_names)
167 for package in package_names:
168 self._candidates[package] = blocker
170 try:
171 _logger_pk.debug(_('Ask for %s'), package_names)
172 tran = _PackageKitTransaction(self.pk, resolve_cb, error_cb)
173 tran.proxy.Resolve('none', package_names)
175 in_progress.append(blocker)
176 except:
177 __, ex, tb = sys.exc_info()
178 blocker.trigger((ex, tb))
179 raise
181 # Now we've collected all the requests together, split them up into chunks
182 # that PackageKit can handle ( < 100 per batch )
183 #_logger_pk.info("sending %d packages", len(package_names))
184 while package_names:
185 next_batch = package_names[:MAX_PACKAGE_KIT_TRANSACTION_SIZE]
186 package_names = package_names[MAX_PACKAGE_KIT_TRANSACTION_SIZE:]
187 do_batch(next_batch)
189 while in_progress:
190 yield in_progress
191 in_progress = [b for b in in_progress if not b.happened]
193 class PackageKitDownload:
194 def __init__(self, url, hint, pk, packagekit_id, expected_size):
195 self.url = url
196 self.status = download.download_fetching
197 self.hint = hint
198 self.aborted_by_user = False
200 self.downloaded = None
202 self.expected_size = expected_size
204 self.packagekit_id = packagekit_id
205 self._impl = hint
206 self._transaction = None
207 self.pk = pk
209 def error_cb(sender):
210 self.status = download.download_failed
211 ex = SafeException('PackageKit install failed: %s' % (sender.error_details or sender.error_code))
212 self.downloaded.trigger(exception = (ex, None))
214 def installed_cb(sender):
215 assert not self._impl.installed, impl
216 self._impl.installed = True
217 self._impl.distro.installed_fixup(self._impl)
219 self.status = download.download_complete
220 self.downloaded.trigger()
222 def install_packages():
223 package_name = self.packagekit_id
224 self._transaction = _PackageKitTransaction(self.pk, installed_cb, error_cb)
225 self._transaction.compat_call([
226 ('InstallPackages', False, [package_name]),
227 ('InstallPackages', [package_name]),
230 _auth_wrapper(install_packages)
232 self.downloaded = tasks.Blocker('PackageKit install %s' % self.packagekit_id)
234 def abort(self):
235 _logger_pk.debug(_('Cancel transaction'))
236 self.aborted_by_user = True
237 self._transaction.proxy.Cancel()
238 self.status = download.download_failed
239 self.downloaded.trigger()
241 def get_current_fraction(self):
242 if self._transaction is None:
243 return None
244 percentage = self._transaction.getPercentage()
245 if percentage > 100:
246 return None
247 else:
248 return float(percentage) / 100.
250 def get_bytes_downloaded_so_far(self):
251 fraction = self.get_current_fraction()
252 if fraction is None:
253 return 0
254 else:
255 if self.expected_size is None:
256 return 0
257 return int(self.expected_size * fraction)
259 def _auth_wrapper(method, *args):
260 try:
261 return method(*args)
262 except dbus.exceptions.DBusException as e:
263 if e.get_dbus_name() != \
264 'org.freedesktop.PackageKit.Transaction.RefusedByPolicy':
265 raise
267 iface, auth = e.get_dbus_message().split()
268 if not auth.startswith('auth_'):
269 raise
271 _logger_pk.debug(_('Authentication required for %s'), auth)
273 pk_auth = dbus.SessionBus().get_object(
274 'org.freedesktop.PolicyKit.AuthenticationAgent', '/',
275 'org.gnome.PolicyKit.AuthorizationManager.SingleInstance')
277 if not pk_auth.ObtainAuthorization(iface, dbus.UInt32(0),
278 dbus.UInt32(os.getpid()), timeout=300):
279 raise
281 return method(*args)
283 class _PackageKitTransaction(object):
284 def __init__(self, pk, finished_cb=None, error_cb=None):
285 self._finished_cb = finished_cb
286 self._error_cb = error_cb
287 self.error_code = None
288 self.error_details = None
289 self.package = {}
290 self.details = {}
291 self.files = {}
293 self.object = dbus.SystemBus().get_object(
294 'org.freedesktop.PackageKit', pk.GetTid(), False)
295 self.proxy = dbus.Interface(self.object,
296 'org.freedesktop.PackageKit.Transaction')
297 self._props = dbus.Interface(self.object, dbus.PROPERTIES_IFACE)
299 self._signals = []
300 for signal, cb in [('Finished', self.__finished_cb),
301 ('ErrorCode', self.__error_code_cb),
302 ('StatusChanged', self.__status_changed_cb),
303 ('Package', self.__package_cb),
304 ('Details', self.__details_cb),
305 ('Files', self.__files_cb)]:
306 self._signals.append(self.proxy.connect_to_signal(signal, cb))
308 defaultlocale = locale.getdefaultlocale()[0]
309 if defaultlocale is not None:
310 self.compat_call([
311 ('SetHints', ['locale=%s' % defaultlocale]),
312 ('SetLocale', defaultlocale),
315 def getPercentage(self):
316 result = self.get_prop('Percentage')
317 if result is None:
318 result, __, __, __ = self.proxy.GetProgress()
319 return result
321 def get_prop(self, prop, default = None):
322 try:
323 return self._props.Get('org.freedesktop.PackageKit.Transaction', prop)
324 except:
325 return default
327 # note: Ubuntu's aptdaemon implementation of PackageKit crashes if passed the wrong
328 # arguments (rather than returning InvalidArgs), so always try its API first.
329 def compat_call(self, calls):
330 for call in calls:
331 method = call[0]
332 args = call[1:]
333 try:
334 dbus_method = self.proxy.get_dbus_method(method)
335 return dbus_method(*args)
336 except dbus.exceptions.DBusException as e:
337 if e.get_dbus_name() not in (
338 'org.freedesktop.DBus.Error.UnknownMethod',
339 'org.freedesktop.DBus.Error.InvalidArgs'):
340 raise
341 raise Exception('Cannot call %r DBus method' % calls)
343 def __finished_cb(self, exit, runtime):
344 _logger_pk.debug(_('Transaction finished: %s'), exit)
346 for i in self._signals:
347 i.remove()
349 if self.error_code is not None:
350 self._error_cb(self)
351 else:
352 self._finished_cb(self)
354 def __error_code_cb(self, code, details):
355 _logger_pk.info(_('Transaction failed: %s(%s)'), details, code)
356 self.error_code = code
357 self.error_details = details
359 def __package_cb(self, status, id, summary):
360 try:
361 from zeroinstall.injector import distro
363 package_name, version, arch, repo_ = id.split(';')
364 clean_version = distro.try_cleanup_distro_version(version)
365 if not clean_version:
366 _logger_pk.info(_("Can't parse distribution version '%(version)s' for package '%(package)s'"), {'version': version, 'package': package_name})
367 return
368 clean_arch = distro.canonical_machine(arch)
369 package = {'version': clean_version,
370 'name': package_name,
371 'arch': clean_arch,
372 'installed': (status == 'installed')}
373 _logger_pk.debug(_('Package: %s %r'), id, package)
374 self.package[str(id)] = package
375 except Exception as ex:
376 _logger_pk.warn("__package_cb(%s, %s, %s): %s", status, id, summary, ex)
378 def __details_cb(self, id, licence, group, detail, url, size):
379 details = {'licence': str(licence),
380 'group': str(group),
381 'detail': str(detail),
382 'url': str(url),
383 'size': int(size)}
384 _logger_pk.debug(_('Details: %s %r'), id, details)
385 self.details[id] = details
387 def __files_cb(self, id, files):
388 self.files[id] = files.split(';')
390 def __status_changed_cb(self, status):
391 pass