Debian Codegraph @

gi/_ossighelper.py

raw
1 # Copyright 2017 Christoph Reiter
2 #
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License, or (at your option) any later version.
7 #
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 # Lesser General Public License for more details.
12 #
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, see <http://www.gnu.org/licenses/>.
15
16
17 import os
18 import socket
19 import signal
20 import asyncio
21 import threading
22 from contextlib import closing, contextmanager
23
24 from . import _gi
25
26
27 def ensure_socket_not_inheritable(sock):
28 """Ensures that the socket is not inherited by child processes.
29
30 Raises:
31 EnvironmentError
32 NotImplementedError: With Python <3.4 on Windows
33
34 """
35 if hasattr(sock, "set_inheritable"):
36 sock.set_inheritable(False)
37 else:
38 try:
39 import fcntl
40 except ImportError:
41 raise NotImplementedError("Not implemented for older Python on Windows")
42 else:
43 fd = sock.fileno()
44 flags = fcntl.fcntl(fd, fcntl.F_GETFD)
45 fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
46
47
48 _wakeup_fd_is_active = False
49 """Since we can't check if set_wakeup_fd() is already used for nested event
50 loops without introducing a race condition we keep track of it globally.
51 """
52
53
54 @contextmanager
55 def wakeup_on_signal():
56 """A decorator for functions which create a glib event loop to keep
57 Python signal handlers working while the event loop is idling.
58
59 In case an OS signal is received will wake the default event loop up
60 shortly so that any registered Python signal handlers registered through
61 signal.signal() can run.
62
63 In case the wrapped function is not called from the main thread it will be
64 called as is and it will not wake up the default loop for signals.
65 """
66 global _wakeup_fd_is_active
67
68 if _wakeup_fd_is_active:
69 yield
70 return
71
72 from gi.repository import GLib
73
74 read_socket, write_socket = socket.socketpair()
75 with closing(read_socket), closing(write_socket):
76 for sock in [read_socket, write_socket]:
77 sock.setblocking(False)
78 ensure_socket_not_inheritable(sock)
79
80 try:
81 orig_fd = signal.set_wakeup_fd(write_socket.fileno())
82 except ValueError:
83 # Raised in case this is not the main thread -> give up.
84 yield
85 return
86 else:
87 _wakeup_fd_is_active = True
88
89 def signal_notify(source, condition):
90 if condition & GLib.IO_IN:
91 try:
92 return bool(read_socket.recv(1))
93 except OSError:
94 return False
95 return True
96 return False
97
98 try:
99 if os.name == "nt":
100 channel = GLib.IOChannel.win32_new_socket(read_socket.fileno())
101 else:
102 channel = GLib.IOChannel.unix_new(read_socket.fileno())
103
104 source_id = GLib.io_add_watch(
105 channel,
106 GLib.PRIORITY_DEFAULT,
107 (
108 GLib.IOCondition.IN
109 | GLib.IOCondition.HUP
110 | GLib.IOCondition.NVAL
111 | GLib.IOCondition.ERR
112 ),
113 signal_notify,
114 )
115 try:
116 yield
117 finally:
118 GLib.source_remove(source_id)
119 finally:
120 write_fd = signal.set_wakeup_fd(orig_fd)
121 if write_fd != write_socket.fileno():
122 # Someone has called set_wakeup_fd while func() was active,
123 # so let's re-revert again.
124 signal.set_wakeup_fd(write_fd)
125 _wakeup_fd_is_active = False
126
127
128 PyOS_getsig = _gi.pyos_getsig
129 PyOS_setsig = _gi.pyos_setsig
130
131 # We save the signal pointer so we can detect if glib has changed the
132 # signal handler behind Python's back (GLib.unix_signal_add)
133 if signal.getsignal(signal.SIGINT) is signal.default_int_handler:
134 startup_sigint_ptr = PyOS_getsig(signal.SIGINT)
135 else:
136 # Something has set the handler before import, we can't get a ptr
137 # for the default handler so make sure the pointer will never match.
138 startup_sigint_ptr = -1
139
140
141 def sigint_handler_is_default():
142 """Returns if on SIGINT the default Python handler would be called."""
143 return (
144 signal.getsignal(signal.SIGINT) is signal.default_int_handler
145 and PyOS_getsig(signal.SIGINT) == startup_sigint_ptr
146 )
147
148
149 @contextmanager
150 def sigint_handler_set_and_restore_default(handler):
151 """Context manager for saving/restoring the SIGINT handler default state.
152
153 Will only restore the default handler again if the handler is not changed
154 while the context is active.
155 """
156 assert sigint_handler_is_default()
157
158 signal.signal(signal.SIGINT, handler)
159 sig_ptr = PyOS_getsig(signal.SIGINT)
160 try:
161 yield
162 finally:
163 if (
164 signal.getsignal(signal.SIGINT) is handler
165 and PyOS_getsig(signal.SIGINT) == sig_ptr
166 ):
167 signal.signal(signal.SIGINT, signal.default_int_handler)
168
169
170 def is_main_thread():
171 """Returns True in case the function is called from the main thread."""
172 return threading.current_thread().name == "MainThread"
173
174
175 _callback_stack = []
176 _sigint_called = False
177
178
179 @contextmanager
180 def register_sigint_fallback(callback):
181 """Installs a SIGINT signal handler in case the default Python one is
182 active which calls 'callback' in case the signal occurs.
183
184 Only does something if called from the main thread.
185
186 In case of nested context managers the signal handler will be only
187 installed once and the callbacks will be called in the reverse order
188 of their registration.
189
190 The old signal handler will be restored in case no signal handler is
191 registered while the context is active.
192 """
193 # To handle multiple levels of event loops we need to call the last
194 # callback first, wait until the inner most event loop returns control
195 # and only then call the next callback, and so on... until we
196 # reach the outer most which manages the signal handler and raises
197 # in the end
198
199 global _callback_stack, _sigint_called
200
201 if not is_main_thread():
202 yield
203 return
204
205 if not sigint_handler_is_default():
206 if _callback_stack:
207 # This is an inner event loop, append our callback
208 # to the stack so the parent context can call it.
209 _callback_stack.append(callback)
210 try:
211 yield
212 finally:
213 cb = _callback_stack.pop()
214 if _sigint_called:
215 cb()
216 else:
217 # There is a signal handler set by the user, just do nothing
218 yield
219 return
220
221 _sigint_called = False
222
223 def sigint_handler(sig_num, frame):
224 global _callback_stack, _sigint_called
225
226 if _sigint_called:
227 return
228 _sigint_called = True
229 _callback_stack.pop()()
230
231 _callback_stack.append(callback)
232 try:
233 with sigint_handler_set_and_restore_default(sigint_handler):
234 yield
235 finally:
236 if _sigint_called:
237 signal.default_int_handler(signal.SIGINT, None)
238 else:
239 _callback_stack.pop()
240
241
242 class DummyEventLoop:
243 @classmethod
244 @contextmanager
245 def paused(cls):
246 yield
247
248 @classmethod
249 @contextmanager
250 def running(cls, quit_func):
251 with wakeup_on_signal():
252 yield
253
254
255 def get_event_loop(ctx):
256 """Return the correct GLibEventLoop or a dummy that just registers the
257 signal wakeup mechanism.
258 """
259 from . import events
260
261 # Try to use the running loop. If there is none, get the policy and
262 # try getting one in the hope that this will give us an event loop for the
263 # correct context.
264 loop = asyncio._get_running_loop()
265 if loop is None:
266 # NOTE: We intentionally ignore the event loop policy.
267 # It is removed in python 3.16 and we cannot properly check if one was
268 # set by the user. Also, it is fair to assume that if one is set, then
269 # it will be ours.
270 loop = events.GLibEventLoopPolicy._get_event_loop()
271
272 if (
273 isinstance(loop, events.GLibEventLoop)
274 and ctx is not None
275 and hash(loop._context) == hash(ctx)
276 ):
277 return loop
278
279 return DummyEventLoop