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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# Changelog

## Unreleased

### Fixed

- Without the agent's console, the console says why for each case (one
running without `--serve` too), as a 503 with `Retry-After`. Its page
reloads itself.

## 0.16.0 (2026-11-10)

Needs `tracepanel-agent` 0.16.0 (installed with it).
Expand Down
1 change: 1 addition & 0 deletions src/tracepanel/asgi/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,7 @@ async def _console(self, scope: Scope, receive: Receive, send: Send, path: str)
content_type=headers.get(b"content-type", b"").decode("latin-1"),
local=is_local(str(client[0])),
too_large=too_large,
accept=headers.get(b"accept", b"").decode("latin-1"),
)
# The console reads SQLite (and may wait for the writer): off the event loop.
response = await asyncio.to_thread(console.dispatch, request)
Expand Down
64 changes: 51 additions & 13 deletions src/tracepanel/console/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def handle(request: Request) -> Response:
document = proxy.trace(trace_id) if trace_id else None
if _service(document) not in {"", conf.get_config().service}:
forwarded = proxy.forward(request, request.path, timeout=proxy.EXPLAIN_TIMEOUT_S)
return forwarded or _no_agent(api=True)
return forwarded or _no_console(request)
span = _span(document, request.query.get("span", ""))
attrs = span.get("attrs") if span else None
if span is None or span.get("kind") != "sql" or not isinstance(attrs, dict):
Expand Down Expand Up @@ -136,7 +136,7 @@ def dispatch(request: Request) -> Response:
connected = getattr(transport.get_writer(), "connected", None)
if callable(connected):
connected()
return proxy.forward(request, request.path) or _no_agent(api=path is not None)
return proxy.forward(request, request.path) or _no_console(request)


def _refused_write(request: Request) -> Response | None:
Expand All @@ -148,14 +148,52 @@ def _refused_write(request: Request) -> Response | None:
return None


def _no_agent(*, api: bool) -> Response:
"""The console without an agent: why, and what to do."""
reason = agent.unavailable(conf.get_config())
if api:
return json_response({"error": f"No tracepanel agent: {reason}"}, status=SERVICE_UNAVAILABLE)
page = (
"<!doctype html><meta charset=utf-8><title>tracepanel</title>"
"<body style='font-family: system-ui; max-width: 40rem; margin: 4rem auto; line-height: 1.5'>"
f"<h1>tracepanel</h1><p>The console comes from the tracepanel agent, and {html.escape(reason)}</p>"
)
return Response(status=SERVICE_UNAVAILABLE, content_type="text/html; charset=utf-8", body=page.encode())
# While the console doesn't answer: the browser asks again this often, and the page reloads itself as often.
RETRY_S = 2


def _no_console(request: Request) -> Response:
"""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": ...}`.
"""
why = agent.no_console(conf.get_config())
headers = {"Retry-After": str(RETRY_S), "Cache-Control": "no-store"}
if "text/html" in request.accept:
body = page(why).encode()
return Response(status=SERVICE_UNAVAILABLE, content_type="text/html; charset=utf-8", body=body, headers=headers)
body = json.dumps({"error": why.detail}, separators=(",", ":")).encode()
return Response(status=SERVICE_UNAVAILABLE, body=body, headers=headers)


def page(why: agent.NoConsole) -> str:
"""The page in the console's look (its dark tokens), with nothing to load: the console is the thing missing."""
title, detail = (html.escape(text, quote=True) for text in why)
return f"""<!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="{RETRY_S}">
<title>Tracepanel: {title}</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>{title}</h1>
<p>{detail}</p>
<p class="muted">This page reloads itself every {RETRY_S} seconds and shows the console once it answers.</p>
</main>
</body>
</html>
"""
2 changes: 2 additions & 0 deletions src/tracepanel/console/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ class Request:
local: bool = False
# Its body was over MAX_BODY: not read, answered 413.
too_large: bool = False
# Its Accept header: a browser's page (text/html) gets a page that says why when there is no console.
accept: str = ""


@dataclass(slots=True)
Expand Down
1 change: 1 addition & 0 deletions src/tracepanel/django/console.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ def dispatch(request: HttpRequest, path: str) -> HttpResponseBase:
content_type=request.content_type or "" if body else "",
local=from_this_machine(request),
too_large=too_large,
accept=request.headers.get("Accept", ""),
)
)
if isinstance(response.native, HttpResponseBase):
Expand Down
51 changes: 50 additions & 1 deletion src/tracepanel/storage/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
import time
from collections.abc import Callable, Iterator
from pathlib import Path
from typing import BinaryIO
from typing import BinaryIO, NamedTuple

