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{policy.Policy.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('<', '<')
21 def _exec_gui(uri
, *args
):
22 os
.execvp('0launch', ['0launch', '--download-only', '--gui'] + list(args
) + [uri
])
27 NM_STATE_CONNECTING
= 2
28 NM_STATE_CONNECTED
= 3
29 NM_STATE_DISCONNECTED
= 4
31 class BackgroundHandler(handler
.Handler
):
32 """A Handler for non-interactive background updates. Runs the GUI if interaction is required."""
33 def __init__(self
, title
, root
):
34 handler
.Handler
.__init
__(self
)
36 self
.notification_service
= None
37 self
.network_manager
= None
38 self
.notification_service_caps
= []
39 self
.root
= root
# If we need to confirm any keys, run the GUI on this
45 info(_("Failed to import D-BUS bindings: %s"), ex
)
49 session_bus
= dbus
.SessionBus()
50 remote_object
= session_bus
.get_object('org.freedesktop.Notifications',
51 '/org/freedesktop/Notifications')
53 self
.notification_service
= dbus
.Interface(remote_object
,
54 'org.freedesktop.Notifications')
56 # The Python bindings insist on printing a pointless introspection
57 # warning to stderr if the service is missing. Force it to be done
58 # now so we can skip it
59 old_stderr
= sys
.stderr
62 self
.notification_service_caps
= [str(s
) for s
in
63 self
.notification_service
.GetCapabilities()]
65 sys
.stderr
= old_stderr
67 info(_("No D-BUS notification service available: %s"), ex
)
70 system_bus
= dbus
.SystemBus()
71 remote_object
= system_bus
.get_object('org.freedesktop.NetworkManager',
72 '/org/freedesktop/NetworkManager')
74 self
.network_manager
= dbus
.Interface(remote_object
,
75 'org.freedesktop.NetworkManager')
77 info(_("No D-BUS network manager service available: %s"), ex
)
79 def get_network_state(self
):
80 if self
.network_manager
:
82 return self
.network_manager
.state()
84 warn(_("Error getting network state: %s"), ex
)
85 return _NetworkState
.NM_STATE_UNKNOWN
87 def confirm_import_feed(self
, pending
, valid_sigs
):
88 """Run the GUI if we need to confirm any keys."""
89 info(_("Can't update feed; signature not yet trusted. Running GUI..."))
90 _exec_gui(self
.root
, '--refresh', '--download-only', '--systray')
92 def report_error(self
, exception
, tb
= None):
93 from zeroinstall
.injector
import download
94 if isinstance(exception
, download
.DownloadError
):
99 details
= '\n' + '\n'.join(traceback
.format_exception(type(exception
), exception
, tb
))
102 details
= unicode(exception
)
104 details
= repr(exception
)
105 self
.notify("Zero Install", _("Error updating %(title)s: %(details)s") % {'title': self
.title
, 'details': details
.replace('<', '<')})
107 def notify(self
, title
, message
, timeout
= 0, actions
= []):
108 """Send a D-BUS notification message if possible. If there is no notification
109 service available, log the message instead."""
110 if not self
.notification_service
:
111 info('%s: %s', title
, message
)
122 hints
['urgency'] = dbus
.types
.Byte(NORMAL
)
124 hints
['urgency'] = dbus
.types
.Byte(LOW
)
126 return self
.notification_service
.Notify('Zero Install',
130 _escape_xml(message
),
135 def have_actions_support(self
):
136 return 'actions' in self
.notification_service_caps
139 """Fork a detached grandchild.
140 @return: True if we are the original."""
143 pid
, status
= os
.waitpid(child
, 0)
147 # The calling process might be waiting for EOF from its child.
148 # Close our stdout so we don't keep it waiting.
149 # Note: this only fixes the most common case; it could be waiting
150 # on any other FD as well. We should really use gobject.spawn_async
151 # to close *all* FDs.
152 null
= os
.open('/dev/null', os
.O_RDWR
)
156 grandchild
= os
.fork()
158 os
._exit
(0) # Parent's waitpid returns and grandchild continues
162 def _check_for_updates(old_policy
, verbose
):
163 from zeroinstall
.injector
.policy
import load_config
, Policy
165 iface_cache
= old_policy
.config
.iface_cache
166 root_iface
= iface_cache
.get_interface(old_policy
.root
).get_name()
168 background_config
= load_config(BackgroundHandler(root_iface
, old_policy
.root
))
169 policy
= Policy(config
= background_config
, requirements
= old_policy
.requirements
)
171 info(_("Checking for updates to '%s' in a background process"), root_iface
)
173 policy
.handler
.notify("Zero Install", _("Checking for updates to '%s'...") % root_iface
, timeout
= 1)
175 network_state
= policy
.handler
.get_network_state()
176 if network_state
!= _NetworkState
.NM_STATE_CONNECTED
:
177 info(_("Not yet connected to network (status = %d). Sleeping for a bit..."), network_state
)
180 if network_state
in (_NetworkState
.NM_STATE_DISCONNECTED
, _NetworkState
.NM_STATE_ASLEEP
):
181 info(_("Still not connected to network. Giving up."))
184 info(_("NetworkManager says we're on-line. Good!"))
186 policy
.freshness
= 0 # Don't bother trying to refresh when getting the interface
187 refresh
= policy
.refresh_all() # (causes confusing log messages)
188 policy
.handler
.wait_for_blocker(refresh
)
190 # We could even download the archives here, but for now just
191 # update the interfaces.
193 if not policy
.need_download():
195 policy
.handler
.notify("Zero Install", _("No updates to download."), timeout
= 1)
198 if not policy
.handler
.have_actions_support():
199 # Can't ask the user to choose, so just notify them
200 # In particular, Ubuntu/Jaunty doesn't support actions
201 policy
.handler
.notify("Zero Install",
202 _("Updates ready to download for '%s'.") % root_iface
,
204 _exec_gui(policy
.root
, '--refresh', '--download-only', '--systray')
207 notification_closed
= tasks
.Blocker("wait for notification response")
209 def _NotificationClosed(nid
, *unused
):
210 if nid
!= our_question
: return
211 notification_closed
.trigger()
213 def _ActionInvoked(nid
, action
):
214 if nid
!= our_question
: return
215 if action
== 'download':
216 _exec_gui(policy
.root
)
217 notification_closed
.trigger()
219 policy
.handler
.notification_service
.connect_to_signal('NotificationClosed', _NotificationClosed
)
220 policy
.handler
.notification_service
.connect_to_signal('ActionInvoked', _ActionInvoked
)
222 our_question
= policy
.handler
.notify("Zero Install", _("Updates ready to download for '%s'.") % root_iface
,
223 actions
= ['download', 'Download'])
225 policy
.handler
.wait_for_blocker(notification_closed
)
227 def spawn_background_update(policy
, verbose
):
228 """Spawn a detached child process to check for updates.
229 @param policy: policy containing interfaces to update
230 @type policy: L{policy.Policy}
231 @param verbose: whether to notify the user about minor events
232 @type verbose: bool"""
233 iface_cache
= policy
.config
.iface_cache
234 # Mark all feeds as being updated. Do this before forking, so that if someone is
235 # running lots of 0launch commands in series on the same program we don't start
236 # huge numbers of processes.
237 for uri
in policy
.solver
.selections
.selections
:
238 iface_cache
.mark_as_checking(uri
) # Main feed
239 for f
in policy
.usable_feeds(iface_cache
.get_interface(uri
)):
240 iface_cache
.mark_as_checking(f
.uri
) # Extra feeds
247 _check_for_updates(policy
, verbose
)
252 traceback
.print_exc()