8000 gh-132975: Improve Remote PDB interrupt handling by godlygeek · Pull Request #133223 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-132975: Improve Remote PDB interrupt handling #133223

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
8d89bf4
Only allow KeyboardInterrupt at specific times
godlygeek Apr 30, 2025
f65f99f
Have _PdbClient work with the socket directly
godlygeek Apr 30, 2025
ec9d3bf
Allow interrupting socket reads on Windows
godlygeek Apr 30, 2025
ed664b8
Use a SIGINT to interrupt the remote on Unix
godlygeek Apr 30, 2025
aafa48c
Handle a ValueError for operations on a closed file
godlygeek May 1, 2025
42e7cec
Use a single complex signal handler for the PDB client
godlygeek May 1, 2025
02da647
Add a news entry
godlygeek May 1, 2025
5abd63a
Update the comment to explain why we catch two exception types
godlygeek May 2, 2025
c9c5bf2
Swap signal_read/signal_write resetting to the outer finally block
godlygeek May 2, 2025
8fa88a5
Use os.kill() on every platform but Windows
godlygeek May 2, 2025
4c0b431
Use `ExitStack` to reduce nesting in `attach`
godlygeek May 2, 2025
5993e06
Use a thread to manage interrupts on Windows
godlygeek May 2, 2025
dd7c9b1
8000 Use the signal handling thread approach on all platforms
godlygeek May 4, 2025
e2391b0
Make all _connect arguments keyword-only
godlygeek May 4, 2025
edd7517
Merge remote-tracking branch 'upstream/main' into improve_remote_pdb_…
godlygeek May 4, 2025
14aa8e7
One line for contextlib imports
godlygeek May 4, 2025
b26ed5c
Add some tests for handling SIGINT in the PDB client
godlygeek May 4, 2025
a860087
Switch back to os.kill() on Unix
godlygeek May 4, 2025
e1bb1d3
Wrap input() calls in a function
godlygeek May 4, 2025
2a7807c
Merge branch 'main' into improve_remote_pdb_interrupt_handling
pablogsal May 5, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Use a thread to manage interrupts on Windows
  • Loading branch information
godlygeek committed May 2, 2025
commit 5993e06c3437cd9ae78d824cfcc22ca3cd2c5387
79 changes: 57 additions & 22 deletions Lib/pdb.py
8000
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@
import json
import token
import types
import atexit
import codeop
import pprint
import signal
Expand All @@ -93,6 +94,7 @@
import traceback
import linecache
import selectors
import threading
import _colorize

from contextlib import ExitStack
Expand Down Expand Up @@ -2906,15 +2908,15 @@ def default(self, line):


class _PdbClient:
def __init__(self, pid, server_socket, interrupt_script):
def __init__(self, pid, server_socket, interrupt_sock):
self.pid = pid
self.read_buf = b""
self.signal_read = None
self.signal_write = None
self.sigint_received = False
self.raise_on_sigint = False
self.server_socket = server_socket
self.interrupt_script = interrupt_script
self.interrupt_sock = interrupt_sock
self.pdb_instance = Pdb()
self.pdb_commands = set()
self.completion_matches = []
Expand Down Expand Up @@ -3136,14 +3138,11 @@ def send_interrupt(self):
# PyErr_CheckSignals is called or the eval loop regains control.
os.kill(self.pid, signal.SIGINT)
else:
# On Windows, inject a remote script that calls Pdb.set_trace()
# when the eval loop regains control. This cannot interrupt IO, and
# also cannot interrupt statements executed at a PDB prompt.
print(
"\n*** Program will stop at the next bytecode instruction."
" (Use 'cont' to resume)."
)
sys.remote_exec(self.pid, self.interrupt_script)
# On Windows, write to a socket that the PDB server listens on.
# This triggers the remote to raise a SIGINT for itself. We do this
# because Windows doesn't allow triggering SIGINT remotely.
# See https://stackoverflow.com/a/35792192 for many more details.
self.interrupt_sock.sendall(signal.SIGINT.to_bytes())

def process_payload(self, payload):
match payload:
Expand Down Expand Up @@ -3226,6 +3225,41 @@ def complete(self, text, state):
return None


def _start_interrupt_listener(host, port):
def sigint_listener(host, port):
with closing(
socket.create_connection((host, port), timeout=5)
) as sock:
# Check if the interpreter is finalizing every quarter of a second.
# Clean up and exit if so.
sock.settimeout(0.25)
sock.shutdown(socket.SHUT_WR)
while not shut_down.is_set():
try:
data = sock.recv(1024)
except socket.timeout:
continue
if data == b"":
return # EOF
signal.raise_signal(signal.SIGINT)

def stop_thread():
shut_down.set()
thread.join()

# Use a daemon thread so that we don't detach until after all non-daemon
# threads are done. Use an atexit handler to stop gracefully at that point,
# so that our thread is stopped before the interpreter is torn down.
shut_down = threading.Event()
thread = threading.Thread(
target=sigint_listener,
args=(host, port),
daemon=True,
)
atexit.register(stop_thread)
thread.start()


def _connect(host, port, frame, commands, version):
with closing(socket.create_connection((host, port))) as conn:
sockfile = conn.makefile("rwb")
Expand Down Expand Up @@ -3255,9 +3289,14 @@ def attach(pid, commands=()):
server = stack.enter_context(
closing(socket.create_server(("localhost", 0)))
)

port = server.getsockname()[1]

if sys.platform == "win32":
commands = [
f"__import__('pdb')._start_interrupt_listener('localhost', {port})",
*commands,
]

connect_script = stack.enter_context(
tempfile.NamedTemporaryFile("w", delete_on_close=False)
)
Expand All @@ -3281,20 +3320,16 @@ def attach(pid, commands=()):

# TODO Add a timeout? Or don't bother since the user can ^C?
client_sock, _ = server.accept()

stack.enter_context(closing(client_sock))

interrupt_script = stack.enter_context(
tempfile.NamedTemporaryFile("w", delete_on_close=False)
)
interrupt_script.write(
'import pdb, sys\n'
'if inst := pdb.Pdb._last_pdb_instance:\n'
' inst.set_trace(sys._getframe(1))\n'
)
interrupt_script.close()
if sys.platform == "win32":
interrupt_sock, _ = server.accept()
stack.enter_context(closing(interrupt_sock))
interrupt_sock.setblocking(False)
else:
interrupt_sock = None

_PdbClient(pid, client_sock, interrupt_script.name).cmdloop()
_PdbClient(pid, client_sock, interrupt_sock).cmdloop()


# Post-Mortem interface
Expand Down
2 changes: 1 addition & 1 deletion Lib/test/test_remote_pdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ def mock_input(prompt):
client = _PdbClient(
pid=0,
server_socket=server_sock,
interrupt_script="/a/b.py",
interrupt_sock=unittest.mock.Mock(spec=socket.socket),
)

if expected_exception is not None:
Expand Down
Loading
0