diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b1d51c..0077b04 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ - 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. +- The console under `/__tracepanel__/` no longer answers a bare 502: a 503 + says why there is no console and what to do, as a page that reloads itself. ## 0.16.1 (2026-11-19) 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 85ef66a..13bafef 100644 --- a/tracepanel-core/src/main/java/dev/tracepanel/core/Agent.java +++ b/tracepanel-core/src/main/java/dev/tracepanel/core/Agent.java @@ -31,6 +31,8 @@ public final class Agent { private final Map env; private final AgentDownload download; private long failedAt = Long.MIN_VALUE / 2; + /** The last start found no binary: what the console's page says then. */ + private volatile boolean noBinary; public Agent(Path store, Map env) { this.store = store; @@ -86,6 +88,45 @@ public synchronized boolean ensure(boolean gone) { return started; } + /** + * What keeps the project's console from answering, as far as this process can tell: what the console's 503 says + * (Console), in the words the other SDKs use. + */ + public Console.NoConsole noConsole() { + String configured = env.get("TRACEPANEL_CONSOLE_URL"); + if (configured != null && !configured.isBlank()) { + return new Console.NoConsole("The console doesn't answer", "No console answers at " + configured + + " (TRACEPANEL_CONSOLE_URL). Start the agent there with --serve, or correct the address."); + } + String named = env.get("TRACEPANEL_AGENT"); + if ("off".equals(named)) { + return new Console.NoConsole("Tracepanel's agent is off", "Tracepanel's agent is off (TRACEPANEL_AGENT=off): traces" + + " aren't kept and there is no console. Unset TRACEPANEL_AGENT to have the app start it."); + } + if (!autoStart()) { + return new Console.NoConsole("No console for the named agent", "The agent named in TRACEPANEL_AGENT (" + named + + ") serves no console here. Start it with --serve, and set TRACEPANEL_CONSOLE_URL to its console's address."); + } + if (answers(address())) { + // The agent writes its console's address before its own: one that answers without a console was started so. + return new Console.NoConsole("Tracepanel's agent runs without its console", "The project's agent runs without its" + + " console (it was started without --serve). Stop it: the next request starts one with its console. Store: " + + store + "."); + } + String explicit = env.get("TRACEPANEL_AGENT_BIN"); + if (explicit != null && !explicit.isBlank() && !Files.isRegularFile(Path.of(explicit))) { + return new Console.NoConsole("No tracepanel-agent to start", "TRACEPANEL_AGENT_BIN names " + explicit + + ", which isn't there. Set it to the tracepanel-agent binary's path."); + } + if (noBinary) { + return new Console.NoConsole("No tracepanel-agent to start", "No tracepanel-agent binary to start: set" + + " TRACEPANEL_AGENT_BIN to the agent's path, or put tracepanel-agent on the PATH (the SDK downloads its" + + " own unless it is offline)."); + } + return new Console.NoConsole("Tracepanel's agent didn't start", "Tracepanel's agent didn't start: " + + store.resolve("agent.log") + " says why. It is tried again within 30 seconds."); + } + /** * 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. @@ -132,6 +173,7 @@ static boolean answers(String address) { private boolean start() { String binary = binary(); + noBinary = binary == null; if (binary == null) { warn("no tracepanel-agent: set TRACEPANEL_AGENT_BIN, or put it on the PATH"); return false; diff --git a/tracepanel-core/src/main/java/dev/tracepanel/core/Console.java b/tracepanel-core/src/main/java/dev/tracepanel/core/Console.java index 0c84361..3aeed02 100644 --- a/tracepanel-core/src/main/java/dev/tracepanel/core/Console.java +++ b/tracepanel-core/src/main/java/dev/tracepanel/core/Console.java @@ -5,6 +5,7 @@ import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URI; +import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; @@ -32,6 +33,12 @@ static Answer text(int status, String message) { } } + /** Why the console doesn't answer, and what to do (Agent.noConsole). */ + public record NoConsole(String title, String detail) {} + + // While the console doesn't answer: the browser asks again this often, and the page reloads itself as often. + private static final int RETRY_S = 2; + private Console() {} public static boolean local(String address) { @@ -48,6 +55,15 @@ static boolean answers(String from, boolean remote) { * elsewhere is refused; so is one over MAX_BODY (`body` null: too large to read). */ public static Answer forward(Tracepanel tracepanel, String method, String path, String contentType, byte[] body, String from) { + return forward(tracepanel, method, path, contentType, body, from, null); + } + + /** + * As above, the request's Accept header given: without a console, a browser's page (it accepts HTML) gets a page + * that says why and reloads itself until the console answers. + */ + public static Answer forward( + Tracepanel tracepanel, String method, String path, String contentType, byte[] body, String from, String accept) { if (!answers(from, tracepanel.config().consoleRemote())) { return Answer.text(403, "The Tracepanel console answers this machine only. TRACEPANEL_CONSOLE_REMOTE=1 opens it" + " to others, such as when the app runs in a container."); @@ -56,7 +72,7 @@ public static Answer forward(Tracepanel tracepanel, String method, String path, // another service's (a linked trace of the chain) the agent asks that app for, down its connection. if (method.equals("GET") && (path.equals("api/explain") || path.startsWith("api/explain?"))) { Answer here = Explain.answer(tracepanel, path.substring(path.indexOf('?') + 1)); - return here != null ? here : agent(tracepanel, method, path, contentType, body, EXPLAIN_TIMEOUT_MS); + return here != null ? here : agent(tracepanel, method, path, contentType, body, accept, EXPLAIN_TIMEOUT_MS); } if (method.equals("GET") && (path.equals("api/capabilities") || path.startsWith("api/capabilities?"))) { // The agent answers what the console can offer, from the app's hello: connected now, it has heard it. @@ -66,15 +82,19 @@ public static Answer forward(Tracepanel tracepanel, String method, String path, if (!local(from)) return Answer.text(403, "The Tracepanel console takes writes from this machine only."); if (body == null) return Answer.text(413, "Too large."); } - return agent(tracepanel, method, path, contentType, body, TIMEOUT_MS); + return agent(tracepanel, method, path, contentType, body, accept, TIMEOUT_MS); } - /** The agent's answer to the request, waited for up to `timeout` milliseconds; the agent started if none answers. */ - private static Answer agent(Tracepanel tracepanel, String method, String path, String contentType, byte[] body, int timeout) { + /** + * The agent's answer to the request, waited for up to `timeout` milliseconds; the agent started if none answers. + * Without a console, 503: why, and what to do. + */ + private static Answer agent( + Tracepanel tracepanel, String method, String path, String contentType, byte[] body, String accept, int timeout) { Agent agent = tracepanel.agent(); String base = agent.console(); if (base == null && agent.ensure(false)) base = agent.console(); - if (base == null) return Answer.text(503, "No Tracepanel agent: set TRACEPANEL_AGENT_BIN, or put tracepanel-agent on the PATH."); + if (base == null) return unavailable(agent.noConsole(), accept); try { return fetch(base + path, method, contentType, body, tracepanel.config().service(), timeout); } catch (IOException e) { @@ -83,11 +103,64 @@ private static Answer agent(Tracepanel tracepanel, String method, String path, S try { return fetch(base + path, method, contentType, body, tracepanel.config().service(), timeout); } catch (IOException again) { - return Answer.text(502, "Tracepanel's agent doesn't answer."); + return unavailable(agent.noConsole(), accept); } } - return Answer.text(502, "Tracepanel's agent doesn't answer."); + return unavailable(agent.noConsole(), accept); + } + } + + /** + * No console: 503 with why and what to do. A browser's page (it accepts HTML) gets a small page that reloads itself + * until the console answers; the console's API calls and its files get `{"error": ...}`. + */ + static Answer unavailable(NoConsole why, String accept) { + Map headers = Map.of("Retry-After", String.valueOf(RETRY_S), "Cache-Control", "no-store"); + if (accept != null && accept.contains("text/html")) { + return new Answer(503, "text/html; charset=utf-8", headers, page(why).getBytes(StandardCharsets.UTF_8)); + } + return new Answer(503, "application/json", headers, Json.write(Map.of("error", why.detail())).getBytes(StandardCharsets.UTF_8)); + } + + /** The page in the console's look (its dark tokens), with nothing to load: the console is what's missing. */ + static String page(NoConsole why) { + return """ + + + + + + + Tracepanel: %2$s + + + +
+

