Tests pass without get_deprecated_singleton_config
[zeroinstall.git] / zeroinstall / injector / background.py
blob3ee4661e140df7bdb4fef7a96e5379d24cde2478
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 import handler
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_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):
95 tb = None
97 if tb:
98 import traceback
99 details = '\n' + '\n'.join(traceback.format_exception(type(exception), exception, tb))
100 else:
101 try:
102 details = unicode(exception)
103 except:
104 details = repr(exception)
105 self.notify("Zero Install", _("Error updating %(title)s: %(details)s") % {'title': self.title, 'details': details.replace('<', '&lt;')})
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)
112 return None
114 LOW = 0
115 NORMAL = 1
116 CRITICAL = 2
118 import dbus.types
120 hints = {}
121 if actions:
122 hints['urgency'] = dbus.types.Byte(NORMAL)
123 else:
124 hints['urgency'] = dbus.types.Byte(LOW)
126 return self.notification_service.Notify('Zero Install',
127 0, # replaces_id,
128 '', # icon
129 _escape_xml(title),
130 _escape_xml(message),
131 actions,
132 hints,
133 timeout * 1000)
135 def have_actions_support(self):
136 return 'actions' in self.notification_service_caps
138 def _detach():
139 """Fork a detached grandchild.
140 @return: True if we are the original."""
141 child = os.fork()
142 if child:
143 pid, status = os.waitpid(child, 0)
144 assert pid == child
145 return True
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)
153 os.dup2(null, 1)
154 os.close(null)
156 grandchild = os.fork()
157 if grandchild:
158 os._exit(0) # Parent's waitpid returns and grandchild continues
160 return False
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)
172 if verbose:
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)
178 import time
179 time.sleep(120)
180 if network_state in (_NetworkState.NM_STATE_DISCONNECTED, _NetworkState.NM_STATE_ASLEEP):
181 info(_("Still not connected to network. Giving up."))
182 sys.exit(1)
183 else:
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():
194 if verbose:
195 policy.handler.notify("Zero Install", _("No updates to download."), timeout = 1)
196 sys.exit(0)
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,
203 timeout = 1)
204 _exec_gui(policy.root, '--refresh', '--download-only', '--systray')
205 sys.exit(1)
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
242 if _detach():
243 return
245 try:
246 try:
247 _check_for_updates(policy, verbose)
248 except SystemExit:
249 raise
250 except:
251 import traceback
252 traceback.print_exc()
253 sys.stdout.flush()
254 finally:
255 os._exit(1)