diff options
| author | Stefan Boberg <[email protected]> | 2026-03-23 14:19:57 +0100 |
|---|---|---|
| committer | GitHub Enterprise <[email protected]> | 2026-03-23 14:19:57 +0100 |
| commit | 2a445406e09328cb4cf320300f2678997d6775b7 (patch) | |
| tree | a92f02d94c92144cb6ae32160397298533e4c822 /src/zenutil/splitconsole | |
| parent | add hub instance crash recovery (#885) (diff) | |
| download | zen-2a445406e09328cb4cf320300f2678997d6775b7.tar.xz zen-2a445406e09328cb4cf320300f2678997d6775b7.zip | |
Dashboard refresh (logs, storage, network, object store, docs) (#835)
## Summary
This PR adds a session management service, several new dashboard pages, and a number of infrastructure improvements.
### Sessions Service
- `SessionsServiceClient` in `zenutil` announces sessions to a remote zenserver with a 15s heartbeat (POST/PUT/DELETE lifecycle)
- Storage server registers itself with its own local sessions service on startup
- Session mode attribute coupled to server mode (Compute, Proxy, Hub, etc.)
- Ended sessions tracked with `ended_at` timestamp; status filtering (Active/Ended/All)
- `--sessions-url` config option for remote session announcement
- In-process log sink (`InProcSessionLogSink`) forwards server log output to the server's own session, visible in the dashboard
### Session Log Viewer
- POST/GET endpoints for session logs (`/sessions/{id}/log`) supporting raw text and structured JSON/CbObject with batch `entries` array
- In-memory log storage per session (capped at 10k entries) with cursor-based pagination for efficient incremental fetching
- Log panel in the sessions dashboard with incremental DOM updates, auto-scroll (Follow toggle), newest-first toggle, text filter, and log-level coloring
- Auto-selects the server's own session on page load
### TCP Log Streaming
- `LogStreamListener` and `TcpLogStreamSink` for log delivery over TCP
- Sequence numbers on each message with drop detection and synthetic "dropped" notice on gaps
- Gathered buffer writes to reduce syscall overhead when flushing batches
- Tests covering basic delivery, multi-line splitting, drop detection, and sequencing
### New Dashboard Pages
- **Sessions**: master-detail layout with selectable rows, metadata panel, live WebSocket updates, paging, abbreviated date formatting, and "this" pill for the local session
- **Object Store**: summary stats tiles and bucket table with click-to-expand inline object listing (`GET /obj/`)
- **Storage**: per-volume disk usage breakdown (`GET /admin/storage`), Garbage Collection status section (next-run countdown, last-run stats), and GC History table with paginated rows and expandable detail panels
- **Network**: overview tiles, per-service request table, proxy connections, and live WebSocket updates; distinct client IPs and session counts via HyperLogLog
### Documentation Page
- In-dashboard Docs page with sidebar navigation, markdown rendering (via `marked`), Mermaid diagram support (theme-aware), collapsible sections, text filtering with highlighting, and cross-document linking
- New user-facing docs: `overview.md` (with architecture and per-mode diagrams), `sessions.md`, `cache.md`, `projects.md`; updated `compute.md`
- Dev docs moved to `docs/dev/`
### Infrastructure & Bug Fixes
- **Deflate compression** for the embedded frontend zip (~3.4MB → ~950KB); zlib inflate support added to `ZipFs` with cached decompressed buffers
- **Local IP addresses**: `GetLocalIpAddresses()` (Windows via `GetAdaptersAddresses`, Linux/Mac via `getifaddrs`); surfaced in `/status/status`, `/health/info`, and the dashboard banner
- **Dashboard nav**: unified into `zen-nav` web component with `MutationObserver` for dynamically added links, CSS `::part()` to merge banner/nav border radii, and prefix-based active link detection
- Stats broadcast refactored from manual JSON string concatenation to `CbObjectWriter`; `CbObject`-to-JS conversion improved for `TimeSpan`, `DateTime`, and large integers
- Stats WebSocket boilerplate consolidated into `ZenPage.connect_stats_ws()`
Diffstat (limited to 'src/zenutil/splitconsole')
| -rw-r--r-- | src/zenutil/splitconsole/logstreamlistener.cpp | 230 |
1 files changed, 193 insertions, 37 deletions
diff --git a/src/zenutil/splitconsole/logstreamlistener.cpp b/src/zenutil/splitconsole/logstreamlistener.cpp index 9f1d1a02c..04718b543 100644 --- a/src/zenutil/splitconsole/logstreamlistener.cpp +++ b/src/zenutil/splitconsole/logstreamlistener.cpp @@ -2,6 +2,7 @@ #include <zenutil/splitconsole/logstreamlistener.h> +#include <zenbase/refcount.h> #include <zencore/compactbinary.h> #include <zencore/fmtutils.h> #include <zencore/logging.h> @@ -11,7 +12,6 @@ ZEN_THIRD_PARTY_INCLUDES_START #include <asio.hpp> ZEN_THIRD_PARTY_INCLUDES_END -#include <atomic> #include <vector> namespace zen { @@ -19,21 +19,17 @@ namespace zen { ////////////////////////////////////////////////////////////////////////// // LogStreamSession — reads CbObject-framed messages from a single TCP connection -class LogStreamSession : public std::enable_shared_from_this<LogStreamSession> +class LogStreamSession : public RefCounted { public: - LogStreamSession(asio::ip::tcp::socket Socket, std::atomic<LogStreamHandler*>& Handler) - : m_Socket(std::move(Socket)) - , m_Handler(Handler) - { - } + LogStreamSession(asio::ip::tcp::socket Socket, LogStreamTarget& Target) : m_Socket(std::move(Socket)), m_Target(Target) {} void Start() { DoRead(); } private: void DoRead() { - auto Self = shared_from_this(); + Ref<LogStreamSession> Self(this); m_Socket.async_read_some(asio::buffer(m_ReadBuf.data() + m_BufferUsed, m_ReadBuf.size() - m_BufferUsed), [Self](const asio::error_code& Ec, std::size_t BytesRead) { if (Ec) @@ -71,8 +67,17 @@ private: std::string_view Text = Obj["text"].AsString(); std::string_view Source = Obj["source"].AsString(); + // Check sequence number for gaps (dropped messages) + uint64_t Seq = Obj["seq"].AsUInt64(); + if (Seq > m_NextExpectedSeq) + { + uint64_t Dropped = Seq - m_NextExpectedSeq; + m_Target.AppendLogLine(fmt::format("[{}] *** {} log message(s) dropped ***", Source.empty() ? "log" : Source, Dropped)); + } + m_NextExpectedSeq = Seq + 1; + // Split multi-line messages into individual AppendLogLine calls so that - // each line gets its own row in the SplitConsole ring buffer. + // each line gets its own row in the target's log output. while (!Text.empty()) { std::string_view Line = Text; @@ -98,17 +103,13 @@ private: continue; } - LogStreamHandler* Handler = m_Handler.load(std::memory_order_acquire); - if (Handler) + if (!Source.empty()) { - if (!Source.empty()) - { - Handler->AppendLogLine(fmt::format("[{}] {}", Source, Line)); - } - else - { - Handler->AppendLogLine(std::string(Line)); - } + m_Target.AppendLogLine(fmt::format("[{}] {}", Source, Line)); + } + else + { + m_Target.AppendLogLine(Line); } } @@ -128,10 +129,11 @@ private: } } - asio::ip::tcp::socket m_Socket; - std::atomic<LogStreamHandler*>& m_Handler; - std::array<uint8_t, 65536> m_ReadBuf{}; - std::size_t m_BufferUsed = 0; + asio::ip::tcp::socket m_Socket; + LogStreamTarget& m_Target; + std::array<uint8_t, 65536> m_ReadBuf{}; + std::size_t m_BufferUsed = 0; + uint64_t m_NextExpectedSeq = 0; }; ////////////////////////////////////////////////////////////////////////// @@ -140,7 +142,10 @@ private: struct LogStreamListener::Impl { // Owned io_context mode — creates and runs its own thread - explicit Impl(uint16_t Port) : m_OwnedIoContext(std::make_unique<asio::io_context>()), m_Acceptor(*m_OwnedIoContext) + Impl(LogStreamTarget& Target, uint16_t Port) + : m_Target(Target) + , m_OwnedIoContext(std::make_unique<asio::io_context>()) + , m_Acceptor(*m_OwnedIoContext) { SetupAcceptor(Port); m_IoThread = std::thread([this]() { @@ -150,7 +155,10 @@ struct LogStreamListener::Impl } // External io_context mode — caller drives the io_context - Impl(asio::io_context& IoContext, uint16_t Port) : m_Acceptor(IoContext) { SetupAcceptor(Port); } + Impl(LogStreamTarget& Target, asio::io_context& IoContext, uint16_t Port) : m_Target(Target), m_Acceptor(IoContext) + { + SetupAcceptor(Port); + } ~Impl() { Shutdown(); } @@ -177,11 +185,12 @@ struct LogStreamListener::Impl uint16_t GetPort() const { return m_Port; } - void SetHandler(LogStreamHandler* Handler) { m_Handler.store(Handler, std::memory_order_release); } - private: void SetupAcceptor(uint16_t Port) { + auto& IoCtx = m_OwnedIoContext ? *m_OwnedIoContext : m_Acceptor.get_executor().context(); + ZEN_UNUSED(IoCtx); + // Try dual-stack IPv6 first (accepts both IPv4 and IPv6), fall back to IPv4-only asio::error_code Ec; m_Acceptor.open(asio::ip::tcp::v6(), Ec); @@ -218,7 +227,7 @@ private: return; // acceptor closed } - auto Session = std::make_shared<LogStreamSession>(std::move(Socket), m_Handler); + Ref<LogStreamSession> Session(new LogStreamSession(std::move(Socket), m_Target)); Session->Start(); if (!m_Stopped.load()) @@ -228,7 +237,7 @@ private: }); } - std::atomic<LogStreamHandler*> m_Handler{nullptr}; + LogStreamTarget& m_Target; std::unique_ptr<asio::io_context> m_OwnedIoContext; // null when using external io_context asio::ip::tcp::acceptor m_Acceptor; std::thread m_IoThread; @@ -239,22 +248,17 @@ private: ////////////////////////////////////////////////////////////////////////// // LogStreamListener -LogStreamListener::LogStreamListener(uint16_t Port) : m_Impl(std::make_unique<Impl>(Port)) +LogStreamListener::LogStreamListener(LogStreamTarget& Target, uint16_t Port) : m_Impl(std::make_unique<Impl>(Target, Port)) { } -LogStreamListener::LogStreamListener(asio::io_context& IoContext, uint16_t Port) : m_Impl(std::make_unique<Impl>(IoContext, Port)) +LogStreamListener::LogStreamListener(LogStreamTarget& Target, asio::io_context& IoContext, uint16_t Port) +: m_Impl(std::make_unique<Impl>(Target, IoContext, Port)) { } LogStreamListener::~LogStreamListener() = default; -void -LogStreamListener::SetHandler(LogStreamHandler* Handler) -{ - m_Impl->SetHandler(Handler); -} - uint16_t LogStreamListener::GetPort() const { @@ -268,3 +272,155 @@ LogStreamListener::Shutdown() } } // namespace zen + +#if ZEN_WITH_TESTS + +# include <zencore/testing.h> +# include <zenutil/splitconsole/tcplogstreamsink.h> + +namespace zen { + +void +logstreamlistener_forcelink() +{ +} + +namespace { + + class CollectingTarget : public LogStreamTarget + { + public: + void AppendLogLine(std::string_view Text) override + { + std::lock_guard<std::mutex> Lock(m_Mutex); + m_Lines.emplace_back(Text); + m_Cv.notify_all(); + } + + std::vector<std::string> WaitForLines(size_t Count, std::chrono::milliseconds Timeout = std::chrono::milliseconds(5000)) + { + std::unique_lock<std::mutex> Lock(m_Mutex); + m_Cv.wait_for(Lock, Timeout, [&]() { return m_Lines.size() >= Count; }); + return m_Lines; + } + + private: + std::mutex m_Mutex; + std::condition_variable m_Cv; + std::vector<std::string> m_Lines; + }; + + logging::LogMessage MakeLogMessage(std::string_view Text, logging::LogLevel Level = logging::Info) + { + static logging::LogPoint Point{{}, Level, {}}; + Point.Level = Level; + return logging::LogMessage(Point, "test", Text); + } + +} // namespace + +TEST_SUITE_BEGIN("util.logstreamlistener"); + +TEST_CASE("BasicMessageDelivery") +{ + CollectingTarget Target; + LogStreamListener Listener(Target); + + { + TcpLogStreamSink Sink("127.0.0.1", Listener.GetPort(), "TestSource", 64); + Sink.Log(MakeLogMessage("hello world")); + Sink.Log(MakeLogMessage("second line")); + } + + auto Lines = Target.WaitForLines(2); + REQUIRE(Lines.size() == 2); + CHECK(Lines[0] == "[TestSource] hello world"); + CHECK(Lines[1] == "[TestSource] second line"); +} + +TEST_CASE("MultiLineMessageSplit") +{ + CollectingTarget Target; + LogStreamListener Listener(Target); + + { + TcpLogStreamSink Sink("127.0.0.1", Listener.GetPort(), "src", 64); + Sink.Log(MakeLogMessage("line1\nline2\nline3")); + } + + auto Lines = Target.WaitForLines(3); + REQUIRE(Lines.size() == 3); + CHECK(Lines[0] == "[src] line1"); + CHECK(Lines[1] == "[src] line2"); + CHECK(Lines[2] == "[src] line3"); +} + +TEST_CASE("DroppedMessageDetection") +{ + // Test sequence-gap detection deterministically by sending raw CbObjects + // with an explicit gap in sequence numbers, bypassing TcpLogStreamSink. + CollectingTarget Target; + LogStreamListener Listener(Target); + + { + asio::io_context IoContext; + asio::ip::tcp::socket Socket(IoContext); + Socket.connect(asio::ip::tcp::endpoint(asio::ip::make_address("127.0.0.1"), Listener.GetPort())); + + // Send seq=0, then seq=5 — the listener should detect a gap of 4 + for (uint64_t Seq : {uint64_t(0), uint64_t(5)}) + { + CbObjectWriter Writer; + Writer.AddString("text", fmt::format("msg{}", Seq)); + Writer.AddString("source", "src"); + Writer.AddInteger("seq", Seq); + CbObject Obj = Writer.Save(); + MemoryView View = Obj.GetView(); + + asio::write(Socket, asio::buffer(View.GetData(), View.GetSize())); + } + } + + // Expect: msg0, drop notice, msg5 + auto Lines = Target.WaitForLines(3); + REQUIRE(Lines.size() >= 3); + CHECK(Lines[0] == "[src] msg0"); + CHECK(Lines[1].find("4 log message(s) dropped") != std::string::npos); + CHECK(Lines[2] == "[src] msg5"); +} + +TEST_CASE("SequenceNumbersAreContiguous") +{ + CollectingTarget Target; + LogStreamListener Listener(Target); + + constexpr int NumMessages = 5; + { + TcpLogStreamSink Sink("127.0.0.1", Listener.GetPort(), "seq", 64); + for (int i = 0; i < NumMessages; i++) + { + Sink.Log(MakeLogMessage(fmt::format("msg{}", i))); + } + } + + auto Lines = Target.WaitForLines(NumMessages); + REQUIRE(Lines.size() == NumMessages); + + // No "dropped" notices should appear when nothing is dropped + for (auto& Line : Lines) + { + CHECK(Line.find("dropped") == std::string::npos); + } + + // Verify ordering + for (int i = 0; i < NumMessages; i++) + { + CHECK(Lines[i] == fmt::format("[seq] msg{}", i)); + } +} + +TEST_SUITE_END(); + +} // namespace zen + +#endif |