if sys.platform == "win32":
import msvcrt
Expand Down Expand Up @@ -221,6 +221,55 @@ def unavailable(config: conf.Config) -> str:
return f"the agent isn't running (see {store_dir(config) / LOG_FILE}): traces aren't kept until it is."


class NoConsole(NamedTuple):
"""Why the console doesn't answer, and what to do: the console's 503 (console.app), in the other SDKs' words."""

title: str
detail: str


def no_console(config: conf.Config) -> NoConsole:
"""What keeps the project's console from answering, as far as this process can tell."""
if config.agent == "off":
return NoConsole(
"Tracepanel's agent is off",
"Tracepanel's agent is off (the agent setting, TRACEPANEL_AGENT=off): traces aren't kept and there is no "
"console. Set it to auto to have the app start it.",
)
if config.agent != "auto":
return NoConsole(
"The console doesn't answer",
f"No console answers at {config.console_url} (the console_url setting) for the agent at {config.agent}. "
"Start that agent with --serve, or correct the address.",
)
directory = store_dir(config)
if answers(address(config)):
# The agent writes its console's address before its own: one that answers without a console was started so.
return 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 "
f"request starts one with its console. Store: {directory}.",
)
explicit = os.environ.get("TRACEPANEL_AGENT_BIN")
if explicit and not Path(explicit).is_file():
return NoConsole(
"No tracepanel-agent to start",
f"TRACEPANEL_AGENT_BIN names {explicit}, which isn't there. Set it to the tracepanel-agent binary's path.",
)
if binary() is None:
return NoConsole(
"No tracepanel-agent to start",
f"No tracepanel-agent binary to start for this platform ({sys.platform}, {platform.machine()}): set "
"TRACEPANEL_AGENT_BIN to the agent's path, or use an agent on another machine: "
"TRACEPANEL_AGENT=tcp:HOST:PORT.",
)
return NoConsole(
"Tracepanel's agent didn't start",
f"Tracepanel's agent didn't start: {directory / LOG_FILE} says why. It is tried again within "
f"{RESTART_S:.0f} seconds.",
)


_start_lock = forks.lock()
_start_after = 0.0

Expand Down
1 change: 1 addition & 0 deletions src/tracepanel/wsgi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,7 @@ def _console(environ: dict[str, Any], path: str, start_response: StartResponse)
content_type=str(environ.get("CONTENT_TYPE", "")) if readable else "",
local=is_local(str(environ.get("REMOTE_ADDR", ""))),
too_large=too_large,
accept=str(environ.get("HTTP_ACCEPT", "")),
)
response = console.dispatch(request)
status = f"{response.status} {http.HTTPStatus(response.status).phrase}"
Expand Down
129 changes: 129 additions & 0 deletions tests/console/test_no_console.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
"""No console answers: 503, why and what to do; a browser's page gets a page that reloads itself until it does."""

import json
import re
import socket
from collections.abc import Iterator
from pathlib import Path

import pytest

from tracepanel.console import app
from tracepanel.console.messages import Request
from tracepanel.core import conf
from tracepanel.storage import agent

HTML = "text/html,application/xhtml+xml"
RETRY = {"Retry-After": "2", "Cache-Control": "no-store"}


@pytest.fixture
def store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
"""The project's store, no agent of its own; the tests never start one (under pytest the SDK doesn't)."""
directory = tmp_path / ".tracepanel"
directory.mkdir()
monkeypatch.setenv("TRACEPANEL_DIR", str(directory))
monkeypatch.setenv("TRACEPANEL_AGENT", "auto")
monkeypatch.setenv("TRACEPANEL_AGENT_BIN", str(tmp_path / "no-such-agent"))
conf.reset()
return directory


@pytest.fixture
def without_console(store: Path) -> Iterator[Path]:
"""An agent that takes traces and serves no console (started without --serve): its address in the store."""
with socket.create_server(("127.0.0.1", 0)) as listening:
(store / "agent.addr").write_text(f"tcp:127.0.0.1:{listening.getsockname()[1]}\n")
yield store


def answered(accept: str = "") -> dict[str, object]:
response = app.dispatch(Request(method="GET", path="api/counts" if not accept else "", accept=accept))
return {
"status": response.status,
"type": response.content_type,
"headers": response.headers,
"body": response.body.decode(),
}


