2 Check for updates in a background process. If we can start a program immediately, but some of our information
3 is rather old (longer that the L{config.Config.freshness} threshold) then we run it anyway, and check for updates using a new
4 process that runs quietly in the background.
6 This avoids the need to annoy people with a 'checking for updates' box when they're trying to run things.
9 # Copyright (C) 2009, Thomas Leonard
10 # See the README file for details, or visit http://0install.net.
12 from zeroinstall
import _
14 from logging
import info
, warn
15 from zeroinstall
.support
import tasks
16 from zeroinstall
.injector
import handler
19 return s
.replace('&', '&').replace('<', '<')
24 NM_STATE_DISCONNECTED
= 20
25 NM_STATE_DISCONNECTING
= 30
26 NM_STATE_CONNECTING
= 40
27 NM_STATE_CONNECTED_LOCAL
= 50
28 NM_STATE_CONNECTED_SITE
= 60
29 NM_STATE_CONNECTED_GLOBAL
= 70
31 # Maps enum values from version <= 0.8 to current (0.9) values
35 2: NM_STATE_CONNECTING
,
36 3: NM_STATE_CONNECTED_GLOBAL
,
37 4: NM_STATE_DISCONNECTED
,
40 class BackgroundHandler(handler
.Handler
):
41 """A Handler for non-interactive background updates. Runs the GUI if interaction is required."""
42 def __init__(self
, title
, root
):
43 handler
.Handler
.__init
__(self
)
45 self
.notification_service
= None
46 self
.network_manager
= None
47 self
.notification_service_caps
= []
48 self
.root
= root
# If we need to confirm any keys, run the GUI on this
54 except Exception as ex
:
55 info(_("Failed to import D-BUS bindings: %s"), ex
)
59 session_bus
= dbus
.SessionBus()
60 remote_object
= session_bus
.get_object('org.freedesktop.Notifications',
61 '/org/freedesktop/Notifications')
63 self
.notification_service
= dbus
.Interface(remote_object
,
64 'org.freedesktop.Notifications')
66 # The Python bindings insist on printing a pointless introspection
67 # warning to stderr if the service is missing. Force it to be done
68 # now so we can skip it
69 old_stderr
= sys
.stderr
72 self
.notification_service_caps
= [str(s
) for s
in
73 self
.notification_service
.GetCapabilities()]
75 sys
.stderr
= old_stderr
76 except Exception as ex
:
77 info(_("No D-BUS notification service available: %s"), ex
)
80 system_bus
= dbus
.SystemBus()
81 remote_object
= system_bus
.get_object('org.freedesktop.NetworkManager',
82 '/org/freedesktop/NetworkManager')
84 self
.network_manager
= dbus
.Interface(remote_object
,
85 'org.freedesktop.NetworkManager')
86 except Exception as ex
:
87 info(_("No D-BUS network manager service available: %s"), ex
)
89 def get_network_state(self
):
90 if self
.network_manager
:
92 state
= self
.network_manager
.state()
94 state
= _NetworkState
.v0_8
.get(state
,
95 _NetworkState
.NM_STATE_UNKNOWN
)
98 except Exception as ex
:
99 warn(_("Error getting network state: %s"), ex
)
100 return _NetworkState
.NM_STATE_UNKNOWN
102 def confirm_import_feed(self
, pending
, valid_sigs
):
103 """Run the GUI if we need to confirm any keys."""
105 if os
.environ
.get('DISPLAY', None):
106 info(_("Can't update feed; signature not yet trusted. Running GUI..."))
110 for dl
in self
.monitored_downloads
:
113 raise handler
.NoTrustedKeys("need to switch to GUI to confirm keys")
115 raise handler
.NoTrustedKeys(_("Background update for {iface} needed to confirm keys, but no GUI available!").format(
119 def report_error(self
, exception
, tb
= None):
120 from zeroinstall
.injector
import download
121 if isinstance(exception
, download
.DownloadError
):
126 details
= '\n' + '\n'.join(traceback
.format_exception(type(exception
), exception
, tb
))
129 details
= unicode(exception
)
131 details
= repr(exception
)
132 self
.notify("Zero Install", _("Error updating %(title)s: %(details)s") % {'title': self
.title
, 'details': details
.replace('<', '<')})
134 def notify(self
, title
, message
, timeout
= 0, actions
= []):
135 """Send a D-BUS notification message if possible. If there is no notification
136 service available, log the message instead."""
137 if not self
.notification_service
:
138 info('%s: %s', title
, message
)
149 hints
['urgency'] = dbus
.types
.Byte(NORMAL
)
151 hints
['urgency'] = dbus
.types
.Byte(LOW
)
153 return self
.notification_service
.Notify('Zero Install',
157 _escape_xml(message
),
163 """Fork a detached grandchild.
164 @return: True if we are the original."""
167 pid
, status
= os
.waitpid(child
, 0)
171 # The calling process might be waiting for EOF from its child.
172 # Close our stdout so we don't keep it waiting.
173 # Note: this only fixes the most common case; it could be waiting
174 # on any other FD as well. We should really use gobject.spawn_async
175 # to close *all* FDs.
176 null
= os
.open(os
.devnull
, os
.O_RDWR
)
180 grandchild
= os
.fork()
182 os
._exit
(0) # Parent's waitpid returns and grandchild continues
186 def _check_for_updates(requirements
, verbose
, app
):
188 old_sels
= app
.get_selections()
190 from zeroinstall
.injector
.driver
import Driver
191 from zeroinstall
.injector
.config
import load_config
193 background_handler
= BackgroundHandler(requirements
.interface_uri
, requirements
.interface_uri
)
194 background_config
= load_config(background_handler
)
195 root_iface
= background_config
.iface_cache
.get_interface(requirements
.interface_uri
).get_name()
196 background_handler
.title
= root_iface
198 driver
= Driver(config
= background_config
, requirements
= requirements
)
200 info(_("Checking for updates to '%s' in a background process"), root_iface
)
202 background_handler
.notify("Zero Install", _("Checking for updates to '%s'...") % root_iface
, timeout
= 1)
204 network_state
= background_handler
.get_network_state()
205 if network_state
not in (_NetworkState
.NM_STATE_CONNECTED_SITE
, _NetworkState
.NM_STATE_CONNECTED_GLOBAL
):
206 info(_("Not yet connected to network (status = %d). Sleeping for a bit..."), network_state
)
209 if network_state
in (_NetworkState
.NM_STATE_DISCONNECTED
, _NetworkState
.NM_STATE_ASLEEP
):
210 info(_("Still not connected to network. Giving up."))
213 info(_("NetworkManager says we're on-line. Good!"))
215 background_config
.freshness
= 0 # Don't bother trying to refresh when getting the interface
216 refresh
= driver
.solve_with_downloads(force
= True) # (causes confusing log messages)
217 tasks
.wait_for_blocker(refresh
)
219 if background_handler
.need_gui
or driver
.get_uncached_implementations():
220 background_handler
.notify("Zero Install",
221 _("Updates ready to download for '%s'.") % root_iface
,
224 if os
.environ
.get('DISPLAY', None):
226 from zeroinstall
import helpers
227 gui_args
= ['--refresh', '--systray', '--download'] + requirements
.get_as_options()
228 new_sels
= helpers
.get_selections_gui(requirements
.interface_uri
, gui_args
)
230 tasks
.wait_for_blocker(driver
.download_uncached_implementations())
231 new_sels
= driver
.solver
.selections
234 background_handler
.notify("Zero Install", _("No updates to download."), timeout
= 1)
235 new_sels
= driver
.solver
.selections
238 assert driver
.solver
.ready
239 from zeroinstall
.support
import xmltools
240 if not xmltools
.nodes_equal(new_sels
.toDOM(), old_sels
.toDOM()):
241 app
.set_selections(new_sels
)
242 app
.set_last_checked()
246 def spawn_background_update(driver
, verbose
):
247 """Spawn a detached child process to check for updates.
248 @param driver: driver containing interfaces to update
249 @type driver: L{driver.Driver}
250 @param verbose: whether to notify the user about minor events
252 @since: 1.5 (used to take a Policy)"""
253 iface_cache
= driver
.config
.iface_cache
254 # Mark all feeds as being updated. Do this before forking, so that if someone is
255 # running lots of 0launch commands in series on the same program we don't start
256 # huge numbers of processes.
257 for uri
in driver
.solver
.feeds_used
:
258 iface_cache
.mark_as_checking(uri
)
260 spawn_background_update2(driver
.requirements
, verbose
)
262 def spawn_background_update2(requirements
, verbose
, app
= None):
263 """Spawn a detached child process to check for updates.
264 @param requirements: requirements for the new selections
265 @type requirements: L{requirements.Requirements}
266 @param verbose: whether to notify the user about minor events
268 @param app: application to update (if any)
269 @type app: L{apps.App} | None
276 _check_for_updates(requirements
, verbose
, app
)
281 traceback
.print_exc()