If we need to confirm keys in a background check, use --systray
[zeroinstall/zeroinstall-rsl.git] / zeroinstall / injector / background.py
blob4a048556de83a87df5ba20fb1f3f0d2b1f8b2ad6
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 import sys, os
10 from logging import info, warn
11 from zeroinstall.support import tasks
12 from zeroinstall.injector.iface_cache import iface_cache
13 from zeroinstall.injector import handler, namespaces
15 # Copyright (C) 2009, Thomas Leonard
16 # See the README file for details, or visit http://0install.net.
18 def _escape_xml(s):
19 return s.replace('&', '&amp;').replace('<', '&lt;')
21 def _exec_gui(uri, *args):
22 os.execvp('0launch', ['0launch', '--download-only', '--gui'] + list(args) + [uri])
24 class _NetworkState:
25 NM_STATE_UNKNOWN = 0
26 NM_STATE_ASLEEP = 1
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)
35 self.title = title
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
41 try:
42 import dbus
43 import dbus.glib
44 except Exception, ex:
45 info("Failed to import D-BUS bindings: %s", ex)
46 return
48 try:
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
60 sys.stderr = None
61 try:
62 self.notification_service_caps = [str(s) for s in
63 self.notification_service.GetCapabilities()]
64 finally:
65 sys.stderr = old_stderr
66 except Exception, ex:
67 info("No D-BUS notification service available: %s", ex)
69 try:
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')
76 except Exception, ex:
77 info("No D-BUS network manager service available: %s", ex)
79 def get_network_state(self):
80 if self.network_manager:
81 try:
82 return self.network_manager.state()
83 except Exception, ex:
84 warn("Error getting network state: %s", ex)
85 return _NetworkState.NM_STATE_UNKNOWN
87 def confirm_trust_keys(self, interface, sigs, iface_xml):
88 """Run the GUI if we need to confirm any keys."""
89 info("Can't update interface; signature not yet trusted. Running GUI...")
90 _exec_gui(self.root, '--refresh', '--download-only', '--systray')
92 def report_error(self, exception, tb = None):
93 self.notify("Zero Install", "Error updating %s: %s" % (self.title, str(exception)))
95 def notify(self, title, message, timeout = 0, actions = []):
96 """Send a D-BUS notification message if possible. If there is no notification
97 service available, log the message instead."""
98 if not self.notification_service:
99 info('%s: %s', title, message)
100 return None
102 LOW = 0
103 NORMAL = 1
104 CRITICAL = 2
106 import dbus.types
108 hints = {}
109 if actions:
110 hints['urgency'] = dbus.types.Byte(NORMAL)
111 else:
112 hints['urgency'] = dbus.types.Byte(LOW)
114 return self.notification_service.Notify('Zero Install',
115 0, # replaces_id,
116 '', # icon
117 _escape_xml(title),
118 _escape_xml(message),
119 actions,
120 hints,
121 timeout * 1000)
123 def have_actions_support(self):
124 return 'actions' in self.notification_service_caps
126 def _detach():
127 """Fork a detached grandchild.
128 @return: True if we are the original."""
129 child = os.fork()
130 if child:
131 pid, status = os.waitpid(child, 0)
132 assert pid == child
133 return True
135 # The calling process might be waiting for EOF from its child.
136 # Close our stdout so we don't keep it waiting.
137 # Note: this only fixes the most common case; it could be waiting
138 # on any other FD as well. We should really use gobject.spawn_async
139 # to close *all* FDs.
140 null = os.open('/dev/null', os.O_RDWR)
141 os.dup2(null, 1)
142 os.close(null)
144 grandchild = os.fork()
145 if grandchild:
146 os._exit(0) # Parent's waitpid returns and grandchild continues
148 return False
150 def _check_for_updates(policy, verbose):
151 root_iface = iface_cache.get_interface(policy.root).get_name()
153 policy.handler = BackgroundHandler(root_iface, policy.root)
155 info("Checking for updates to '%s' in a background process", root_iface)
156 if verbose:
157 policy.handler.notify("Zero Install", "Checking for updates to '%s'..." % root_iface, timeout = 1)
159 network_state = policy.handler.get_network_state()
160 if network_state != _NetworkState.NM_STATE_CONNECTED:
161 info("Not yet connected to network (status = %d). Sleeping for a bit...", network_state)
162 import time
163 time.sleep(120)
164 if network_state in (_NetworkState.NM_STATE_DISCONNECTED, _NetworkState.NM_STATE_ASLEEP):
165 info("Still not connected to network. Giving up.")
166 sys.exit(1)
167 else:
168 info("NetworkManager says we're on-line. Good!")
170 policy.freshness = 0 # Don't bother trying to refresh when getting the interface
171 refresh = policy.refresh_all() # (causes confusing log messages)
172 policy.handler.wait_for_blocker(refresh)
174 # We could even download the archives here, but for now just
175 # update the interfaces.
177 if not policy.need_download():
178 if verbose:
179 policy.handler.notify("Zero Install", "No updates to download.", timeout = 1)
180 sys.exit(0)
182 if not policy.handler.have_actions_support():
183 # Can't ask the user to choose, so just notify them
184 # In particular, Ubuntu/Jaunty doesn't support actions
185 policy.handler.notify("Zero Install",
186 "Updates ready to download for '%s'." % root_iface,
187 timeout = 1)
188 _exec_gui(policy.root, '--refresh', '--download-only', '--systray')
189 sys.exit(1)
191 notification_closed = tasks.Blocker("wait for notification response")
193 def _NotificationClosed(nid, *unused):
194 if nid != our_question: return
195 notification_closed.trigger()
197 def _ActionInvoked(nid, action):
198 if nid != our_question: return
199 if action == 'download':
200 _exec_gui(policy.root)
201 notification_closed.trigger()
203 policy.handler.notification_service.connect_to_signal('NotificationClosed', _NotificationClosed)
204 policy.handler.notification_service.connect_to_signal('ActionInvoked', _ActionInvoked)
206 our_question = policy.handler.notify("Zero Install", "Updates ready to download for '%s'." % root_iface,
207 actions = ['download', 'Download'])
209 policy.handler.wait_for_blocker(notification_closed)
211 def spawn_background_update(policy, verbose):
212 """Spawn a detached child process to check for updates.
213 @param policy: policy containing interfaces to update
214 @type policy: L{policy.Policy}
215 @param verbose: whether to notify the user about minor events
216 @type verbose: bool"""
217 # Mark all feeds as being updated. Do this before forking, so that if someone is
218 # running lots of 0launch commands in series on the same program we don't start
219 # huge numbers of processes.
220 for x in policy.implementation:
221 iface_cache.mark_as_checking(x.uri) # Main feed
222 for f in policy.usable_feeds(x):
223 iface_cache.mark_as_checking(f.uri) # Extra feeds
225 if _detach():
226 return
228 try:
229 try:
230 _check_for_updates(policy, verbose)
231 except SystemExit:
232 raise
233 except:
234 import traceback
235 traceback.print_exc()
236 sys.stdout.flush()
237 finally:
238 os._exit(1)