def error(message: str) -> dict[str, object]:
return {
"status": 503,
"type": "application/json",
"headers": RETRY,
"body": json.dumps({"error": message}, separators=(",", ":")),
}


def runs_without_console(store: Path) -> str:
return (
"The project's agent runs without its console (it was started without --serve). Stop it: the next request "
f"starts one with its console. Store: {store}."
)


def test_an_agent_without_its_console_gets_a_page_that_says_to_stop_it_and_reloads(without_console: Path) -> None:
page = answered(HTML)
body = str(page["body"])

assert page == {"status": 503, "type": "text/html; charset=utf-8", "headers": RETRY, "body": body}

assert '<meta http-equiv="refresh" content="2">' in body
assert "<h1>Tracepanel&#x27;s agent runs without its console</h1>" in body
detail = runs_without_console(without_console).replace("'", "&#x27;")
assert f"<p>{detail}</p>" in body


def test_an_agent_without_its_console_its_console_address_left_over(without_console: Path) -> None:
(without_console / "console.addr").write_text("http://127.0.0.1:9/\n")

assert answered() == error(runs_without_console(without_console))


def test_the_agent_off_says_so(store: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("TRACEPANEL_AGENT", "off")
conf.reset()

assert answered() == error(
"Tracepanel's agent is off (the agent setting, TRACEPANEL_AGENT=off): traces aren't kept and there is no "
"console. Set it to auto to have the app start it."
)


def test_a_named_agent_without_a_console_says_where_it_looked(store: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("TRACEPANEL_AGENT", "tcp:127.0.0.1:9")
monkeypatch.setenv("TRACEPANEL_CONSOLE_URL", "http://127.0.0.1:9/")
conf.reset()

assert answered() == error(
"No console answers at http://127.0.0.1:9/ (the console_url setting) for the agent at tcp:127.0.0.1:9. "
"Start that agent with --serve, or correct the address."
)


def test_no_binary_to_start_says_how_to_get_one(store: Path) -> None:
missing = store.parent / "no-such-agent"

assert answered() == error(
f"TRACEPANEL_AGENT_BIN names {missing}, which isn't there. Set it to the tracepanel-agent binary's path."
)


def test_an_agent_that_does_not_start_points_to_its_log(store: Path, monkeypatch: pytest.MonkeyPatch) -> None:
binary = store.parent / "tracepanel-agent"
binary.write_text("#!/bin/sh\nexit 1\n")
monkeypatch.setenv("TRACEPANEL_AGENT_BIN", str(binary))

assert answered() == error(
f"Tracepanel's agent didn't start: {store / 'agent.log'} says why. It is tried again within 30 seconds."
)


def test_the_page_needs_nothing_from_elsewhere_and_what_it_says_makes_no_markup() -> None:
page = app.page(agent.NoConsole("A <b>title</b>", "Store: /tmp/\"x\" & 'y'."))

assert "<title>Tracepanel: A &lt;b&gt;title&lt;/b&gt;</title>" in page
assert "<p>Store: /tmp/&quot;x&quot; &amp; &#x27;y&#x27;.</p>" in page

assert re.search(r"<(script|link|img)\b|https?:", page) is None
6 changes: 3 additions & 3 deletions tests/django/test_widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,13 @@ def test_widget_can_be_disabled(client: Client, traces: list[Trace], db: None, s
def test_without_an_agent_no_script_and_the_console_says_why(client: Client, traces: list[Trace], db: None) -> None:
# The panel is the agent's: without one (the tests turn it off) the page gets the headers, not the script.
body = client.get("/html/").content.decode()
console = client.get("/__tracepanel__/")
console = client.get("/__tracepanel__/", headers={"Accept": "text/html"})
api = client.get("/__tracepanel__/api/counts")

assert "<script" not in body

assert (console.status_code, "the agent is off" in console.content.decode()) == (503, True)
assert (api.status_code, api.json()) == (503, {"error": IsStr(regex="No tracepanel agent: the agent is off.*")})
assert (console.status_code, "agent is off" in console.content.decode()) == (503, True)
assert (api.status_code, api.json()) == (503, {"error": IsStr(regex="Tracepanel's agent is off .*")})


def test_a_pages_redirect_is_named_for_the_page_it_leads_to(client: Client, traces: list[Trace]) -> None:
Expand Down
Loading