%2$s

+

%3$s

+

This page reloads itself every %1$d seconds and shows the console once it answers.

+
+ + + """.formatted(RETRY_S, escape(why.title()), escape(why.detail())); + } + + private static String escape(String text) { + StringBuilder out = new StringBuilder(text.length()); + for (char c : text.toCharArray()) { + if ("&<>\"'".indexOf(c) >= 0) out.append("&#").append((int) c).append(';'); + else out.append(c); } + return out.toString(); } /** diff --git a/tracepanel-core/src/test/java/dev/tracepanel/core/ConsoleUnavailableTest.java b/tracepanel-core/src/test/java/dev/tracepanel/core/ConsoleUnavailableTest.java new file mode 100644 index 0000000..7c66725 --- /dev/null +++ b/tracepanel-core/src/test/java/dev/tracepanel/core/ConsoleUnavailableTest.java @@ -0,0 +1,136 @@ +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.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; +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; + +/** The console's answer when no console answers: 503, why and what to do; a page that reloads itself for a browser. */ +class ConsoleUnavailableTest { + private static final String HTML = "text/html,application/xhtml+xml"; + private static final Map RETRY = Map.of("Retry-After", "2", "Cache-Control", "no-store"); + + @TempDir + Path root; + + private Path store() { + return root.resolve(".tracepanel"); + } + + private Tracepanel tracepanel(Map more) throws Exception { + Files.createDirectories(store()); + Map env = new HashMap<>(Map.of( + "TRACEPANEL_ROOT", root.toString(), "TRACEPANEL_DIR", store().toString(), + "TRACEPANEL_AGENT_BIN", root.resolve("no-such-agent").toString())); + env.putAll(more); + return new Tracepanel(Config.load(env, "shop"), List.of(), env); + } + + private static Console.Answer get(Tracepanel tracepanel, String accept) { + return Console.forward(tracepanel, "GET", "api/counts", null, null, "127.0.0.1", accept); + } + + private static String json(String error) { + return Json.write(Map.of("error", error)); + } + + private static Map answered(Console.Answer answer) { + return Map.of("status", answer.status(), "type", answer.contentType(), "headers", answer.headers(), + "body", new String(answer.body(), StandardCharsets.UTF_8)); + } + + private String withoutConsole() { + return "The project's agent runs without its console (it was started without --serve). Stop it: the next request" + + " starts one with its console. Store: " + store() + "."; + } + + @Test + void an_agent_without_its_console_gets_a_page_that_says_to_stop_it_and_reloads() throws Exception { + Tracepanel tracepanel = tracepanel(Map.of()); + try (ServerSocket agent = new ServerSocket(0, 5, InetAddress.getLoopbackAddress())) { + Files.writeString(store().resolve("agent.addr"), "tcp:127.0.0.1:" + agent.getLocalPort() + "\n"); + + Console.Answer answer = get(tracepanel, HTML); + String page = new String(answer.body(), StandardCharsets.UTF_8); + + assertEquals(List.of(503, "text/html; charset=utf-8", RETRY), List.of(answer.status(), answer.contentType(), answer.headers())); + assertTrue(page.contains(""), page); + assertTrue(page.contains("

Tracepanel's agent runs without its console

"), page); + assertTrue(page.contains("

" + withoutConsole().replace("'", "'") + "

"), page); + } + } + + @Test + void an_agent_without_its_console_its_console_address_left_over_gets_json() throws Exception { + Tracepanel tracepanel = tracepanel(Map.of()); + try (ServerSocket agent = new ServerSocket(0, 5, InetAddress.getLoopbackAddress())) { + Files.writeString(store().resolve("agent.addr"), "tcp:127.0.0.1:" + agent.getLocalPort() + "\n"); + Files.writeString(store().resolve("console.addr"), "http://127.0.0.1:9/\n"); + + assertEquals( + Map.of("status", 503, "type", "application/json", "headers", RETRY, "body", json(withoutConsole())), + answered(get(tracepanel, "*/*"))); + } + } + + @Test + void the_agent_off_says_so() throws Exception { + Tracepanel tracepanel = tracepanel(Map.of("TRACEPANEL_AGENT", "off")); + + assertEquals( + Map.of("status", 503, "type", "application/json", "headers", RETRY, "body", json( + "Tracepanel's agent is off (TRACEPANEL_AGENT=off): traces aren't kept and there is no console." + + " Unset TRACEPANEL_AGENT to have the app start it.")), + answered(get(tracepanel, null))); + } + + @Test + void no_binary_to_start_says_how_to_get_one() throws Exception { + Tracepanel tracepanel = tracepanel(Map.of()); + + assertEquals( + Map.of("status", 503, "type", "application/json", "headers", RETRY, "body", json( + "TRACEPANEL_AGENT_BIN names " + root.resolve("no-such-agent") + + ", which isn't there. Set it to the tracepanel-agent binary's path.")), + answered(get(tracepanel, null))); + } + + @Test + @DisabledOnOs(OS.WINDOWS) + void an_agent_that_does_not_start_points_to_its_log() throws Exception { + Path binary = root.resolve("tracepanel-agent"); + Files.writeString(binary, "#!/bin/sh\nexit 1\n"); + Files.setPosixFilePermissions(binary, PosixFilePermissions.fromString("rwx------")); + Tracepanel tracepanel = tracepanel(Map.of("TRACEPANEL_AGENT_BIN", binary.toString())); + + assertEquals( + Map.of("status", 503, "type", "application/json", "headers", RETRY, "body", json( + "Tracepanel's agent didn't start: " + store().resolve("agent.log") + + " says why. It is tried again within 30 seconds.")), + answered(get(tracepanel, null))); + } + + @Test + void the_page_needs_nothing_from_elsewhere_and_what_it_says_makes_no_markup() { + String page = Console.page(new Console.NoConsole("A title", "Store: /tmp/\"x\" & 'y'.")); + + assertTrue(page.contains("Tracepanel: A <b>title</b>"), page); + assertTrue(page.contains("

Store: /tmp/"x" & 'y'.

"), page); + + assertFalse(Pattern.compile("<(script|link|img)\\b|https?:").matcher(page).find(), page); + } +} diff --git a/tracepanel-ktor/src/main/kotlin/dev/tracepanel/ktor/Tracepanel.kt b/tracepanel-ktor/src/main/kotlin/dev/tracepanel/ktor/Tracepanel.kt index 899e7c8..39914ea 100644 --- a/tracepanel-ktor/src/main/kotlin/dev/tracepanel/ktor/Tracepanel.kt +++ b/tracepanel-ktor/src/main/kotlin/dev/tracepanel/ktor/Tracepanel.kt @@ -345,6 +345,7 @@ private suspend fun console(tracepanel: Core, call: ApplicationCall, path: Strin tracepanel, method, path + if (query.isEmpty()) "" else "?$query", call.request.contentType().takeIf { it != ContentType.Any }?.toString(), body?.takeIf { it.size <= Console.MAX_BODY }, call.request.local.remoteAddress, + call.request.headers["Accept"], ) answer.headers().forEach { (name, value) -> call.response.headers.append(name, value, safeOnly = false) } call.respondBytes( diff --git a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelServerFilter.java b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelServerFilter.java index 69643f5..c963393 100644 --- a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelServerFilter.java +++ b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelServerFilter.java @@ -186,7 +186,7 @@ private Publisher> console(HttpRequest request, String String address = remote.getAddress() == null ? remote.getHostString() : remote.getAddress().getHostAddress(); Console.Answer answer = Console.forward(tracepanel, request.getMethodName(), path + (query == null ? "" : "?" + query), request.getContentType().map(Object::toString).orElse(null), - body, address); + body, address, request.getHeaders().get("Accept")); MutableHttpResponse response = HttpResponse.status(HttpStatus.valueOf(answer.status())) .body(answer.body()).contentType(answer.contentType()); answer.headers().forEach(response::header); diff --git a/tracepanel-spring-boot/src/main/java/dev/tracepanel/spring/TracepanelFilter.java b/tracepanel-spring-boot/src/main/java/dev/tracepanel/spring/TracepanelFilter.java index 3684c82..9f6844f 100644 --- a/tracepanel-spring-boot/src/main/java/dev/tracepanel/spring/TracepanelFilter.java +++ b/tracepanel-spring-boot/src/main/java/dev/tracepanel/spring/TracepanelFilter.java @@ -293,7 +293,7 @@ private void console(HttpServletRequest request, HttpServletResponse response, S if (body != null && body.length > Console.MAX_BODY) body = null; } Console.Answer answer = Console.forward(tracepanel, request.getMethod(), path + (query == null ? "" : "?" + query), - request.getContentType(), body, request.getRemoteAddr()); + request.getContentType(), body, request.getRemoteAddr(), request.getHeader("Accept")); response.setStatus(answer.status()); if (answer.contentType() != null) response.setContentType(answer.contentType()); answer.headers().forEach(response::setHeader);