Report errors before starting new task
[zeroinstall.git] / zeroinstall / injector / handler.py
blobf1197a0ac4846057625e0f6698363a2651a04fd4
1 """
2 Integrates download callbacks with an external mainloop.
3 While things are being downloaded, Zero Install returns control to your program.
4 Your mainloop is responsible for monitoring the state of the downloads and notifying
5 Zero Install when they are complete.
7 To do this, you supply a L{Handler} to the L{policy}.
8 """
10 # Copyright (C) 2009, Thomas Leonard
11 # See the README file for details, or visit http://0install.net.
13 from zeroinstall import _
14 import sys
15 from logging import debug, warn
17 from zeroinstall import NeedDownload, SafeException
18 from zeroinstall.support import tasks
19 from zeroinstall.injector import download
21 class NoTrustedKeys(SafeException):
22 """Thrown by L{Handler.confirm_trust_keys} on failure."""
23 pass
25 class Handler(object):
26 """
27 This implementation uses the GLib mainloop. Note that QT4 can use the GLib mainloop too.
29 @ivar monitored_downloads: dict of downloads in progress
30 @type monitored_downloads: {URL: L{download.Download}}
31 @ivar n_completed_downloads: number of downloads which have finished for GUIs, etc (can be reset as desired).
32 @type n_completed_downloads: int
33 @ivar total_bytes_downloaded: informational counter for GUIs, etc (can be reset as desired). Updated when download finishes.
34 @type total_bytes_downloaded: int
35 """
37 __slots__ = ['monitored_downloads', '_loop', 'dry_run', 'total_bytes_downloaded', 'n_completed_downloads', '_current_confirm']
39 def __init__(self, mainloop = None, dry_run = False):
40 self.monitored_downloads = {}
41 self._loop = None
42 self.dry_run = dry_run
43 self.n_completed_downloads = 0
44 self.total_bytes_downloaded = 0
45 self._current_confirm = None
47 def monitor_download(self, dl):
48 """Called when a new L{download} is started.
49 This is mainly used by the GUI to display the progress bar."""
50 dl.start()
51 self.monitored_downloads[dl.url] = dl
52 self.downloads_changed()
54 @tasks.async
55 def download_done_stats():
56 yield dl.downloaded
57 # NB: we don't check for exceptions here; someone else should be doing that
58 try:
59 self.n_completed_downloads += 1
60 self.total_bytes_downloaded += dl.get_bytes_downloaded_so_far()
61 del self.monitored_downloads[dl.url]
62 self.downloads_changed()
63 except Exception, ex:
64 self.report_error(ex)
65 download_done_stats()
67 def impl_added_to_store(self, impl):
68 """Called by the L{fetch.Fetcher} when adding an implementation.
69 The GUI uses this to update its display.
70 @param impl: the implementation which has been added
71 @type impl: L{model.Implementation}
72 """
73 pass
75 def downloads_changed(self):
76 """This is just for the GUI to override to update its display."""
77 pass
79 def wait_for_blocker(self, blocker):
80 """Run a recursive mainloop until blocker is triggered.
81 @param blocker: event to wait on
82 @type blocker: L{tasks.Blocker}"""
83 if not blocker.happened:
84 import gobject
86 def quitter():
87 yield blocker
88 self._loop.quit()
89 quit = tasks.Task(quitter(), "quitter")
91 assert self._loop is None # Avoid recursion
92 self._loop = gobject.MainLoop(gobject.main_context_default())
93 try:
94 debug(_("Entering mainloop, waiting for %s"), blocker)
95 self._loop.run()
96 finally:
97 self._loop = None
99 assert blocker.happened, "Someone quit the main loop!"
101 tasks.check(blocker)
103 def get_download(self, url, force = False, hint = None):
104 """Return the Download object currently downloading 'url'.
105 If no download for this URL has been started, start one now (and
106 start monitoring it).
107 If the download failed and force is False, return it anyway.
108 If force is True, abort any current or failed download and start
109 a new one.
110 @rtype: L{download.Download}
112 if self.dry_run:
113 raise NeedDownload(url)
115 try:
116 dl = self.monitored_downloads[url]
117 if dl and force:
118 dl.abort()
119 raise KeyError
120 except KeyError:
121 dl = download.Download(url, hint)
122 self.monitor_download(dl)
123 return dl
125 def confirm_keys(self, pending, fetch_key_info):
126 """We don't trust any of the signatures yet. Ask the user.
127 When done update the L{trust} database, and then call L{trust.TrustDB.notify}.
128 This method just calls L{confirm_import_feed} if the handler (self) is
129 new-style, or L{confirm_trust_keys} for older classes. A class
130 is considered old-style if it overrides confirm_trust_keys and
131 not confirm_import_feed.
132 @since: 0.42
133 @arg pending: an object holding details of the updated feed
134 @type pending: L{PendingFeed}
135 @arg fetch_key_info: a function which can be used to fetch information about a key fingerprint
136 @type fetch_key_info: str -> L{Blocker}
137 @return: A blocker that triggers when the user has chosen, or None if already done.
138 @rtype: None | L{Blocker}"""
140 assert pending.sigs
142 if hasattr(self.confirm_trust_keys, 'original') or not hasattr(self.confirm_import_feed, 'original'):
143 # new-style class
144 from zeroinstall.injector import gpg
145 valid_sigs = [s for s in pending.sigs if isinstance(s, gpg.ValidSig)]
146 if not valid_sigs:
147 raise SafeException('No valid signatures found on "%s". Signatures:%s' %
148 (pending.url, ''.join(['\n- ' + str(s) for s in pending.sigs])))
150 # Start downloading information about the keys...
151 kfs = {}
152 for sig in valid_sigs:
153 kfs[sig] = fetch_key_info(sig.fingerprint)
155 return self._queue_confirm_import_feed(pending, kfs)
156 else:
157 # old-style class
158 from zeroinstall.injector import iface_cache
159 import warnings
160 warnings.warn(_("Should override confirm_import_feed(); using old confirm_trust_keys() for now"), DeprecationWarning, stacklevel = 2)
162 iface = iface_cache.iface_cache.get_interface(pending.url)
163 return self.confirm_trust_keys(iface, pending.sigs, pending.new_xml)
165 @tasks.async
166 def _queue_confirm_import_feed(self, pending, valid_sigs):
167 # If we're already confirming something else, wait for that to finish...
168 while self._current_confirm is not None:
169 yield self._current_confirm
171 self._current_confirm = lock = tasks.Blocker('confirm key lock')
172 try:
173 done = self.confirm_import_feed(pending, valid_sigs)
174 yield done
175 tasks.check(done)
176 finally:
177 self._current_confirm = None
178 lock.trigger()
180 @tasks.async
181 def confirm_import_feed(self, pending, valid_sigs):
182 """Sub-classes should override this method to interact with the user about new feeds.
183 If multiple feeds need confirmation, L{confirm_keys} will only invoke one instance of this
184 method at a time.
185 @param pending: the new feed to be imported
186 @type pending: L{PendingFeed}
187 @param valid_sigs: maps signatures to a list of fetchers collecting information about the key
188 @type valid_sigs: {L{gpg.ValidSig} : L{fetch.KeyInfoFetcher}}
189 @since: 0.42
190 @see: L{confirm_keys}"""
191 from zeroinstall.injector import trust
193 assert valid_sigs
195 domain = trust.domain_from_url(pending.url)
197 # Ask on stderr, because we may be writing XML to stdout
198 print >>sys.stderr, "\nFeed:", pending.url
199 print >>sys.stderr, "The feed is correctly signed with the following keys:"
200 for x in valid_sigs:
201 print >>sys.stderr, "-", x
203 def text(parent):
204 text = ""
205 for node in parent.childNodes:
206 if node.nodeType == node.TEXT_NODE:
207 text = text + node.data
208 return text
210 shown = set()
211 key_info_fetchers = valid_sigs.values()
212 while key_info_fetchers:
213 old_kfs = key_info_fetchers
214 key_info_fetchers = []
215 for kf in old_kfs:
216 infos = set(kf.info) - shown
217 if infos:
218 if len(valid_sigs) > 1:
219 print "%s: " % kf.fingerprint
220 for info in infos:
221 print >>sys.stderr, "-", text(info)
222 shown.add(info)
223 if kf.blocker:
224 key_info_fetchers.append(kf)
225 if key_info_fetchers:
226 for kf in key_info_fetchers: print >>sys.stderr, kf.status
227 blockers = [kf.blocker for kf in key_info_fetchers]
228 yield blockers
229 for b in blockers:
230 try:
231 tasks.check(b)
232 except Exception, ex:
233 warn("Failed to get key info: %s", ex)
235 if len(valid_sigs) == 1:
236 print >>sys.stderr, "Do you want to trust this key to sign feeds from '%s'?" % domain
237 else:
238 print >>sys.stderr, "Do you want to trust all of these keys to sign feeds from '%s'?" % domain
239 while True:
240 print >>sys.stderr, "Trust [Y/N] ",
241 i = raw_input()
242 if not i: continue
243 if i in 'Nn':
244 raise NoTrustedKeys(_('Not signed with a trusted key'))
245 if i in 'Yy':
246 break
247 for key in valid_sigs:
248 print >>sys.stderr, "Trusting", key.fingerprint, "for", domain
249 trust.trust_db.trust_key(key.fingerprint, domain)
251 confirm_import_feed.original = True
253 def confirm_trust_keys(self, interface, sigs, iface_xml):
254 """We don't trust any of the signatures yet. Ask the user.
255 When done update the L{trust} database, and then call L{trust.TrustDB.notify}.
256 @deprecated: see L{confirm_keys}
257 @arg interface: the interface being updated
258 @arg sigs: a list of signatures (from L{gpg.check_stream})
259 @arg iface_xml: the downloaded data (not yet trusted)
260 @return: a blocker, if confirmation will happen asynchronously, or None
261 @rtype: L{tasks.Blocker}"""
262 import warnings
263 warnings.warn(_("Use confirm_keys, not confirm_trust_keys"), DeprecationWarning, stacklevel = 2)
264 from zeroinstall.injector import trust, gpg
265 assert sigs
266 valid_sigs = [s for s in sigs if isinstance(s, gpg.ValidSig)]
267 if not valid_sigs:
268 raise SafeException('No valid signatures found on "%s". Signatures:%s' %
269 (interface.uri, ''.join(['\n- ' + str(s) for s in sigs])))
271 domain = trust.domain_from_url(interface.uri)
273 # Ask on stderr, because we may be writing XML to stdout
274 print >>sys.stderr, "\nInterface:", interface.uri
275 print >>sys.stderr, "The interface is correctly signed with the following keys:"
276 for x in valid_sigs:
277 print >>sys.stderr, "-", x
279 if len(valid_sigs) == 1:
280 print >>sys.stderr, "Do you want to trust this key to sign feeds from '%s'?" % domain
281 else:
282 print >>sys.stderr, "Do you want to trust all of these keys to sign feeds from '%s'?" % domain
283 while True:
284 print >>sys.stderr, "Trust [Y/N] ",
285 i = raw_input()
286 if not i: continue
287 if i in 'Nn':
288 raise NoTrustedKeys(_('Not signed with a trusted key'))
289 if i in 'Yy':
290 break
291 for key in valid_sigs:
292 print >>sys.stderr, "Trusting", key.fingerprint, "for", domain
293 trust.trust_db.trust_key(key.fingerprint, domain)
295 trust.trust_db.notify()
297 confirm_trust_keys.original = True # Detect if someone overrides it
299 def report_error(self, exception, tb = None):
300 """Report an exception to the user.
301 @param exception: the exception to report
302 @type exception: L{SafeException}
303 @param tb: optional traceback
304 @since: 0.25"""
305 warn("%s", str(exception) or type(exception))
306 #import traceback
307 #traceback.print_exception(exception, None, tb)