Set machine for Gentoo native packages #2982836
[zeroinstall.git] / zeroinstall / injector / background.py
bloba18dc24d4b5ed58213d4041e7400ebc7cd960e17
1 """
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.
7 """
9 # Copyright (C) 2009, Thomas Leonard
10 # See the README file for details, or visit http://0install.net.
12 from zeroinstall import _
13 import sys, os
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
19 def _escape_xml(s):
20 return s.replace('&', '&amp;').replace('<', '&lt;')
22 def _exec_gui(uri, *args):
23 os.execvp('0launch', ['0launch', '--download-only', '--gui'] + list(args) + [uri])
25 class _NetworkState:
26 NM_STATE_UNKNOWN = 0
27 NM_STATE_ASLEEP = 1
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)
36 self.title = title
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
42 try:
43 import dbus
44 import dbus.glib
45 except Exception, ex:
46 info(_("Failed to import D-BUS bindings: %s"), ex)
47 return
49 try:
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
61 sys.stderr = None
62 try:
63 self.notification_service_caps = [str(s) for s in
64 self.notification_service.GetCapabilities()]
65 finally:
66 sys.stderr = old_stderr
67 except Exception, ex:
68 info(_("No D-BUS notification service available: %s"), ex)
70 try:
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')
77 except Exception, ex:
78 info(_("No D-BUS network manager service available: %s"), ex)
80 def get_network_state(self):
81 if self.network_manager:
82 try:
83 return self.network_manager.state()
84 except Exception, ex:
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):
96 tb = None
98 if tb:
99 import traceback
100 details = '\n' + '\n'.join(traceback.format_exception(type(exception), exception, tb))
101 else:
102 details = str(exception)
103 self.notify("Zero Install", _("Error updating %(title)s: %(details)s") % {'title': self.title, 'details': details.replace('<', '&lt;')})
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)
110 return None
112 LOW = 0
113 NORMAL = 1
114 CRITICAL = 2
116 import dbus.types
118 hints = {}
119 if actions:
120 hints['urgency'] = dbus.types.Byte(NORMAL)
121 else:
122 hints['urgency'] = dbus.types.Byte(LOW)
124 return self.notification_service.Notify('Zero Install',
125 0, # replaces_id,
126 '', # icon
127 _escape_xml(title),
128 _escape_xml(message),
129 actions,
130 hints,
131 timeout * 1000)
133 def have_actions_support(self):
134 return 'actions' in self.notification_service_caps
136 def _detach():
137 """Fork a detached grandchild.
138 @return: True if we are the original."""
139 child = os.fork()
140 if child:
141 pid, status = os.waitpid(child, 0)
142 assert pid == child
143 return True
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)
151 os.dup2(null, 1)
152 os.close(null)
154 grandchild = os.fork()
155 if grandchild:
156 os._exit(0) # Parent's waitpid returns and grandchild continues
158 return False
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)
166 if verbose:
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)
172 import time
173 time.sleep(120)
174 if network_state in (_NetworkState.NM_STATE_DISCONNECTED, _NetworkState.NM_STATE_ASLEEP):
175 info(_("Still not connected to network. Giving up."))
176 sys.exit(1)
177 else:
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():
188 if verbose:
189 policy.handler.notify("Zero Install", _("No updates to download."), timeout = 1)
190 sys.exit(0)
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,
197 timeout = 1)
198 _exec_gui(policy.root, '--refresh', '--download-only', '--systray')
199 sys.exit(1)
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
235 if _detach():
236 return
238 try:
239 try:
240 _check_for_updates(policy, verbose)
241 except SystemExit:
242 raise
243 except:
244 import traceback
245 traceback.print_exc()
246 sys.stdout.flush()
247 finally:
248 os._exit(1)