fix(debugger): keep Python Debug Server loopback hosts on loopback (#6487)

The port check retried every bind error for 5 s; it now retries only AddrInUse (the previous adapter still shutting down) and reports any other bind error at once.

Every loopback form of the host (127.1, LOCALHOST, 0:0:0:0:0:0:0:1, ::ffff:127.0.0.1) is normalised with the URL parser and stays on loopback: localhost and IPv6 loopback listen on 127.0.0.1, since debugpy's adapter before 1.8 listens on IPv4 only, and the connect line and waiting note say 127.0.0.1 then. Another 127.x address listens on itself. Docs explain that an imported VS Code listen.host of 0.0.0.0 becomes localhost and how to reach the IDE from a container.

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-27 20:25:27 +08:00
1 джерело 032a3b0453
коміт aa1aa91b0d
5 files changed
+55 -18

No files matched your search

+12 -3
Переглянути файл
@@ -25,10 +25,10 @@ pub(crate) async fn require_free_port(arguments: &Value) -> Result<(), IdeError>
loop {
match std::net::TcpListener::bind((host, port)) {
Ok(_) => return Ok(()),
Err(e) if tokio::time::Instant::now() >= deadline => {
return Err(IdeError::unavailable(format!("Cannot listen on {host}:{port}: {e}")));
Err(e) if e.kind() == std::io::ErrorKind::AddrInUse && tokio::time::Instant::now() < deadline => {
tokio::time::sleep(Duration::from_millis(100)).await;
}
Err(_) => tokio::time::sleep(Duration::from_millis(100)).await,
Err(e) => return Err(IdeError::unavailable(format!("Cannot listen on {host}:{port}: {e}"))),
}
}
}
@@ -84,6 +84,15 @@ mod tests {
assert!(require_free_port(&listen).await.is_ok());
}
#[tokio::test]
async fn an_address_the_machine_lacks_is_reported_at_once() {
// 192.0.2.0/24 is reserved for documentation, never a local address.
let started = std::time::Instant::now();
let e = require_free_port(&json!({"listen": {"host": "192.0.2.1", "port": 5678}})).await.unwrap_err();
assert!(e.to_string().contains("Cannot listen on 192.0.2.1:5678"), "{e}");
assert!(started.elapsed() < Duration::from_secs(1));
}
#[tokio::test]
async fn waits_for_the_previous_adapter_to_release_the_port() {
let previous = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
+1 -1
Переглянути файл
@@ -142,7 +142,7 @@ Python debugging uses debugpy. If it is missing when you start a debug session,
- Debugging `manage.py` enables Django support in debugpy.
- **Attach to Process…** (`⌥⇧F5` / `Ctrl+Alt+F5`) lists local Python processes under **Python (debugpy)**.
- The **Python Remote Debug (debugpy)** configuration attaches to a process started with `python -m debugpy --listen`, locally or on another machine, with local and remote root mapping.
- The **Python Debug Server** configuration works the other way round: the IDE listens and the program connects with `import debugpy; debugpy.connect(("localhost", 5678)); debugpy.wait_for_client()`, from a container or another machine too. Install the IDE debugger's debugpy version where the program runs; the Debug console warns when they differ.
- The **Python Debug Server** configuration works the other way round: the IDE listens and the program connects with `import debugpy; debugpy.connect(("localhost", 5678)); debugpy.wait_for_client()`, from a container or another machine too. Install the IDE debugger's debugpy version where the program runs; the Debug console warns when they differ. A VS Code `attach` with `"listen"` imports as this configuration; its `listen.host` `0.0.0.0` is where VS Code binds, so it imports as `localhost`. For a program in a container or on another machine, set the IDE host name to an address it can reach, such as `host.docker.internal`.
Options:
+1 -1
Переглянути файл
@@ -142,7 +142,7 @@ Python 调试使用 debugpy。开始调试时如果缺少 debugpy,OpenIDEA 会
- 调试 `manage.py` 时会开启 debugpy 的 Django 支持。
- **附加到进程…**(`⌥⇧F5` / `Ctrl+Alt+F5`)会在 **Python (debugpy)** 分组下列出本机的 Python 进程。
- **Python 远程调试 (debugpy)** 配置可以附加到用 `python -m debugpy --listen` 启动的进程,本机或远程机器都可以,并支持本地与远程根目录映射。
- **Python 调试服务器** 配置方向相反:由 IDE 监听,程序用 `import debugpy; debugpy.connect(("localhost", 5678)); debugpy.wait_for_client()` 连接进来,也可以从容器或其他机器连接。程序所在环境要安装与 IDE 调试器相同版本的 debugpy,版本不同时调试控制台会给出警告。
- **Python 调试服务器** 配置方向相反:由 IDE 监听,程序用 `import debugpy; debugpy.connect(("localhost", 5678)); debugpy.wait_for_client()` 连接进来,也可以从容器或其他机器连接。程序所在环境要安装与 IDE 调试器相同版本的 debugpy,版本不同时调试控制台会给出警告。VS Code 里带 `"listen"` 的 `attach` 会导入成这种配置;其中 `listen.host` 的 `0.0.0.0` 是 VS Code 的绑定地址,所以导入成 `localhost`。程序在容器或其他机器上时,要把 IDE 主机名改成程序能访问到的地址,例如 `host.docker.internal`。
相关选项:
+13 -4
Переглянути файл
@@ -167,9 +167,14 @@ describe("remote attach requests", () => {
redirectOutput: true,
justMyCode: expect.any(Boolean),
});
expect(listen({ host: "::1", port: "5679" }).listen).toEqual({ host: "::1", port: 5679 });
expect(listen({ host: "127.0.0.2" }).listen.host).toBe("127.0.0.1");
// Every loopback form stays on loopback; IPv6 loopback on 127.0.0.1, which every debugpy listens on.
expect(listen({ host: "::1", port: "5679" }).listen).toEqual({ host: "127.0.0.1", port: 5679 });
for (const host of ["[::1]", "0:0:0:0:0:0:0:1", "::ffff:127.0.0.1", "LOCALHOST"])
expect(listen({ host }).listen.host, host).toBe("127.0.0.1");
expect(listen({ host: "127.0.0.2" }).listen.host).toBe("127.0.0.2");
expect(listen({ host: "127.1" }).listen.host).toBe("127.0.0.1");
expect(listen({ host: "fd00::5" }).listen.host).toBe("::");
expect(listen({ host: "a b" }).listen.host).toBe("a b");
expect(listen({ host: "host.docker.internal", remoteRoot: "/app" })).toMatchObject({
listen: { host: "0.0.0.0", port: 5678 },
pathMappings: [{ localRoot: "/p", remoteRoot: "/app" }],
@@ -183,8 +188,12 @@ describe("remote attach requests", () => {
'import debugpy; debugpy.connect(("host.docker.internal", 5679)); debugpy.wait_for_client()',
);
expect(remote.debugpyConnectLine({ host: 'a"b' })).toContain('connect(("a\\"b", 5678))');
// Python's connect takes an IPv6 address without brackets.
expect(remote.debugpyConnectLine({ host: "[::1]" })).toContain('connect(("::1", 5678))');
// Python's connect takes an IPv6 address without brackets; IPv6 loopback connects where the IDE listens.
expect(remote.debugpyConnectLine({ host: "[fd00::5]" })).toContain('connect(("fd00::5", 5678))');
expect(remote.debugpyConnectLine({ host: "[::1]" })).toContain('connect(("127.0.0.1", 5678))');
expect(remoteWaitingNote(configOf(remote.pythonDebugServerType, { host: "::1" }), false, true)).toContain(
"connection on 127.0.0.1:5678…",
);
});
it("Python Debug Server says it waits for a connection until the program connects, and listens again", () => {
+28 -9
Переглянути файл
@@ -199,18 +199,37 @@ export const pythonRemoteType: RunConfigTypeContribution = {
/** The line the program runs to connect, in place of PyCharm's `pydevd_pycharm.settrace(...)`. */
export function debugpyConnectLine(p: Params): string {
const host = hostOf(p)
.replace(/^\[(.*)\]$/, "$1")
.replace(/\\/g, "\\\\")
.replace(/"/g, '\\"');
const host = connectHost(hostOf(p)).replace(/\\/g, "\\\\").replace(/"/g, '\\"');
return `import debugpy; debugpy.connect(("${host}", ${portOf(p, 5678)})); debugpy.wait_for_client()`;
}
/** Where the adapter listens: loopback for a local program, every interface (IPv4 or IPv6) otherwise. */
/** The host as the URL parser normalises it (`127.1`, `0:0:0:0:0:0:0:1`), IPv6 in brackets; null when not a host. */
function canonicalHost(host: string): string | null {
try {
return new URL(`http://${host.includes(":") && !host.startsWith("[") ? `[${host}]` : host}`).hostname;
} catch {
return null;
}
}
/** IPv6 loopback, plain or IPv4-mapped. */
const IPV6_LOOPBACK = /^\[(::1|::ffff:7f[0-9a-f]{2}:[0-9a-f]{1,4})\]$/;
/** Where the adapter listens: loopback for a local program, every interface (IPv4 or IPv6) otherwise.
* IPv6 loopback listens on 127.0.0.1: debugpy's adapter before 1.8 listens on IPv4 only, and leaves an
* `attach` it cannot listen for unanswered. */
function listenAddress(host: string): string {
if (/^(::1|\[::1\])$/.test(host)) return "::1";
if (/^(localhost|127(\.\d+){3})$/i.test(host)) return "127.0.0.1";
return host.includes(":") ? "::" : "0.0.0.0";
const h = canonicalHost(host);
if (h == null) return host; // Not a host: the port check reports it.
if (h === "localhost" || IPV6_LOOPBACK.test(h)) return "127.0.0.1";
if (/^127\./.test(h)) return h;
return h.startsWith("[") ? "::" : "0.0.0.0";
}
/** The host the program connects to: where the adapter listens for IPv6 loopback, as given otherwise. */
function connectHost(host: string): string {
const h = canonicalHost(host);
return h != null && IPV6_LOOPBACK.test(h) ? "127.0.0.1" : host.replace(/^\[(.*)\]$/, "$1");
}
export const pythonDebugServerType: RunConfigTypeContribution = {
@@ -503,7 +522,7 @@ export function remoteWaitingNote(
const p = rc?.params ?? {};
if (listensAgain(rc)) {
if (!connecting) return null;
const address = serverAddress(hostOf(p), portOf(p, 5678));
const address = serverAddress(connectHost(hostOf(p)), portOf(p, 5678));
const line = debugpyConnectLine(p);
return tx`Waiting for process connection on ${address}…` + "\n" + tx`Add to the program: ${line}`;
}