From 6bff2511a0bfb3f250542044472551839cb1987a Mon Sep 17 00:00:00 2001 From: antonrh Date: Fri, 20 Nov 2026 11:09:08 +0200 Subject: [PATCH] fix: keep a live agent's address files when the hello fails Agent.ensure(true) deleted agent.addr and console.addr before starting a new agent. When they belonged to an agent another process had just started, or a busy one, the new agent exited ("an agent already runs") and the live one was left without addresses until it idle-exited. Now nothing is deleted (the agent removes stale ones under the store's lock), ensure first asks whether the address answers (a bare connect), and a start waits until it does. --- CHANGELOG.md | 7 ++ .../main/java/dev/tracepanel/core/Agent.java | 78 +++++++++++++++--- .../main/java/dev/tracepanel/core/Sender.java | 21 +---- .../java/dev/tracepanel/core/AgentTest.java | 81 +++++++++++++++++++ 4 files changed, 157 insertions(+), 30 deletions(-) create mode 100644 tracepanel-core/src/test/java/dev/tracepanel/core/AgentTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a75547..5b1d51c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## Unreleased + +### Fixed + +- An agent another app had just started, or a busy one, keeps its address + files: the SDK no longer removes them when its hello fails, so apps reach it. + ## 0.16.1 (2026-11-19) ### Added diff --git a/tracepanel-core/src/main/java/dev/tracepanel/core/Agent.java b/tracepanel-core/src/main/java/dev/tracepanel/core/Agent.java index fb11a25..85ef66a 100644 --- a/tracepanel-core/src/main/java/dev/tracepanel/core/Agent.java +++ b/tracepanel-core/src/main/java/dev/tracepanel/core/Agent.java @@ -1,7 +1,13 @@ package dev.tracepanel.core; +import java.io.Closeable; import java.io.File; import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.StandardProtocolFamily; +import java.net.UnixDomainSocketAddress; +import java.nio.channels.SocketChannel; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -15,6 +21,8 @@ */ public final class Agent { private static final long START_WAIT_MS = 1500; + // A bare connect to the address: an agent on this machine accepts at once. + private static final int PROBE_TIMEOUT_MS = 250; // An agent that exited (idle, killed, a new build) is started again at once; one that couldn't start, after this. private static final long RESTART_MS = 30_000; private static final String IDLE_EXIT_S = "1800"; @@ -64,25 +72,64 @@ private boolean autoStart() { /** * Whether an agent runs for the project: one already does, or this starts it (RESTART_MS after a failure). - * `gone`: the one at its address didn't answer, and its addresses go before a new one starts. + * `gone`: the one at its address didn't take the app's hello, so whether it answers at all is asked first. + * Its addresses stay either way: they may be another process's agent's, starting or busy this very moment, and + * an agent that didn't exit cleanly leaves its own to the next one, which removes them while it holds the store's + * lock. */ public synchronized boolean ensure(boolean gone) { if (!gone && !address().isEmpty()) return true; + if (gone && answers(address())) return true; if (!autoStart() || System.currentTimeMillis() - failedAt < RESTART_MS) return false; - if (gone) { - for (String name : List.of("agent.addr", "console.addr")) { - try { - Files.deleteIfExists(store.resolve(name)); - } catch (IOException ignored) { - // Another process's: it starts the new one. - } - } - } boolean started = start(); if (!started) failedAt = System.currentTimeMillis(); return started; } + /** + * A socket connected to the agent's address, `unix:/path` or `tcp:host:port` (a channel for the former); null for + * an address of neither kind. + */ + static Closeable connect(String address, int timeoutMs) throws IOException { + if (address.startsWith("unix:")) { + SocketChannel socket = SocketChannel.open(StandardProtocolFamily.UNIX); + try { + socket.connect(UnixDomainSocketAddress.of(Path.of(address.substring("unix:".length())))); + } catch (IOException | RuntimeException e) { + socket.close(); + throw e; + } + return socket; + } + if (address.startsWith("tcp:")) { + String hostPort = address.substring("tcp:".length()); + int at = hostPort.lastIndexOf(':'); + Socket socket = new Socket(); + try { + socket.connect( + new InetSocketAddress(hostPort.substring(0, at).replaceAll("^\\[|]$", ""), Integer.parseInt(hostPort.substring(at + 1))), + timeoutMs); + } catch (IOException | RuntimeException e) { + socket.close(); + throw e; + } + return socket; + } + return null; + } + + /** Whether an agent listens at the address: an address file alone may be a stopped agent's. */ + static boolean answers(String address) { + try { + Closeable socket = connect(address, PROBE_TIMEOUT_MS); + if (socket == null) return false; + socket.close(); + return true; + } catch (IOException | RuntimeException e) { + return false; + } + } + private boolean start() { String binary = binary(); if (binary == null) { @@ -108,8 +155,14 @@ private boolean start() { warn("the agent didn't start: " + e.getMessage()); return false; } + // Until its address answers: the file may still be a stopped agent's (a unix socket's is the same path each + // time). Another process's agent may win the race (one per store): then that one's answers. long deadline = System.currentTimeMillis() + START_WAIT_MS; - while (System.currentTimeMillis() < deadline && address().isEmpty()) { + while (!answers(address())) { + if (System.currentTimeMillis() >= deadline) { + warn("the agent didn't start (see " + store.resolve("agent.log") + ")"); + return false; + } try { Thread.sleep(20); } catch (InterruptedException e) { @@ -117,8 +170,7 @@ private boolean start() { return false; } } - if (address().isEmpty()) warn("the agent didn't start (see " + store.resolve("agent.log") + ")"); - return !address().isEmpty(); + return true; } /** diff --git a/tracepanel-core/src/main/java/dev/tracepanel/core/Sender.java b/tracepanel-core/src/main/java/dev/tracepanel/core/Sender.java index e88013f..e24a595 100644 --- a/tracepanel-core/src/main/java/dev/tracepanel/core/Sender.java +++ b/tracepanel-core/src/main/java/dev/tracepanel/core/Sender.java @@ -1,19 +1,16 @@ package dev.tracepanel.core; import java.io.ByteArrayOutputStream; +import java.io.Closeable; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.net.InetSocketAddress; import java.net.Socket; -import java.net.StandardProtocolFamily; -import java.net.UnixDomainSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.SocketChannel; import java.nio.charset.StandardCharsets; -import java.nio.file.Path; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; @@ -226,24 +223,14 @@ static List capabilities(Config config, Set sends, boolean datab /** A connection the agent accepted after the hello line, or null. */ private Connection handshake(String address) { try { - AutoCloseable channel; + Closeable channel = Agent.connect(address, CONNECT_TIMEOUT_MS); OutputStream out; InputStream in; - if (address.startsWith("unix:")) { - SocketChannel socket = SocketChannel.open(StandardProtocolFamily.UNIX); - socket.connect(UnixDomainSocketAddress.of(Path.of(address.substring("unix:".length())))); - channel = socket; + if (channel instanceof SocketChannel socket) { out = Channels.newOutputStream(socket); in = Channels.newInputStream(socket); - } else if (address.startsWith("tcp:")) { - String hostPort = address.substring("tcp:".length()); - int at = hostPort.lastIndexOf(':'); - Socket socket = new Socket(); - socket.connect( - new InetSocketAddress(hostPort.substring(0, at).replaceAll("^\\[|]$", ""), Integer.parseInt(hostPort.substring(at + 1))), - CONNECT_TIMEOUT_MS); + } else if (channel instanceof Socket socket) { socket.setSoTimeout(CONNECT_TIMEOUT_MS); - channel = socket; out = socket.getOutputStream(); in = socket.getInputStream(); } else { diff --git a/tracepanel-core/src/test/java/dev/tracepanel/core/AgentTest.java b/tracepanel-core/src/test/java/dev/tracepanel/core/AgentTest.java new file mode 100644 index 0000000..82cfea0 --- /dev/null +++ b/tracepanel-core/src/test/java/dev/tracepanel/core/AgentTest.java @@ -0,0 +1,81 @@ +package dev.tracepanel.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.InetAddress; +import java.net.ServerSocket; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.io.TempDir; + +class AgentTest { + @Test + @DisabledOnOs(OS.WINDOWS) + void an_agent_that_does_not_take_the_hello_yet_keeps_its_addresses(@TempDir Path root) throws Exception { + Path store = root.resolve(".tracepanel"); + Files.createDirectories(store); + Path started = root.resolve("started"); + Path binary = script(root, "touch '" + started + "'"); + Map env = Map.of( + "TRACEPANEL_ROOT", root.toString(), "TRACEPANEL_DIR", store.toString(), "TRACEPANEL_AGENT_BIN", binary.toString()); + // Another process's agent, starting: it listens, and answers no hello yet. + try (ServerSocket starting = new ServerSocket(0, 5, InetAddress.getLoopbackAddress())) { + String address = "tcp:127.0.0.1:" + starting.getLocalPort(); + Files.writeString(store.resolve("agent.addr"), address + "\n"); + Files.writeString(store.resolve("console.addr"), "http://127.0.0.1:1/\n"); + Agent agent = new Agent(store, env); + + assertFalse(new Sender(Config.load(env, "shop"), agent).connected()); + + assertEquals(address, agent.address()); + assertEquals("http://127.0.0.1:1/", agent.console()); + + assertFalse(Files.exists(started), "no second agent started"); + } + } + + @Test + @DisabledOnOs(OS.WINDOWS) + void an_address_nothing_listens_at_is_a_stopped_agents_and_a_new_one_starts(@TempDir Path root) throws Exception { + Path store = root.resolve(".tracepanel"); + Files.createDirectories(store); + try (ServerSocket fresh = new ServerSocket(0, 5, InetAddress.getLoopbackAddress())) { + String address = "tcp:127.0.0.1:" + fresh.getLocalPort(); + // The new agent: it writes its address a moment after it starts, in the store it is given (--dir). + Path binary = script(root, "sleep 0.2; printf '%s\\n' '" + address + "' > \"$2/agent.addr\""); + Map env = Map.of( + "TRACEPANEL_ROOT", root.toString(), "TRACEPANEL_DIR", store.toString(), "TRACEPANEL_AGENT_BIN", binary.toString()); + Files.writeString(store.resolve("agent.addr"), "unix:" + root.resolve("gone.sock") + "\n"); + Agent agent = new Agent(store, env); + + assertTrue(agent.ensure(true)); + + assertEquals(address, agent.address()); + } + } + + @Test + void whether_an_agent_answers_is_a_bare_connect(@TempDir Path root) throws Exception { + try (ServerSocket listening = new ServerSocket(0, 5, InetAddress.getLoopbackAddress())) { + assertTrue(Agent.answers("tcp:127.0.0.1:" + listening.getLocalPort())); + } + + assertFalse(Agent.answers("unix:" + root.resolve("gone.sock"))); + assertFalse(Agent.answers("")); + assertFalse(Agent.answers("tcp:nonsense")); + } + + private static Path script(Path root, String body) throws Exception { + Path binary = root.resolve("tracepanel-agent"); + Files.writeString(binary, "#!/bin/sh\n" + body + "\n"); + Files.setPosixFilePermissions(binary, PosixFilePermissions.fromString("rwx------")); + return binary; + } +}