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
.iface_cache
import iface_cache
17 from zeroinstall
.injector
import handler
20 return s
.replace('&', '&').replace('<', '<')
22 def _exec_gui(uri
, *args
):
23 os
.execvp('0launch', ['0launch', '--download-only', '--gui'] + list(args
) + [uri
])
28 NM_STATE_CONNECTING
= 2
29 NM_STATE_CONNECTED
= 3
30 NM_STATE_DISCONNECTED
= 4
32 class BackgroundHandler(handler
.Handler
):
33 """A Handler for non-interactive background updates. Runs the GUI if interaction is required."""
34 def __init__(self
, title
, root
):
35 handler
.Handler
.__init
__(self
)
37 self
.notification_service
= None
38 self
.network_manager
= None
39 self
.notification_service_caps
= []
40 self
.root
= root
# If we need to confirm any keys, run the GUI on this
46 info(_("Failed to import D-BUS bindings: %s"), ex
)
50 session_bus
= dbus
.SessionBus()
51 remote_object
= session_bus
.get_object('org.freedesktop.Notifications',
52 '/org/freedesktop/Notifications')
54 self
.notification_service
= dbus
.Interface(remote_object
,
55 'org.freedesktop.Notifications')
57 # The Python bindings insist on printing a pointless introspection
58 # warning to stderr if the service is missing. Force it to be done
59 # now so we can skip it
60 old_stderr
= sys
.stderr
63 self
.notification_service_caps
= [str(s
) for s
in
64 self
.notification_service
.GetCapabilities()]
66 sys
.stderr
= old_stderr
68 info(_("No D-BUS notification service available: %s"), ex
)
71 system_bus
= dbus
.SystemBus()
72 remote_object
= system_bus
.get_object('org.freedesktop.NetworkManager',
73 '/org/freedesktop/NetworkManager')
75 self
.network_manager
= dbus
.Interface(remote_object
,
76 'org.freedesktop.NetworkManager')
78 info(_("No D-BUS network manager service available: %s"), ex
)
80 def get_network_state(self
):
81 if self
.network_manager
:
83 return self
.network_manager
.state()
85 warn(_("Error getting network state: %s"), ex
)
86 return _NetworkState
.NM_STATE_UNKNOWN
88 def confirm_trust_keys(self
, interface
, sigs
, iface_xml
):
89 """Run the GUI if we need to confirm any keys."""
90 info(_("Can't update interface; signature not yet trusted. Running GUI..."))
91 _exec_gui(self
.root
, '--refresh', '--download-only', '--systray')
93 def report_error(self
, exception
, tb
= None):
94 from zeroinstall
.injector
import download
95 if isinstance(exception
, download
.DownloadError
):
100 details
= '\n' + '\n'.join(traceback
.format_exception(type(exception
), exception
, tb
))
102 details
= str(exception
)
103 self
.notify("Zero Install", _("Error updating %(title)s: %(details)s") % {'title': self
.title
, 'details': details
.replace('<', '<')})
105 def notify(self
, title
, message
, timeout
= 0, actions
= []):
106 """Send a D-BUS notification message if possible. If there is no notification
107 service available, log the message instead."""
108 if not self
.notification_service
:
109 info('%s: %s', title
, message
)
120 hints
['urgency'] = dbus
.types
.Byte(NORMAL
)
122 hints
['urgency'] = dbus
.types
.Byte(LOW
)
124 return self
.notification_service
.Notify('Zero Install',
128 _escape_xml(message
),
133 def have_actions_support(self
):
134 return 'actions' in self
.notification_service_caps
137 """Fork a detached grandchild.
138 @return: True if we are the original."""
141 pid
, status
= os
.waitpid(child
, 0)
145 # The calling process might be waiting for EOF from its child.
146 # Close our stdout so we don't keep it waiting.
147 # Note: this only fixes the most common case; it could be waiting
148 # on any other FD as well. We should really use gobject.spawn_async
149 # to close *all* FDs.
150 null
= os
.open('/dev/null', os
.O_RDWR
)
154 grandchild
= os
.fork()
156 os
._exit
(0) # Parent's waitpid returns and grandchild continues
160 def _check_for_updates(policy
, verbose
):
161 root_iface
= iface_cache
.get_interface(policy
.root
).get_name()
163 policy
.handler
= BackgroundHandler(root_iface
, policy
.root
)
165 info(_("Checking for updates to '%s' in a background process"), root_iface
)
167 policy
.handler
.notify("Zero Install", _("Checking for updates to '%s'...") % root_iface
, timeout
= 1)
169 network_state
= policy
.handler
.get_network_state()
170 if network_state
!= _NetworkState
.NM_STATE_CONNECTED
:
171 info(_("Not yet connected to network (status = %d). Sleeping for a bit..."), network_state
)
174 if network_state
in (_NetworkState
.NM_STATE_DISCONNECTED
, _NetworkState
.NM_STATE_ASLEEP
):
175 info(_("Still not connected to network. Giving up."))
178 info(_("NetworkManager says we're on-line. Good!"))
180 policy
.freshness
= 0 # Don't bother trying to refresh when getting the interface
181 refresh
= policy
.refresh_all() # (causes confusing log messages)
182 policy
.handler
.wait_for_blocker(refresh
)
184 # We could even download the archives here, but for now just
185 # update the interfaces.
187 if not policy
.need_download():
189 policy
.handler
.notify("Zero Install", _("No updates to download."), timeout
= 1)
192 if not policy
.handler
.have_actions_support():
193 # Can't ask the user to choose, so just notify them
194 # In particular, Ubuntu/Jaunty doesn't support actions
195 policy
.handler
.notify("Zero Install",
196 _("Updates ready to download for '%s'.") % root_iface
,
198 _exec_gui(policy
.root
, '--refresh', '--download-only', '--systray')
201 notification_closed
= tasks
.Blocker("wait for notification response")
203 def _NotificationClosed(nid
, *unused
):
204 if nid
!= our_question
: return
205 notification_closed
.trigger()
207 def _ActionInvoked(nid
, action
):
208 if nid
!= our_question
: return
209 if action
== 'download':
210 _exec_gui(policy
.root
)
211 notification_closed
.trigger()
213 policy
.handler
.notification_service
.connect_to_signal('NotificationClosed', _NotificationClosed
)
214 policy
.handler
.notification_service
.connect_to_signal('ActionInvoked', _ActionInvoked
)
216 our_question
= policy
.handler
.notify("Zero Install", _("Updates ready to download for '%s'.") % root_iface
,
217 actions
= ['download', 'Download'])
219 policy
.handler
.wait_for_blocker(notification_closed
)
221 def spawn_background_update(policy
, verbose
):
222 """Spawn a detached child process to check for updates.
223 @param policy: policy containing interfaces to update
224 @type policy: L{policy.Policy}
225 @param verbose: whether to notify the user about minor events
226 @type verbose: bool"""
227 # Mark all feeds as being updated. Do this before forking, so that if someone is
228 # running lots of 0launch commands in series on the same program we don't start
229 # huge numbers of processes.
230 for x
in policy
.implementation
:
231 iface_cache
.mark_as_checking(x
.uri
) # Main feed
232 for f
in policy
.usable_feeds(x
):
233 iface_cache
.mark_as_checking(f
.uri
) # Extra feeds
240 _check_for_updates(policy
, verbose
)
245 traceback
.print_exc()