Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
42 changes: 42 additions & 0 deletions tracepanel-core/src/main/java/dev/tracepanel/core/Agent.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ public final class Agent {
private final Map<String, String> 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<String, String> env) {
this.store = store;
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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;
Expand Down
87 changes: 80 additions & 7 deletions tracepanel-core/src/main/java/dev/tracepanel/core/Console.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand All @@ -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.");
Expand All @@ -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.
Expand All @@ -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) {
Expand All @@ -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<String, String> 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 """
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="refresh" content="%1$d">
<title>Tracepanel: %2$s</title>
<style>
:root { color-scheme: dark; }
body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #0a0c11; color: #eceef3;
font: 15px/1.55 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; }
main { box-sizing: border-box; max-width: 38rem; margin: 2rem 1rem; padding: 1.5rem 1.75rem; border: 1px solid #2a3040;
border-radius: 12px; background: rgb(245 181 68 / 0.06); }
h1 { margin: 0 0 0.75rem; font-size: 1.05rem; font-weight: 600; color: #f5b544; }
p { margin: 0.5rem 0; overflow-wrap: anywhere; }
.muted { color: #8c93a6; font-size: 13px; }
</style>
</head>
<body>
<main>
<h1>%2$s</h1>
<p>%3$s</p>
<p class="muted">This page reloads itself every %1$d seconds and shows the console once it answers.</p>
</main>
</body>
</html>
""".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();
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -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<String, String> RETRY = Map.of("Retry-After", "2", "Cache-Control", "no-store");

@TempDir
Path root;

private Path store() {
return root.resolve(".tracepanel");
}

private Tracepanel tracepanel(Map<String, String> more) throws Exception {
Files.createDirectories(store());
Map<String, String> 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<String, Object> 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("<meta http-equiv=\"refresh\" content=\"2\">"), page);
assertTrue(page.contains("<h1>Tracepanel&#39;s agent runs without its console</h1>"), page);
assertTrue(page.contains("<p>" + withoutConsole().replace("'", "&#39;") + "</p>"), 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 <b>title</b>", "Store: /tmp/\"x\" & 'y'."));

assertTrue(page.contains("<title>Tracepanel: A &#60;b&#62;title&#60;/b&#62;</title>"), page);
assertTrue(page.contains("<p>Store: /tmp/&#34;x&#34; &#38; &#39;y&#39;.</p>"), page);

assertFalse(Pattern.compile("<(script|link|img)\\b|https?:").matcher(page).find(), page);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ private Publisher<MutableHttpResponse<?>> 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<byte[]> response = HttpResponse.status(HttpStatus.valueOf(answer.status()))
.body(answer.body()).contentType(answer.contentType());
answer.headers().forEach(response::header);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down