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/include | |
| 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/include')
3 files changed, 103 insertions, 59 deletions
diff --git a/src/zenutil/include/zenutil/sessionsclient.h b/src/zenutil/include/zenutil/sessionsclient.h new file mode 100644 index 000000000..aca45e61d --- /dev/null +++ b/src/zenutil/include/zenutil/sessionsclient.h @@ -0,0 +1,65 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#pragma once + +#include <zencore/compactbinary.h> +#include <zencore/logging.h> +#include <zencore/logging/sink.h> + +#include <zencore/uid.h> + +#include <memory> +#include <string> + +namespace zen { + +class HttpClient; + +/// Client for announcing and maintaining a session on a remote zenserver's /sessions/ endpoint. +/// Follows the same best-effort pattern as ZenComputeServer's coordinator announce. +class SessionsServiceClient +{ +public: + struct Options + { + std::string TargetUrl; // Base URL of the target zenserver (e.g. "http://localhost:8558") + std::string AppName; // Application name to register + std::string Mode; // Server mode (e.g. "Server", "Compute", "Proxy") + Oid SessionId = Oid::Zero; // Session ID to register under + Oid JobId = Oid::Zero; // Optional job ID + }; + + explicit SessionsServiceClient(Options Opts); + ~SessionsServiceClient(); + + SessionsServiceClient(const SessionsServiceClient&) = delete; + SessionsServiceClient& operator=(const SessionsServiceClient&) = delete; + + /// POST /sessions/{id} — register or re-announce the session with optional metadata. + [[nodiscard]] bool Announce(CbObjectView Metadata = {}); + + /// PUT /sessions/{id} — update metadata on an existing session. + [[nodiscard]] bool UpdateMetadata(CbObjectView Metadata = {}); + + /// DELETE /sessions/{id} — remove the session. + [[nodiscard]] bool Remove(); + + /// Create a logging sink that forwards log messages to the session's log endpoint. + /// The sink batches messages on a background thread and POSTs them periodically. + /// The returned sink can be added to any logger via Logger::AddSink(). + logging::SinkPtr CreateLogSink(); + + const Options& GetOptions() const { return m_Options; } + const std::string& GetSessionPath() const { return m_SessionPath; } + +private: + CbObject BuildRequestBody(CbObjectView Metadata) const; + + LoggerRef Log() { return m_Log; } + LoggerRef m_Log; + Options m_Options; + std::string m_SessionPath; // "sessions/<hex>" + std::unique_ptr<HttpClient> m_Http; +}; + +} // namespace zen diff --git a/src/zenutil/include/zenutil/splitconsole/logstreamlistener.h b/src/zenutil/include/zenutil/splitconsole/logstreamlistener.h index 06544308c..f3b960f51 100644 --- a/src/zenutil/include/zenutil/splitconsole/logstreamlistener.h +++ b/src/zenutil/include/zenutil/splitconsole/logstreamlistener.h @@ -6,7 +6,7 @@ #include <cstdint> #include <memory> -#include <string> +#include <string_view> ZEN_THIRD_PARTY_INCLUDES_START #include <asio/io_context.hpp> @@ -14,44 +14,37 @@ ZEN_THIRD_PARTY_INCLUDES_END namespace zen { -/// Interface for receiving log lines from a LogStreamListener. -/// Clients implement this to route received log messages to their desired output. -class LogStreamHandler +/// Abstract target for log lines received over a TCP log stream. +class LogStreamTarget { public: - virtual ~LogStreamHandler() = default; + virtual ~LogStreamTarget() = default; - virtual void AppendLogLine(std::string Line) = 0; + /// Called (potentially from any thread) when a log line is received. + virtual void AppendLogLine(std::string_view Text) = 0; }; /// TCP listener that accepts connections from remote processes streaming log messages. /// Each message is a CbObject with fields: "text" (string), "source" (string), "level" (string, optional). /// -/// A LogStreamHandler can be set to receive parsed log lines. If no handler is set, -/// received messages are silently discarded. -/// /// Two modes of operation: -/// - Owned thread: pass only Port; an internal IO thread is created. +/// - Owned thread: pass only Target and Port; an internal IO thread is created. /// - External io_context: pass an existing asio::io_context; no thread is created, /// the caller is responsible for running the io_context. class LogStreamListener { public: /// Start listening with an internal IO thread. - explicit LogStreamListener(uint16_t Port = 0); + LogStreamListener(LogStreamTarget& Target, uint16_t Port = 0); /// Start listening on an externally-driven io_context (no thread created). - LogStreamListener(asio::io_context& IoContext, uint16_t Port = 0); + LogStreamListener(LogStreamTarget& Target, asio::io_context& IoContext, uint16_t Port = 0); ~LogStreamListener(); LogStreamListener(const LogStreamListener&) = delete; LogStreamListener& operator=(const LogStreamListener&) = delete; - /// Set the handler that will receive parsed log lines. May be called at any time. - /// Pass nullptr to stop delivering messages. - void SetHandler(LogStreamHandler* Handler); - /// Returns the actual port the listener is bound to. uint16_t GetPort() const; @@ -63,4 +56,6 @@ private: std::unique_ptr<Impl> m_Impl; }; +void logstreamlistener_forcelink(); + } // namespace zen diff --git a/src/zenutil/include/zenutil/splitconsole/tcplogstreamsink.h b/src/zenutil/include/zenutil/splitconsole/tcplogstreamsink.h index 2ab7d469e..f4ac5ff22 100644 --- a/src/zenutil/include/zenutil/splitconsole/tcplogstreamsink.h +++ b/src/zenutil/include/zenutil/splitconsole/tcplogstreamsink.h @@ -3,11 +3,11 @@ #pragma once #include <zencore/compactbinarybuilder.h> -#include <zencore/logging.h> #include <zencore/logging/sink.h> #include <zencore/thread.h> ZEN_THIRD_PARTY_INCLUDES_START +#include <EASTL/fixed_vector.h> #include <asio.hpp> ZEN_THIRD_PARTY_INCLUDES_END @@ -17,6 +17,7 @@ ZEN_THIRD_PARTY_INCLUDES_END #include <mutex> #include <string> #include <thread> +#include <vector> namespace zen { @@ -52,22 +53,7 @@ public: void Log(const logging::LogMessage& Msg) override { - logging::MemoryBuffer Formatted; - { - RwLock::SharedLockScope Lock(m_FormatterLock); - if (m_Formatter) - { - m_Formatter->Format(Msg, Formatted); - } - else - { - // Fallback: use raw payload - auto Payload = Msg.GetPayload(); - Formatted.append(Payload.data(), Payload.data() + Payload.size()); - } - } - - std::string_view Text(Formatted.data(), Formatted.size()); + std::string_view Text = Msg.GetPayload(); // Strip trailing newlines while (!Text.empty() && (Text.back() == '\n' || Text.back() == '\r')) @@ -75,20 +61,22 @@ public: Text.remove_suffix(1); } - // Build CbObject with text, source, and level fields + uint64_t Seq = m_NextSequence.fetch_add(1, std::memory_order_relaxed); + + // Build CbObject with text, source, level, and sequence number fields CbObjectWriter Writer; Writer.AddString("text", Text); Writer.AddString("source", m_Source); - Writer.AddString("level", ToStringView(Msg.GetLevel())); + Writer.AddString("level", logging::ToStringView(Msg.GetLevel())); + Writer.AddInteger("seq", Seq); CbObject Obj = Writer.Save(); // Enqueue for async write { std::lock_guard<std::mutex> Lock(m_QueueMutex); - if (m_Queue.size() >= m_MaxQueueSize) + while (m_Queue.size() >= m_MaxQueueSize) { m_Queue.pop_front(); - m_DroppedMessages.fetch_add(1, std::memory_order_relaxed); } m_Queue.push_back(std::move(Obj)); } @@ -100,10 +88,9 @@ public: // Nothing to flush — writes happen asynchronously } - void SetFormatter(std::unique_ptr<logging::Formatter> InFormatter) override + void SetFormatter(std::unique_ptr<logging::Formatter> /*InFormatter*/) override { - RwLock::ExclusiveLockScope Lock(m_FormatterLock); - m_Formatter = std::move(InFormatter); + // Not used — we output the raw payload directly } private: @@ -131,13 +118,6 @@ private: Batch.swap(m_Queue); } - uint32_t Dropped = m_DroppedMessages.exchange(0, std::memory_order_relaxed); - if (Dropped > 0) - { - // We could/should log here, but that could cause a feedback loop which - // would trigger subsequent dropped message warnings - } - if (!m_Connected && !Connect()) { if (m_Stopping) @@ -147,16 +127,21 @@ private: continue; // drop batch — will retry on next batch } + // Build a gathered buffer sequence so the entire batch is written + // in a single socket operation (or as few as the OS needs). + eastl::fixed_vector<asio::const_buffer, 64> Buffers; + Buffers.reserve(Batch.size()); for (auto& Obj : Batch) { - MemoryView View = Obj.GetView(); - asio::error_code Ec; - asio::write(m_Socket, asio::buffer(View.GetData(), View.GetSize()), Ec); - if (Ec) - { - m_Connected = false; - break; // drop remaining messages in batch - } + MemoryView View = Obj.GetView(); + Buffers.emplace_back(View.GetData(), View.GetSize()); + } + + asio::error_code Ec; + asio::write(m_Socket, Buffers, Ec); + if (Ec) + { + m_Connected = false; } } } @@ -191,15 +176,14 @@ private: std::string m_Source; uint32_t m_MaxQueueSize; - // Formatter (protected by RwLock since Log is called from multiple threads) - RwLock m_FormatterLock; - std::unique_ptr<logging::Formatter> m_Formatter; + // Sequence counter — incremented atomically by Log() callers. + // Gaps in the sequence seen by the receiver indicate dropped messages. + std::atomic<uint64_t> m_NextSequence{0}; // Queue shared between Log() callers and IO thread std::mutex m_QueueMutex; std::condition_variable m_QueueCv; std::deque<CbObject> m_Queue; - std::atomic<uint32_t> m_DroppedMessages{0}; bool m_Stopping = false; std::chrono::steady_clock::time_point m_DrainDeadline; |