From 83e815e06c872751a72fbe69d98a8f33910cb20c Mon Sep 17 00:00:00 2001 From: Eric Curtin Date: Fri, 20 Nov 2026 21:25:19 +0000 Subject: [PATCH 1/4] feat(supervisor): relay agent OTLP logs and metrics Closes #5562 Signed-off-by: Eric Curtin --- crates/openshell-supervisor/README.md | 2 +- .../src/otlp_relay/buffer.rs | 102 +++-- .../src/otlp_relay/enrichment.rs | 10 +- .../src/otlp_relay/exporter.rs | 74 ++-- .../src/otlp_relay/mod.rs | 383 ++++++++++++++---- .../src/otlp_relay/receiver.rs | 150 +++---- docs/how-it-works/gateways/configuration.mdx | 8 +- docs/observability/overview.mdx | 2 +- 8 files changed, 518 insertions(+), 213 deletions(-) diff --git a/crates/openshell-supervisor/README.md b/crates/openshell-supervisor/README.md index bddab556c7..201ca2cc96 100644 --- a/crates/openshell-supervisor/README.md +++ b/crates/openshell-supervisor/README.md @@ -132,7 +132,7 @@ Console JSON is installed independently of optional file appenders and uses an I ## OTLP agent trace relay -The `otlp_relay` module forwards the workload's OTLP/HTTP protobuf trace exports to the collector named by `OPENSHELL_OTLP_AGENT_ENDPOINT`, over the transport named by `OPENSHELL_OTLP_AGENT_PROTOCOL` (`grpc` when unset, or `http/protobuf`). Each export carries the collector headers from the launch bundle's `agent_otlp_headers` and, for an `https` collector, verifies it and authenticates with `agent_otlp_tls`; the supervisor's own span and OCSF exporters use the `traces_` and `ocsf_` fields the same way. The gateway sets those variables only when `[openshell.gateway.otlp.agent]` is enabled, so trace export alone leaves the relay inactive. Metrics and logs exports to the relay are acknowledged and discarded. The workload exports to the reserved address `192.0.0.8:4318`; the sandbox broker stages that connection to the supervisor, and the network proxy hands the stream to the relay's HTTP/1.1 receiver through the generic reserved-destination hook instead of evaluating policy. The receiver replaces the `openshell.sandbox.id` and `openshell.telemetry.source=agent` resource attributes, pushes the re-encoded batch into a bounded buffer, and a single export task forwards the encoded batches to the collector with a lazy connection. +The `otlp_relay` module forwards the workload's OTLP/HTTP protobuf trace, log, and metrics exports to the collector named by `OPENSHELL_OTLP_AGENT_ENDPOINT`, over the transport named by `OPENSHELL_OTLP_AGENT_PROTOCOL` (`grpc` when unset, or `http/protobuf`). Each export carries the collector headers from the launch bundle's `agent_otlp_headers` and, for an `https` collector, verifies it and authenticates with `agent_otlp_tls`; the supervisor's own span and OCSF exporters use the `traces_` and `ocsf_` fields the same way. The gateway sets those variables only when `[openshell.gateway.otlp.agent]` is enabled, so trace export alone leaves the relay inactive. The workload exports to the reserved address `192.0.0.8:4318`; the sandbox broker stages that connection to the supervisor, and the network proxy hands the stream to the relay's HTTP/1.1 receiver through the generic reserved-destination hook instead of evaluating policy. The receiver replaces the `openshell.sandbox.id` and `openshell.telemetry.source=agent` resource attributes, pushes the re-encoded batch into the bounded buffer of its signal, and a single export task forwards the encoded batches to the collector with a lazy connection. Limits are fixed: 2 MiB per request body, at most 512 `ResourceSpans` entries, 256 KiB of encoded `Resource` fields, and 8192 resource attributes per request (each of these answers 413), a 10 second header-read timeout, 16 concurrent connections, 32 buffered batches, and a 5 second deadline per export attempt. Only the resources are decoded; spans are copied byte for byte, at most two requests at a time. Worst-case memory attributable to the agent is about 67 MiB of buffered batches, plus 32 MiB of bodies awaiting enrichment across the 16 connections, plus about 12 MiB for the two enrichments in progress, plus about 4 MiB for the batch being exported and its encoded copy. A full buffer answers 503 with `Retry-After`. Without an agent endpoint nothing starts and the proxy refuses the relay address. After the agent exits, `run_sandbox_with_backend` flushes buffered batches for up to 5 seconds before it reports the exit to the gateway, then logs a final summary of rejected and failed counts. Flushes skip the wait while the most recent export failed, and batches still pending when the relay is dropped without a flush count as failed. The supervisor tells the sandbox runtime through `AgentSpec::otlp_relay_active` whether the relay runs, and the runtime injects the generic `OTEL_EXPORTER_OTLP_*` defaults only then. diff --git a/crates/openshell-supervisor/src/otlp_relay/buffer.rs b/crates/openshell-supervisor/src/otlp_relay/buffer.rs index 2512f69d1c..b01e500e59 100644 --- a/crates/openshell-supervisor/src/otlp_relay/buffer.rs +++ b/crates/openshell-supervisor/src/otlp_relay/buffer.rs @@ -1,8 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -//! Bounded buffer of enriched, encoded trace batches between the receiver -//! and the export task. +//! Bounded buffers of enriched, encoded batches between the receiver and the +//! export task, one per signal. //! //! Sending never blocks and never drops silently: a full buffer surfaces as //! [`BufferFull`] so the receiver can answer 503 and the agent SDK retries. @@ -10,6 +10,8 @@ use bytes::Bytes; use tokio::sync::mpsc; +use super::Signal; + /// The buffer has no room for another batch. #[derive(Debug, PartialEq, Eq)] pub enum SendError { @@ -34,62 +36,114 @@ impl std::error::Error for SendError {} /// Not `Clone`: the receiver holds the only sender, so closing the buffer /// at shutdown ends the export task's input. pub struct BatchSender { - tx: mpsc::Sender, + queues: [mpsc::Sender; Signal::ALL.len()], } impl BatchSender { - /// Buffers `batch` without waiting. - pub fn try_send(&self, batch: Bytes) -> Result<(), SendError> { - self.tx.try_send(batch).map_err(|error| match error { - mpsc::error::TrySendError::Full(_) => SendError::BufferFull, - mpsc::error::TrySendError::Closed(_) => SendError::BufferClosed, - }) + /// Buffers `batch` of `signal` without waiting. + pub fn try_send(&self, signal: Signal, batch: Bytes) -> Result<(), SendError> { + self.queues[signal.index()] + .try_send(batch) + .map_err(|error| match error { + mpsc::error::TrySendError::Full(_) => SendError::BufferFull, + mpsc::error::TrySendError::Closed(_) => SendError::BufferClosed, + }) } } /// Consumer side, held by the export task. pub struct BatchReceiver { - rx: mpsc::Receiver, + queues: [mpsc::Receiver; Signal::ALL.len()], } impl BatchReceiver { - /// Next buffered batch in arrival order, or `None` once every sender has - /// been dropped and the buffer is drained. - pub async fn recv(&mut self) -> Option { - self.rx.recv().await + /// Next buffered batch, or `None` once every sender has been dropped and + /// the buffer is drained. Traces go before logs and logs before metrics + /// when several are waiting; arrival order holds within a signal. + pub async fn recv(&mut self) -> Option<(Signal, Bytes)> { + let [traces, logs, metrics] = &mut self.queues; + tokio::select! { + biased; + Some(batch) = traces.recv() => Some((Signal::Traces, batch)), + Some(batch) = logs.recv() => Some((Signal::Logs, batch)), + Some(batch) = metrics.recv() => Some((Signal::Metrics, batch)), + else => None, + } } } -/// Creates a buffer holding at most `capacity` batches. +/// Creates a buffer holding at most `capacity` trace batches and a quarter +/// of that, rounded up, for each of logs and metrics. pub fn new_buffer(capacity: usize) -> (BatchSender, BatchReceiver) { - let (tx, rx) = mpsc::channel(capacity); - (BatchSender { tx }, BatchReceiver { rx }) + let (senders, receivers): (Vec<_>, Vec<_>) = Signal::ALL + .map(|signal| { + let capacity = match signal { + Signal::Traces => capacity, + Signal::Logs | Signal::Metrics => capacity.div_ceil(4), + }; + mpsc::channel(capacity) + }) + .into_iter() + .unzip(); + ( + BatchSender { + queues: senders.try_into().expect("one queue per signal"), + }, + BatchReceiver { + queues: receivers.try_into().expect("one queue per signal"), + }, + ) } #[cfg(test)] mod tests { use super::*; + const T: Signal = Signal::Traces; + #[tokio::test] async fn capacity_is_honoured_and_full_is_reported() { let (tx, mut rx) = new_buffer(32); for i in 0..32u8 { - tx.try_send(Bytes::from(vec![i])).unwrap(); + tx.try_send(T, Bytes::from(vec![i])).unwrap(); } assert_eq!( - tx.try_send(Bytes::from_static(b"x")), + tx.try_send(T, Bytes::from_static(b"x")), Err(SendError::BufferFull) ); - assert_eq!(rx.recv().await.unwrap(), Bytes::from(vec![0u8])); - tx.try_send(Bytes::from_static(b"x")).unwrap(); + assert_eq!(rx.recv().await.unwrap(), (T, Bytes::from(vec![0u8]))); + tx.try_send(T, Bytes::from_static(b"x")).unwrap(); + } + + #[tokio::test] + async fn a_full_signal_does_not_block_the_others() { + let (tx, mut rx) = new_buffer(32); + for _ in 0..8 { + tx.try_send(Signal::Logs, Bytes::from_static(b"l")).unwrap(); + } + assert_eq!( + tx.try_send(Signal::Logs, Bytes::from_static(b"l")), + Err(SendError::BufferFull) + ); + tx.try_send(Signal::Metrics, Bytes::from_static(b"m")) + .unwrap(); + tx.try_send(T, Bytes::from_static(b"t")).unwrap(); + assert_eq!(rx.recv().await.unwrap().0, T); + assert_eq!(rx.recv().await.unwrap().0, Signal::Logs); } #[tokio::test] async fn recv_returns_none_after_the_sender_drops() { let (tx, mut rx) = new_buffer(4); - tx.try_send(Bytes::from_static(b"a")).unwrap(); + tx.try_send(T, Bytes::from_static(b"a")).unwrap(); + tx.try_send(Signal::Metrics, Bytes::from_static(b"b")) + .unwrap(); drop(tx); - assert_eq!(rx.recv().await.unwrap(), Bytes::from_static(b"a")); + assert_eq!(rx.recv().await.unwrap(), (T, Bytes::from_static(b"a"))); + assert_eq!( + rx.recv().await.unwrap(), + (Signal::Metrics, Bytes::from_static(b"b")) + ); assert!(rx.recv().await.is_none()); } @@ -98,7 +152,7 @@ mod tests { let (tx, rx) = new_buffer(4); drop(rx); assert_eq!( - tx.try_send(Bytes::from_static(b"a")), + tx.try_send(T, Bytes::from_static(b"a")), Err(SendError::BufferClosed) ); } diff --git a/crates/openshell-supervisor/src/otlp_relay/enrichment.rs b/crates/openshell-supervisor/src/otlp_relay/enrichment.rs index 7fce2483d2..257a457663 100644 --- a/crates/openshell-supervisor/src/otlp_relay/enrichment.rs +++ b/crates/openshell-supervisor/src/otlp_relay/enrichment.rs @@ -1,7 +1,13 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -//! Resource attribution for relayed agent traces. +//! Resource attribution for relayed agent traces, logs, and metrics. +//! +//! The three export requests share one wire layout for this purpose: the +//! repeated `ResourceSpans`, `ResourceLogs`, or `ResourceMetrics` entries are +//! field 1 of the request and each carries its `Resource` in field 1, so the +//! walk below serves every signal. Names in this module follow the trace +//! schema. //! //! Every forwarded `ResourceSpans` entry carries exactly two supervisor-owned //! resource attributes. Agent-supplied values for those keys are always @@ -113,7 +119,7 @@ pub enum EnrichError { impl std::fmt::Display for EnrichError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::Malformed(error) => write!(f, "malformed ExportTraceServiceRequest: {error}"), + Self::Malformed(error) => write!(f, "malformed OTLP export request: {error}"), Self::TooManyResourceSpans => { write!(f, "more than {MAX_RESOURCE_SPANS} resource_spans entries") } diff --git a/crates/openshell-supervisor/src/otlp_relay/exporter.rs b/crates/openshell-supervisor/src/otlp_relay/exporter.rs index ec29acdfb3..9a34532db3 100644 --- a/crates/openshell-supervisor/src/otlp_relay/exporter.rs +++ b/crates/openshell-supervisor/src/otlp_relay/exporter.rs @@ -24,7 +24,7 @@ use tonic::codec::{Codec, DecodeBuf, Decoder, EncodeBuf, Encoder}; use tonic::transport::{Channel, Endpoint}; use tonic::{GrpcMethod, Status}; -use super::EXPORT_TIMEOUT; +use super::{EXPORT_TIMEOUT, Signal}; /// HTTP/2 PING cadence while an export is in flight. Pings are never sent on /// an idle connection: stock collectors (grpc-go) close connections that @@ -38,9 +38,7 @@ const HTTP2_PING_TIMEOUT: Duration = Duration::from_secs(2); /// that ends a slow export. const CLIENT_TIMEOUT_MARGIN: Duration = Duration::from_secs(1); -const SERVICE: &str = "opentelemetry.proto.collector.trace.v1.TraceService"; const METHOD: &str = "Export"; -const PATH: &str = "/opentelemetry.proto.collector.trace.v1.TraceService/Export"; /// One export attempt failed. The batch is discarded by the caller. #[derive(Debug)] @@ -94,11 +92,12 @@ enum Transport { Grpc(Grpc), Http { client: Box, - uri: http::Uri, + /// Export URI per signal, indexed like [`Signal::ALL`]. + uris: [http::Uri; Signal::ALL.len()], }, } -/// Forwards encoded `ExportTraceServiceRequest` batches to one collector. +/// Forwards encoded OTLP export request batches to one collector. pub struct Exporter { transport: Transport, endpoint: String, @@ -124,8 +123,18 @@ impl Exporter { OtlpHttpClient::new(tls, EXPORT_TIMEOUT + CLIENT_TIMEOUT_MARGIN) .map_err(EndpointError::Setup)?, ), - uri: openshell_otel::signal_url(endpoint, "v1/traces") - .map_err(EndpointError::Http)?, + uris: Signal::ALL + .into_iter() + .map(|signal| { + openshell_otel::signal_url( + endpoint, + signal.http_path().trim_start_matches('/'), + ) + }) + .collect::, _>>() + .map_err(EndpointError::Http)? + .try_into() + .expect("one URI per signal"), }, }; Ok(Self { @@ -141,13 +150,15 @@ impl Exporter { &self.endpoint } - /// Sends one encoded batch, bounded by [`EXPORT_TIMEOUT`]. - pub async fn export(&self, batch: Bytes) -> Result<(), ExportError> { + /// Sends one encoded batch of `signal`, bounded by [`EXPORT_TIMEOUT`]. + pub async fn export(&self, signal: Signal, batch: Bytes) -> Result<(), ExportError> { let send = async { match &self.transport { - Transport::Grpc(client) => export_grpc(client.clone(), &self.headers, batch).await, - Transport::Http { client, uri } => { - export_http(client, uri, &self.headers, batch).await + Transport::Grpc(client) => { + export_grpc(client.clone(), &self.headers, signal, batch).await + } + Transport::Http { client, uris } => { + export_http(client, &uris[signal.index()], &self.headers, batch).await } } }; @@ -191,6 +202,7 @@ fn grpc_channel( async fn export_grpc( mut client: Grpc, headers: &http::HeaderMap, + signal: Signal, batch: Bytes, ) -> Result<(), ExportError> { client.ready().await.map_err(|error| { @@ -200,11 +212,14 @@ async fn export_grpc( })?; let mut request = tonic::Request::new(batch); *request.metadata_mut() = tonic::metadata::MetadataMap::from_headers(headers.clone()); + let service = signal.grpc_service(); request .extensions_mut() - .insert(GrpcMethod::new(SERVICE, METHOD)); + .insert(GrpcMethod::new(service, METHOD)); + let path = PathAndQuery::try_from(format!("/{service}/{METHOD}")) + .expect("service and method names are valid path characters"); client - .unary(request, PathAndQuery::from_static(PATH), PassthroughCodec) + .unary(request, path, PassthroughCodec) .await .map(|_| ()) .map_err(ExportError::Status) @@ -247,7 +262,9 @@ fn error_chain(error: &dyn std::error::Error) -> String { } /// gRPC codec that writes a pre-encoded request body as-is and decodes the -/// collector's `ExportTraceServiceResponse`. +/// collector's response. The logs and metrics responses share the wire layout +/// of `ExportTraceServiceResponse` (a `partial_success` message in field 1), +/// so one decoder serves every signal. struct PassthroughCodec; impl Codec for PassthroughCodec { @@ -382,7 +399,7 @@ mod tests { let batch = Bytes::from(encoded_request("over-http", &[])); exporter - .export(batch.clone()) + .export(Signal::Traces, batch.clone()) .await .expect("export succeeds"); let export = collector.next_export().await; @@ -408,7 +425,7 @@ mod tests { ) .unwrap(); let error = exporter - .export(Bytes::from(encoded_request("s", &[]))) + .export(Signal::Traces, Bytes::from(encoded_request("s", &[]))) .await .expect_err("403 fails"); assert!( @@ -432,7 +449,7 @@ mod tests { let started = Instant::now(); let error = exporter - .export(Bytes::from(encoded_request("s", &[]))) + .export(Signal::Traces, Bytes::from(encoded_request("s", &[]))) .await .expect_err("closed port fails"); assert!(matches!(error, ExportError::Http(_)), "{error}"); @@ -463,7 +480,7 @@ mod tests { let started = Instant::now(); let error = exporter - .export(Bytes::from(encoded_request("s", &[]))) + .export(Signal::Traces, Bytes::from(encoded_request("s", &[]))) .await .expect_err("silent collector times out"); assert!(matches!(error, ExportError::Timeout), "{error}"); @@ -473,7 +490,7 @@ mod tests { "elapsed {elapsed:?}" ); exporter - .export(Bytes::from(encoded_request("s", &[]))) + .export(Signal::Traces, Bytes::from(encoded_request("s", &[]))) .await .expect("the next export reconnects"); collector.abort(); @@ -518,7 +535,7 @@ mod tests { let grpc = OtlpTestServer::start().await; Exporter::new(grpc.endpoint(), OtlpProtocol::Grpc, headers(), None) .unwrap() - .export(batch()) + .export(Signal::Traces, batch()) .await .expect("gRPC export succeeds"); grpc.wait_for_export().await; @@ -527,7 +544,7 @@ mod tests { let mut http = OtlpHttpTestServer::start().await; Exporter::new(http.endpoint(), OtlpProtocol::HttpProtobuf, headers(), None) .unwrap() - .export(batch()) + .export(Signal::Traces, batch()) .await .expect("HTTP export succeeds"); assert_eq!( @@ -559,7 +576,7 @@ mod tests { Some(&tls), ) .unwrap() - .export(batch()) + .export(Signal::Traces, batch()) .await .expect("gRPC export over mutual TLS succeeds"); assert_eq!(grpc.shutdown().await.spans.len(), 1); @@ -572,7 +589,7 @@ mod tests { Some(&tls), ) .unwrap() - .export(batch()) + .export(Signal::Traces, batch()) .await .expect("HTTP export over mutual TLS succeeds"); assert_eq!(http.next_export().await.path, "/v1/traces"); @@ -593,7 +610,10 @@ mod tests { &[("service.name", "unit-agent"), ("custom", "kept")], )); - exporter.export(batch).await.expect("export succeeds"); + exporter + .export(Signal::Traces, batch) + .await + .expect("export succeeds"); collector.wait_for_export().await; let received = collector.shutdown().await; @@ -622,7 +642,7 @@ mod tests { let started = Instant::now(); let error = exporter - .export(Bytes::from(encoded_request("s", &[]))) + .export(Signal::Traces, Bytes::from(encoded_request("s", &[]))) .await .expect_err("closed port fails"); assert!(matches!(error, ExportError::Status(_)), "{error}"); @@ -646,7 +666,7 @@ mod tests { .unwrap(); let started = Instant::now(); let error = exporter - .export(Bytes::from(encoded_request("s", &[]))) + .export(Signal::Traces, Bytes::from(encoded_request("s", &[]))) .await .expect_err("silent collector fails"); assert!(matches!(error, ExportError::Status(_)), "{error}"); diff --git a/crates/openshell-supervisor/src/otlp_relay/mod.rs b/crates/openshell-supervisor/src/otlp_relay/mod.rs index 4b45cda49c..4ce980e77b 100644 --- a/crates/openshell-supervisor/src/otlp_relay/mod.rs +++ b/crates/openshell-supervisor/src/otlp_relay/mod.rs @@ -1,9 +1,9 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -//! Supervisor-direct OTLP trace relay. +//! Supervisor-direct OTLP relay for agent traces, logs, and metrics. //! -//! A sandboxed agent exports OTLP/HTTP protobuf traces to the reserved +//! A sandboxed agent exports OTLP/HTTP protobuf to the reserved //! address [`openshell_core::sandbox_env::OTLP_RELAY_ADDR`]. The sandbox //! broker stages that connection to the supervisor, the network proxy hands //! the stream to [`receiver::OtlpConnectionServer`], and the accepted batch @@ -37,13 +37,56 @@ use self::buffer::new_buffer; use self::exporter::Exporter; use self::receiver::{OtlpConnectionServer, ReceiverHandle}; +/// An OTLP signal the relay forwards. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Signal { + Traces, + Logs, + Metrics, +} + +impl Signal { + pub const ALL: [Self; 3] = [Self::Traces, Self::Logs, Self::Metrics]; + + /// The signal an OTLP/HTTP export path carries. + pub fn from_path(path: &str) -> Option { + Self::ALL + .into_iter() + .find(|signal| signal.http_path() == path) + } + + /// OTLP/HTTP export path, also the suffix under the collector endpoint. + pub const fn http_path(self) -> &'static str { + match self { + Self::Traces => "/v1/traces", + Self::Logs => "/v1/logs", + Self::Metrics => "/v1/metrics", + } + } + + /// Fully qualified name of the gRPC collector service with the `Export` + /// method. + pub const fn grpc_service(self) -> &'static str { + match self { + Self::Traces => "opentelemetry.proto.collector.trace.v1.TraceService", + Self::Logs => "opentelemetry.proto.collector.logs.v1.LogsService", + Self::Metrics => "opentelemetry.proto.collector.metrics.v1.MetricsService", + } + } + + const fn index(self) -> usize { + self as usize + } +} + /// Maximum accepted request body, in wire bytes. pub const MAX_BODY_BYTES: usize = 2 * 1024 * 1024; /// Maximum size of a batch after attribution, derived from the per-entry /// growth bound and the entry cap. /// /// Relay memory attributable to the agent is bounded by three parts: the -/// export buffer, [`BUFFER_CAPACITY`] batches of this size (about 67 MiB); +/// export buffers, [`BUFFER_CAPACITY`] batches of this size for traces and a +/// quarter of that for each of logs and metrics (about 100 MiB in all); /// bodies read but not yet enriched, [`MAX_CONCURRENT_CONNECTIONS`] times /// [`MAX_BODY_BYTES`] (32 MiB); and the working set of the /// [`ENRICHMENT_CONCURRENCY`] enrichments in progress, each about twice the @@ -66,7 +109,9 @@ pub const MAX_CONCURRENT_CONNECTIONS: usize = 16; /// body plus the decoded resources, so two slots bound that transient /// regardless of how many connections hold a body. pub const ENRICHMENT_CONCURRENCY: usize = 2; -/// Number of enriched batches held between receipt and export. +/// Number of enriched trace batches held between receipt and export. Logs +/// and metrics each get a quarter of it in a buffer of their own, so a chatty +/// signal cannot crowd out the others. pub const BUFFER_CAPACITY: usize = 32; /// Deadline for one export attempt to the collector. pub const EXPORT_TIMEOUT: Duration = Duration::from_secs(5); @@ -79,7 +124,7 @@ pub const SUMMARY_INTERVAL: Duration = Duration::from_secs(30); /// `Retry-After` value sent with a 503 back-pressure response. pub const RETRY_AFTER_SECS: u64 = 1; -/// Point-in-time copy of the relay counters. +/// Point-in-time copy of the relay counters, summed over all signals. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct CounterSnapshot { /// Batches delivered to the collector. @@ -90,36 +135,64 @@ pub struct CounterSnapshot { pub export_failures: u64, } -/// Cumulative relay counters shared by the receiver, exporter, and summary -/// task. Counts are monotonic for the supervisor's lifetime. #[derive(Debug, Default)] -pub struct RelayCounters { +struct SignalCounts { accepted: AtomicU64, exported: AtomicU64, rejected: AtomicU64, export_failures: AtomicU64, - /// Metrics and logs exports acknowledged and dropped, since the relay - /// forwards traces only. - discarded_signals: AtomicU64, +} + +impl SignalCounts { + fn snapshot(&self) -> CounterSnapshot { + CounterSnapshot { + exported: self.exported.load(Ordering::Relaxed), + rejected: self.rejected.load(Ordering::Relaxed), + export_failures: self.export_failures.load(Ordering::Relaxed), + } + } + + /// Accepted batches not yet exported or failed: buffered plus in flight. + fn pending(&self) -> u64 { + let CounterSnapshot { + exported, + export_failures, + .. + } = self.snapshot(); + self.accepted + .load(Ordering::Relaxed) + .saturating_sub(exported) + .saturating_sub(export_failures) + } +} + +/// Cumulative relay counters shared by the receiver, exporter, and summary +/// task. Counts are monotonic for the supervisor's lifetime. +#[derive(Debug, Default)] +pub struct RelayCounters { + signals: [SignalCounts; Signal::ALL.len()], /// Whether the most recent export attempt failed. Cleared by the next /// success; flushes skip waiting while it is set. last_export_failed: AtomicBool, first_rejection_logged: AtomicBool, - first_discard_logged: AtomicBool, first_failure_logged: AtomicBool, final_summary_logged: AtomicBool, } impl RelayCounters { + fn counts(&self, signal: Signal) -> &SignalCounts { + &self.signals[signal.index()] + } + /// Records one batch accepted into the buffer. - pub fn record_accepted(&self) { - self.accepted.fetch_add(1, Ordering::Relaxed); + pub fn record_accepted(&self, signal: Signal) { + self.counts(signal).accepted.fetch_add(1, Ordering::Relaxed); } /// Records one export request refused with 503 because the buffer was /// full. Warns on the first occurrence only. - pub fn record_rejection(&self) { - self.rejected.fetch_add(1, Ordering::Relaxed); + pub fn record_rejection(&self, signal: Signal) { + self.counts(signal).rejected.fetch_add(1, Ordering::Relaxed); if !self.first_rejection_logged.swap(true, Ordering::Relaxed) { warn!( buffer_capacity = BUFFER_CAPACITY, @@ -128,28 +201,17 @@ impl RelayCounters { } } - /// Records one metrics or logs export that was acknowledged and dropped. - /// Logs the first occurrence only, since an agent SDK sends one per - /// export interval for as long as it runs. - pub fn record_discarded_signal(&self, signal: &'static str) { - self.discarded_signals.fetch_add(1, Ordering::Relaxed); - if !self.first_discard_logged.swap(true, Ordering::Relaxed) { - info!( - signal, - "OTLP relay discarded an agent export: the relay forwards traces only" - ); - } - } - - /// Metrics and logs exports discarded so far. - pub fn discarded_signals(&self) -> u64 { - self.discarded_signals.load(Ordering::Relaxed) - } - /// Records one export attempt that failed or timed out. Warns on the /// first occurrence only. - pub fn record_export_failure(&self, endpoint: &str, error: &dyn std::fmt::Display) { - self.export_failures.fetch_add(1, Ordering::Relaxed); + pub fn record_export_failure( + &self, + signal: Signal, + endpoint: &str, + error: &dyn std::fmt::Display, + ) { + self.counts(signal) + .export_failures + .fetch_add(1, Ordering::Relaxed); self.last_export_failed.store(true, Ordering::Relaxed); if !self.first_failure_logged.swap(true, Ordering::Relaxed) { warn!(endpoint, %error, "OTLP relay export to collector failed"); @@ -157,8 +219,8 @@ impl RelayCounters { } /// Records one batch delivered to the collector. - pub fn record_export_success(&self) { - self.exported.fetch_add(1, Ordering::Relaxed); + pub fn record_export_success(&self, signal: Signal) { + self.counts(signal).exported.fetch_add(1, Ordering::Relaxed); self.last_export_failed.store(false, Ordering::Relaxed); } @@ -167,26 +229,38 @@ impl RelayCounters { self.last_export_failed.load(Ordering::Relaxed) } - /// Current counts. + /// Current counts over all signals. pub fn snapshot(&self) -> CounterSnapshot { - CounterSnapshot { - exported: self.exported.load(Ordering::Relaxed), - rejected: self.rejected.load(Ordering::Relaxed), - export_failures: self.export_failures.load(Ordering::Relaxed), - } + self.signals.iter().map(SignalCounts::snapshot).fold( + CounterSnapshot { + exported: 0, + rejected: 0, + export_failures: 0, + }, + |total, counts| CounterSnapshot { + exported: total.exported + counts.exported, + rejected: total.rejected + counts.rejected, + export_failures: total.export_failures + counts.export_failures, + }, + ) } /// Accepted batches not yet exported or failed: buffered plus in flight. fn pending(&self) -> u64 { - let CounterSnapshot { - exported, - export_failures, - .. - } = self.snapshot(); - self.accepted - .load(Ordering::Relaxed) - .saturating_sub(exported) - .saturating_sub(export_failures) + self.signals.iter().map(SignalCounts::pending).sum() + } + + /// Counts every pending batch as an export failure and returns how many + /// there were. + fn discard_pending(&self) -> u64 { + self.signals + .iter() + .map(|counts| { + let pending = counts.pending(); + counts.export_failures.fetch_add(pending, Ordering::Relaxed); + pending + }) + .sum() } fn log_summary(&self) { @@ -195,11 +269,20 @@ impl RelayCounters { rejected, export_failures, } = self.snapshot(); + let [traces, logs, metrics] = Signal::ALL.map(|signal| self.counts(signal).snapshot()); info!( exported, rejected, export_failures, - discarded_signals = self.discarded_signals(), + traces_exported = traces.exported, + traces_rejected = traces.rejected, + traces_export_failures = traces.export_failures, + logs_exported = logs.exported, + logs_rejected = logs.rejected, + logs_export_failures = logs.export_failures, + metrics_exported = metrics.exported, + metrics_rejected = metrics.rejected, + metrics_export_failures = metrics.export_failures, "OTLP relay summary" ); } @@ -287,11 +370,8 @@ impl Drop for OtlpRelay { // A lifecycle path that drops the relay without `shutdown` discards // whatever is still buffered or in flight; count it so the final // summary reports the loss. After `shutdown` nothing is pending. - let discarded = self.counters.pending(); + let discarded = self.counters.discard_pending(); if discarded > 0 { - self.counters - .export_failures - .fetch_add(discarded, Ordering::Relaxed); warn!( discarded, "OTLP relay stopped without a flush; discarding buffered batches" @@ -465,10 +545,12 @@ fn assemble( if let Some(mut gate) = export_gate { let _ = gate.wait_for(|open| *open).await; } - while let Some(batch) = buffer_rx.recv().await { - match exporter.export(batch).await { - Ok(()) => counters.record_export_success(), - Err(error) => counters.record_export_failure(exporter.endpoint(), &error), + while let Some((signal, batch)) = buffer_rx.recv().await { + match exporter.export(signal, batch).await { + Ok(()) => counters.record_export_success(signal), + Err(error) => { + counters.record_export_failure(signal, exporter.endpoint(), &error); + } } } } @@ -574,11 +656,8 @@ impl OtlpRelay { if self.counters.last_export_failed() { self.export_task.abort(); let _ = (&mut self.export_task).await; - let discarded = self.counters.pending(); + let discarded = self.counters.discard_pending(); if discarded > 0 { - self.counters - .export_failures - .fetch_add(discarded, Ordering::Relaxed); warn!( discarded, "OTLP relay flush skipped: the last export to the collector failed; discarding buffered batches" @@ -599,10 +678,7 @@ impl OtlpRelay { ); } Ok(Err(join_error)) => { - let discarded = self.counters.pending(); - self.counters - .export_failures - .fetch_add(discarded, Ordering::Relaxed); + let discarded = self.counters.discard_pending(); warn!( %join_error, discarded, @@ -615,10 +691,7 @@ impl OtlpRelay { // discarded. self.export_task.abort(); let _ = (&mut self.export_task).await; - let discarded = self.counters.pending(); - self.counters - .export_failures - .fetch_add(discarded, Ordering::Relaxed); + let discarded = self.counters.discard_pending(); warn!( discarded, "OTLP relay flush deadline exceeded; discarding buffered batches" @@ -832,6 +905,144 @@ mod tests { })); } + fn export_requests() -> ( + opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest, + opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest, + ) { + use openshell_otel_test_support::relay::string_attribute; + use opentelemetry_proto::tonic::common::v1::{AnyValue, any_value}; + use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs}; + use opentelemetry_proto::tonic::metrics::v1::ResourceMetrics; + use opentelemetry_proto::tonic::resource::v1::Resource; + + let resource = || { + Some(Resource { + attributes: vec![ + string_attribute("service.name", "unit-agent"), + string_attribute(SANDBOX_ID_KEY, "evil"), + ], + ..Default::default() + }) + }; + let logs = opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + resource: resource(), + scope_logs: vec![ScopeLogs { + log_records: vec![LogRecord { + body: Some(AnyValue { + value: Some(any_value::Value::StringValue("agent-log".into())), + }), + ..Default::default() + }], + ..Default::default() + }], + ..Default::default() + }], + }; + let metrics = + opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest { + resource_metrics: vec![ResourceMetrics { + resource: resource(), + ..Default::default() + }], + }; + (logs, metrics) + } + + #[tokio::test] + async fn logs_and_metrics_reach_a_grpc_collector_with_attribution() { + let collector = OtlpTestServer::start().await; + let (relay, reserved) = start(OtlpRelayConfig { + endpoint: collector.endpoint().to_string(), + protocol: OtlpProtocol::Grpc, + headers: None, + tls: None, + sandbox_id: "sb-test".into(), + }) + .unwrap(); + let (mut client, boundary) = tokio::io::duplex(64 * 1024); + tokio::spawn(reserved.handler.serve(Box::new(boundary)).unwrap()); + + let (logs, metrics) = export_requests(); + for (path, body) in [ + ("/v1/logs", logs.encode_to_vec()), + ("/v1/metrics", metrics.encode_to_vec()), + ] { + client + .write_all(&request("POST", path, PROTOBUF, &body)) + .await + .unwrap(); + assert_eq!(read_head(&mut client).await.status, 200, "{path}"); + } + + wait_until(Duration::from_secs(5), || { + let received = collector.received(); + !received.log_bodies.is_empty() && !received.metric_exports.is_empty() + }) + .await; + let received = collector.shutdown().await; + assert_eq!(received.log_bodies, ["agent-log"]); + let resource = received.metric_exports[0].resource_metrics[0] + .resource + .as_ref() + .unwrap(); + assert!(resource.attributes.iter().any(|attribute| { + attribute.key == SANDBOX_ID_KEY + && attribute + .value + .as_ref() + .and_then(|value| value.value.as_ref()) + == Some( + &opentelemetry_proto::tonic::common::v1::any_value::Value::StringValue( + "sb-test".into(), + ), + ) + })); + assert!( + received.duplicate_resource_keys.is_empty(), + "spoofed attribution keys were appended to, not replaced: {:?}", + received.duplicate_resource_keys + ); + assert_eq!(relay.counters.snapshot().exported, 2); + } + + #[tokio::test] + async fn logs_and_metrics_are_posted_to_their_paths_on_an_http_collector() { + let mut collector = OtlpHttpTestServer::start().await; + let (_relay, reserved) = start(OtlpRelayConfig { + endpoint: collector.endpoint().to_string(), + protocol: OtlpProtocol::HttpProtobuf, + headers: None, + tls: None, + sandbox_id: "sb-http".into(), + }) + .unwrap(); + let (mut client, boundary) = tokio::io::duplex(64 * 1024); + tokio::spawn(reserved.handler.serve(Box::new(boundary)).unwrap()); + + let (logs, metrics) = export_requests(); + for (path, body) in [ + ("/v1/metrics", metrics.encode_to_vec()), + ("/v1/logs", logs.encode_to_vec()), + ] { + client + .write_all(&request("POST", path, PROTOBUF, &body)) + .await + .unwrap(); + assert_eq!(read_head(&mut client).await.status, 200, "{path}"); + let export = collector.next_export().await; + assert_eq!(export.path, path); + assert_eq!(export.headers[http::header::CONTENT_TYPE], PROTOBUF); + assert!( + export + .body + .windows(b"sb-http".len()) + .any(|window| window == b"sb-http"), + "{path} carries the sandbox id" + ); + } + } + #[tokio::test] async fn http_post_over_duplex_reaches_collector() { let collector = OtlpTestServer::start().await; @@ -1151,9 +1362,11 @@ mod tests { for span in ["one", "two"] { assert_eq!(post(&relay, span).await, 200); } - relay - .counters - .record_export_failure(&collector.endpoint, &"collector down"); + relay.counters.record_export_failure( + Signal::Traces, + &collector.endpoint, + &"collector down", + ); let counters = Arc::clone(&relay.counters); assert_eq!(counters.pending(), 1); @@ -1186,9 +1399,9 @@ mod tests { #[tokio::test] async fn a_successful_export_clears_the_failure_flag() { let counters = RelayCounters::default(); - counters.record_export_failure("http://collector:4317", &"boom"); + counters.record_export_failure(Signal::Traces, "http://collector:4317", &"boom"); assert!(counters.last_export_failed()); - counters.record_export_success(); + counters.record_export_success(Signal::Traces); assert!(!counters.last_export_failed()); } @@ -1198,7 +1411,7 @@ mod tests { let _guard = logs.install(); let collector = OtlpTestServer::start().await; let (relay, _reserved, _gate) = gated(collector.endpoint()); - relay.counters.record_rejection(); + relay.counters.record_rejection(Signal::Traces); // An early-exit lifecycle path drops the relay without `shutdown`. drop(relay); assert_eq!(logs.count(tracing::Level::INFO, "OTLP relay summary"), 1); @@ -1242,7 +1455,7 @@ mod tests { let _guard = logs.install(); let counters = RelayCounters::default(); for _ in 0..10 { - counters.record_rejection(); + counters.record_rejection(Signal::Traces); } assert_eq!( logs.count( @@ -1260,7 +1473,7 @@ mod tests { let _guard = logs.install(); let counters = RelayCounters::default(); for _ in 0..3 { - counters.record_export_failure("http://collector:4317", &"boom"); + counters.record_export_failure(Signal::Traces, "http://collector:4317", &"boom"); } assert_eq!( logs.count( @@ -1284,7 +1497,7 @@ mod tests { tokio::task::yield_now().await; assert_eq!(summaries(), 0, "no summary while nothing was rejected"); - counters.record_rejection(); + counters.record_rejection(Signal::Traces); tokio::time::advance(SUMMARY_INTERVAL).await; tokio::task::yield_now().await; assert_eq!(summaries(), 1); @@ -1296,7 +1509,7 @@ mod tests { tokio::task::yield_now().await; assert_eq!(summaries(), 1, "unchanged counts emit no summary"); - counters.record_export_failure("http://collector:4317", &"boom"); + counters.record_export_failure(Signal::Traces, "http://collector:4317", &"boom"); tokio::time::advance(SUMMARY_INTERVAL).await; tokio::task::yield_now().await; assert_eq!(summaries(), 2); @@ -1475,7 +1688,7 @@ mod tests { let _guard = logs.install(); let collector = OtlpTestServer::start().await; let (relay, _reserved, gate) = gated(collector.endpoint()); - relay.counters.record_rejection(); + relay.counters.record_rejection(Signal::Traces); gate.send_replace(true); relay.shutdown(FLUSH_TIMEOUT).await; assert_eq!(logs.count(tracing::Level::INFO, "OTLP relay summary"), 1); diff --git a/crates/openshell-supervisor/src/otlp_relay/receiver.rs b/crates/openshell-supervisor/src/otlp_relay/receiver.rs index ea664698db..75a09abe92 100644 --- a/crates/openshell-supervisor/src/otlp_relay/receiver.rs +++ b/crates/openshell-supervisor/src/otlp_relay/receiver.rs @@ -7,8 +7,8 @@ //! broker stages that connect for the supervisor, whose proxy hands the //! resulting duplex stream to [`OtlpConnectionServer::serve`] instead of //! dialing upstream. The server speaks HTTP/1.1 on that stream and accepts -//! `POST /v1/traces` with an uncompressed protobuf body. No socket is ever -//! bound. +//! `POST /v1/traces`, `/v1/logs`, and `/v1/metrics` with an uncompressed +//! protobuf body. No socket is ever bound. use std::convert::Infallible; use std::sync::atomic::{AtomicBool, Ordering}; @@ -34,7 +34,7 @@ use tonic_types::Status as RpcStatus; use super::{ BODY_READ_TIMEOUT, ENRICHMENT_CONCURRENCY, HEADER_READ_TIMEOUT, MAX_BODY_BYTES, MAX_CONCURRENT_CONNECTIONS, MAX_ENRICHED_BYTES, RECEIVER_SHUTDOWN_TIMEOUT, RETRY_AFTER_SECS, - RelayCounters, enrichment, + RelayCounters, Signal, enrichment, }; /// Reservation for one relay connection. @@ -181,29 +181,16 @@ impl OtlpConnectionServer { &self, request: Request, ) -> Result>, Infallible> { - // The relay forwards traces only. Agents whose SDK also exports - // metrics or logs to the generic endpoint get an OTLP success, so they - // do not retry forever, and the body is drained without being kept. - if request.method() == Method::POST - && let Some(signal) = discarded_signal(request.uri().path()) - { - // A body that is not delivered in time is abandoned; hyper closes - // the connection because the request was not consumed. - let _ = tokio::time::timeout(BODY_READ_TIMEOUT, drain_body(request.into_body())).await; - self.counters.record_discarded_signal(signal); - return Ok(Response::builder() - .status(StatusCode::OK) - .header(CONTENT_TYPE, "application/x-protobuf") - .body(Full::new(Bytes::new())) - .expect("static response builds")); - } - if request.method() != Method::POST || request.uri().path() != "/v1/traces" { + let Some(signal) = (request.method() == Method::POST) + .then(|| Signal::from_path(request.uri().path())) + .flatten() + else { return Ok(rejected( StatusCode::NOT_FOUND, "not found", - "not found; the relay serves POST /v1/traces only", + "not found; the relay serves POST /v1/traces, /v1/logs and /v1/metrics only", )); - } + }; // `identity` declares an uncompressed body; every other coding is // refused rather than decoded. let compressed = request @@ -323,10 +310,12 @@ impl OtlpConnectionServer { let sent = lock(&self.buffer_tx) .as_ref() - .map_or(Err(SendError::BufferClosed), |tx| tx.try_send(enriched)); + .map_or(Err(SendError::BufferClosed), |tx| { + tx.try_send(signal, enriched) + }); match sent { Ok(()) => { - self.counters.record_accepted(); + self.counters.record_accepted(signal); Ok(Response::builder() .status(StatusCode::OK) .header(CONTENT_TYPE, "application/x-protobuf") @@ -334,7 +323,7 @@ impl OtlpConnectionServer { .expect("static response builds")) } Err(SendError::BufferFull) => { - self.counters.record_rejection(); + self.counters.record_rejection(signal); Ok(unavailable( "relay buffer is full; retry after the Retry-After interval", )) @@ -358,30 +347,6 @@ enum BodyRead { Failed(hyper::Error), } -/// The OTLP signal a path exports when the relay accepts and discards it. -fn discarded_signal(path: &str) -> Option<&'static str> { - match path { - "/v1/metrics" => Some("metrics"), - "/v1/logs" => Some("logs"), - _ => None, - } -} - -/// Reads and drops a discarded export body, up to [`OVERSIZE_DRAIN_CAP`], so -/// the response is delivered on a connection the client has finished writing -/// to. Nothing is buffered. -async fn drain_body(mut body: Incoming) { - let mut total = 0usize; - while let Some(Ok(frame)) = body.frame().await { - if let Some(data) = frame.data_ref() { - total += data.len(); - if total > OVERSIZE_DRAIN_CAP { - break; - } - } - } -} - /// Reads the body up to [`MAX_BODY_BYTES`]. Once the limit is crossed, or /// when the declared length already exceeds it, the rest is discarded up /// to [`OVERSIZE_DRAIN_CAP`] so the response can be delivered on a @@ -676,7 +641,7 @@ mod tests { assert_eq!(head.status, 200); assert_eq!(head.header("content-type"), Some(PROTOBUF)); - let buffered = rx.recv().await.expect("one batch buffered"); + let buffered = rx.recv().await.expect("one batch buffered").1; let attributes = resource_attributes(&buffered); assert!(attributes.contains(&("service.name".to_string(), "unit-agent".to_string()))); assert!(attributes.contains(&( @@ -702,29 +667,76 @@ mod tests { } #[tokio::test] - async fn metrics_and_logs_are_acknowledged_and_discarded() { + async fn logs_and_metrics_are_enriched_and_buffered() { + use openshell_otel_test_support::relay::string_attribute; + use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest; + use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest; + use opentelemetry_proto::tonic::logs::v1::ResourceLogs; + use opentelemetry_proto::tonic::metrics::v1::ResourceMetrics; + use opentelemetry_proto::tonic::resource::v1::Resource; + + let resource = || { + Some(Resource { + attributes: vec![ + string_attribute("service.name", "unit-agent"), + string_attribute(enrichment::SANDBOX_ID_KEY, "spoofed"), + ], + ..Default::default() + }) + }; + let logs = ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + resource: resource(), + ..Default::default() + }], + } + .encode_to_vec(); + let metrics = ExportMetricsServiceRequest { + resource_metrics: vec![ResourceMetrics { + resource: resource(), + ..Default::default() + }], + } + .encode_to_vec(); + let (server, _handle, mut rx) = start(BUFFER_CAPACITY); let mut client = connect(&server); - for path in ["/v1/metrics", "/v1/logs"] { - let head = send(&mut client, &request("POST", path, PROTOBUF, &[1, 2, 3])).await; + for (path, body) in [("/v1/logs", &logs), ("/v1/metrics", &metrics)] { + let head = send(&mut client, &request("POST", path, PROTOBUF, body)).await; assert_eq!(head.status, 200, "{path}"); assert_eq!(head.header("content-type"), Some(PROTOBUF)); } - // The same connection still serves a trace export afterwards, so the - // discarded bodies were consumed. - let head = send( - &mut client, - &request("POST", "/v1/traces", PROTOBUF, &body()), - ) - .await; - assert_eq!(head.status, 200); - assert!(rx.recv().await.is_some(), "the trace batch is buffered"); + + let attributes = |resource: Option| { + let mut attributes = resource + .expect("resource present") + .attributes + .into_iter() + .map(|attribute| attribute.key) + .collect::>(); + attributes.sort(); + attributes + }; + let expected = vec![ + enrichment::SANDBOX_ID_KEY.to_string(), + enrichment::SOURCE_KEY.to_string(), + "service.name".to_string(), + ]; + let (signal, batch) = rx.recv().await.expect("logs buffered"); + assert_eq!(signal, Signal::Logs); + let decoded = ExportLogsServiceRequest::decode(batch).unwrap(); + assert_eq!( + attributes(decoded.resource_logs[0].resource.clone()), + expected + ); + let (signal, batch) = rx.recv().await.expect("metrics buffered"); + assert_eq!(signal, Signal::Metrics); + let decoded = ExportMetricsServiceRequest::decode(batch).unwrap(); assert_eq!( - server.counters.accepted.load(Ordering::Relaxed), - 1, - "metrics and logs are not buffered" + attributes(decoded.resource_metrics[0].resource.clone()), + expected ); - assert_eq!(server.counters.discarded_signals(), 2); + assert_eq!(server.counters.pending(), 2); } #[tokio::test] @@ -876,7 +888,7 @@ mod tests { ) .await; assert_eq!(head.status, 200); - let buffered = rx.recv().await.expect("the valid batch is buffered"); + let buffered = rx.recv().await.expect("the valid batch is buffered").1; let attributes = resource_attributes(&buffered); assert!(attributes.contains(&("service.name".to_string(), "unit-agent".to_string()))); let rejections = server.counters.snapshot().rejected; @@ -1154,8 +1166,8 @@ mod tests { let first_head = read_head(&mut first).await; assert_eq!(first_head.status, 200); - let a = resource_attributes(&rx.recv().await.unwrap()); - let b = resource_attributes(&rx.recv().await.unwrap()); + let a = resource_attributes(&rx.recv().await.unwrap().1); + let b = resource_attributes(&rx.recv().await.unwrap().1); let id = |attrs: &Vec<(String, String)>| { attrs .iter() diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index 274df1f747..4b54e95a6c 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -1107,7 +1107,7 @@ Metrics include `openshell_ocsf_otlp_queued_total`, `openshell_ocsf_otlp_exporte ### Agent trace relay -Set `enabled = true` in `[openshell.gateway.otlp.agent]` to have each sandbox forward the workload's own traces. It defaults to `false`, so trace export alone never changes the workload environment. Traces go to the table's collector, or to the `[openshell.gateway.otlp]` collector when it has no `endpoint`, and that collector must be reachable from sandboxes. Use `protocol = "http/protobuf"` for trace backends that accept only OTLP/HTTP, and `headers` for the ones that need them. For example, MLflow accepts traces directly when each request names an experiment: +Set `enabled = true` in `[openshell.gateway.otlp.agent]` to have each sandbox forward the workload's own traces, logs, and metrics. It defaults to `false`, so trace export alone never changes the workload environment. They go to the table's collector, or to the `[openshell.gateway.otlp]` collector when it has no `endpoint`, and that collector must be reachable from sandboxes. Use `protocol = "http/protobuf"` for trace backends that accept only OTLP/HTTP, and `headers` for the ones that need them. For example, MLflow accepts traces directly when each request names an experiment: ```toml [openshell.gateway.otlp.agent] @@ -1117,11 +1117,11 @@ protocol = "http/protobuf" headers = { x-mlflow-experiment-id = "0" } ``` -While the relay is active, the sandbox runtime sets `OTEL_EXPORTER_OTLP_ENDPOINT=http://192.0.0.8:4318` and `OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf` in every workload process, and sets `OTEL_EXPORTER_OTLP_COMPRESSION` and `OTEL_EXPORTER_OTLP_TRACES_COMPRESSION` to `none`, so a standard OpenTelemetry SDK exports without configuration. These are lowest-precedence defaults. They are not set when the sandbox creation request or an environment passed to `openshell sandbox exec` names `OTEL_EXPORTER_OTLP_ENDPOINT` or `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`, or when the image `ENV` names one for the main process, since `openshell sandbox exec` sessions do not inherit the image environment, and an endpoint the workload sets itself, for example with a shell `export`, takes precedence over them. A workload that exports elsewhere does so subject to the sandbox's network policy, and its traces carry no relay attribution. Provider credentials cannot redirect traces. While the relay is off, nothing is injected. Because the generic endpoint is set, an SDK that also exports metrics or logs sends them to the relay, which answers with an empty OTLP success and discards them. To keep metrics and logs, point those exporters elsewhere with `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` and `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`. The address is a reserved label rather than a network destination: the supervisor serves it inside the sandbox boundary and forwards accepted batches to the collector over the configured `protocol`. The collector's address is never visible inside the sandbox. +While the relay is active, the sandbox runtime sets `OTEL_EXPORTER_OTLP_ENDPOINT=http://192.0.0.8:4318` and `OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf` in every workload process, and sets `OTEL_EXPORTER_OTLP_COMPRESSION` and `OTEL_EXPORTER_OTLP_TRACES_COMPRESSION` to `none`, so a standard OpenTelemetry SDK exports without configuration. These are lowest-precedence defaults. They are not set when the sandbox creation request or an environment passed to `openshell sandbox exec` names `OTEL_EXPORTER_OTLP_ENDPOINT` or `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`, or when the image `ENV` names one for the main process, since `openshell sandbox exec` sessions do not inherit the image environment, and an endpoint the workload sets itself, for example with a shell `export`, takes precedence over them. A workload that exports elsewhere does so subject to the sandbox's network policy, and its traces carry no relay attribution. Provider credentials cannot redirect traces. While the relay is off, nothing is injected. The relay forwards logs and metrics too, so an SDK that exports them, for example with `OTEL_LOGS_EXPORTER=otlp` and `OTEL_METRICS_EXPORTER=otlp`, needs no other setting. The address is a reserved label rather than a network destination: the supervisor serves it inside the sandbox boundary and forwards accepted batches to the collector over the configured `protocol`. The collector's address is never visible inside the sandbox. -Every forwarded resource carries `openshell.sandbox.id`, with the same value as the supervisor's own spans, and `openshell.telemetry.source=agent`. Values the agent supplies for those two keys are replaced at the resource level; span and scope attributes pass through unchanged, so filter and join on the resource attributes. Filter on `openshell.telemetry.source` to separate agent traces from infrastructure traces, and join on `openshell.sandbox.id` to correlate them. +Every forwarded resource carries `openshell.sandbox.id`, with the same value as the supervisor's own spans, and `openshell.telemetry.source=agent`. Values the agent supplies for those two keys are replaced at the resource level; span and scope attributes pass through unchanged, so filter and join on the resource attributes. Filter on `openshell.telemetry.source` to separate agent telemetry from infrastructure telemetry, and join on `openshell.sandbox.id` to correlate them. -Agents must export traces as OTLP/HTTP protobuf with compression disabled. The relay answers 415 to JSON bodies and to any `Content-Encoding` other than `identity`, 413 to bodies larger than 2 MiB, to requests with more than 512 `ResourceSpans` entries, and to requests whose resource attributes exceed 8192 in number or 256 KiB in total, 408 to requests whose body does not arrive within 30 seconds, and 503 with `Retry-After` while its buffer of 32 batches is full, which standard SDKs retry with backoff. Error responses carry a protobuf `google.rpc.Status` whose message states the reason. While the relay is off, connections to the relay address are refused immediately. +Agents must export as OTLP/HTTP protobuf with compression disabled. The relay answers 415 to JSON bodies and to any `Content-Encoding` other than `identity`, 413 to bodies larger than 2 MiB, to requests with more than 512 `ResourceSpans`, `ResourceLogs`, or `ResourceMetrics` entries, and to requests whose resource attributes exceed 8192 in number or 256 KiB in total, 408 to requests whose body does not arrive within 30 seconds, and 503 with `Retry-After` while that signal's buffer is full, which standard SDKs retry with backoff. Traces buffer 32 batches, and logs and metrics buffer 8 each, so one signal cannot crowd out the others. Error responses carry a protobuf `google.rpc.Status` whose message states the reason. While the relay is off, connections to the relay address are refused immediately. Delivery is best-effort. The relay answers 200 once a batch is buffered and makes one export attempt per batch, so a batch is lost if the collector is unavailable at that moment. The supervisor logs the first failed export and a periodic summary of failures. Before the sandbox reports that its main process exited, and before a suspended sandbox's supervisor exits, the relay flushes buffered batches for up to 5 seconds, and skips that wait when its most recent export failed. It keeps serving `openshell sandbox exec` sessions after the main process exits and flushes once more when the sandbox is torn down. diff --git a/docs/observability/overview.mdx b/docs/observability/overview.mdx index d6b5cfe6bd..a59d3a9c82 100644 --- a/docs/observability/overview.mdx +++ b/docs/observability/overview.mdx @@ -62,7 +62,7 @@ protocol = "http/protobuf" headers = { x-mlflow-experiment-id = "0" } ``` -While the relay is on, every workload process gets `OTEL_EXPORTER_OTLP_ENDPOINT` pointing at it, so an agent that uses a standard OpenTelemetry SDK exports without further configuration. Each relayed trace carries `openshell.telemetry.source=agent` and the sandbox's `openshell.sandbox.id`, so you can separate agent traces from OpenShell's own and join them with the sandbox's supervisor spans. For the workload environment, request limits, and delivery guarantees, refer to [Agent Trace Relay](/how-it-works/gateways/configuration#agent-trace-relay). +While the relay is on, every workload process gets `OTEL_EXPORTER_OTLP_ENDPOINT` pointing at it, so an agent that uses a standard OpenTelemetry SDK exports without further configuration. The relay also forwards the agent's OTLP logs and metrics to the same collector. Each relayed record carries `openshell.telemetry.source=agent` and the sandbox's `openshell.sandbox.id`, so you can separate agent telemetry from OpenShell's own and join them with the sandbox's supervisor spans. For the workload environment, request limits, and delivery guarantees, refer to [Agent Trace Relay](/how-it-works/gateways/configuration#agent-trace-relay). ## Metrics From 0684adedddee955014e64aef4009a1fcd3049995 Mon Sep 17 00:00:00 2001 From: Eric Curtin Date: Mon, 23 Nov 2026 22:56:13 +0000 Subject: [PATCH 2/4] test(supervisor): share the logs and metrics test requests Signed-off-by: Eric Curtin --- .../src/otlp_relay/enrichment.rs | 41 +++++++++++++++ .../src/otlp_relay/mod.rs | 52 ++----------------- .../src/otlp_relay/receiver.rs | 31 ++--------- 3 files changed, 50 insertions(+), 74 deletions(-) diff --git a/crates/openshell-supervisor/src/otlp_relay/enrichment.rs b/crates/openshell-supervisor/src/otlp_relay/enrichment.rs index 257a457663..136073504e 100644 --- a/crates/openshell-supervisor/src/otlp_relay/enrichment.rs +++ b/crates/openshell-supervisor/src/otlp_relay/enrichment.rs @@ -402,12 +402,53 @@ fn string_attribute(key: &str, value: &str) -> KeyValue { #[cfg(test)] pub mod test_util { + use openshell_otel_test_support::relay::string_attribute; + use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest; + use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest; use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest; use opentelemetry_proto::tonic::common::v1::{AnyValue, KeyValue, any_value}; + use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs}; + use opentelemetry_proto::tonic::metrics::v1::ResourceMetrics; use opentelemetry_proto::tonic::resource::v1::Resource; use opentelemetry_proto::tonic::trace::v1::{ResourceSpans, ScopeSpans, Span}; use prost::Message; + /// A logs and a metrics export, each with one resource that spoofs the + /// sandbox id. The log record's body is `agent-log`. + pub fn logs_and_metrics_requests() -> (ExportLogsServiceRequest, ExportMetricsServiceRequest) { + let resource = || { + Some(Resource { + attributes: vec![ + string_attribute("service.name", "unit-agent"), + string_attribute(super::SANDBOX_ID_KEY, "evil"), + ], + ..Default::default() + }) + }; + let logs = ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + resource: resource(), + scope_logs: vec![ScopeLogs { + log_records: vec![LogRecord { + body: Some(AnyValue { + value: Some(any_value::Value::StringValue("agent-log".into())), + }), + ..Default::default() + }], + ..Default::default() + }], + ..Default::default() + }], + }; + let metrics = ExportMetricsServiceRequest { + resource_metrics: vec![ResourceMetrics { + resource: resource(), + ..Default::default() + }], + }; + (logs, metrics) + } + /// Builds a protobuf-encoded request with one span named `span_name` and /// the given string resource attributes. pub fn encoded_request(span_name: &str, attributes: &[(&str, &str)]) -> Vec { diff --git a/crates/openshell-supervisor/src/otlp_relay/mod.rs b/crates/openshell-supervisor/src/otlp_relay/mod.rs index 4ce980e77b..8d8c2de1fa 100644 --- a/crates/openshell-supervisor/src/otlp_relay/mod.rs +++ b/crates/openshell-supervisor/src/otlp_relay/mod.rs @@ -713,7 +713,9 @@ mod tests { use tokio::io::AsyncWriteExt as _; use tracing_subscriber::layer::SubscriberExt as _; - use super::enrichment::test_util::{encoded_request, encoded_request_with_large_span}; + use super::enrichment::test_util::{ + encoded_request, encoded_request_with_large_span, logs_and_metrics_requests, + }; use super::enrichment::{SANDBOX_ID_KEY, SOURCE_KEY, SOURCE_VALUE}; use super::exporter::test_util::SilentCollector; use super::receiver::test_util::{connect, read_head, request, send}; @@ -905,50 +907,6 @@ mod tests { })); } - fn export_requests() -> ( - opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest, - opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest, - ) { - use openshell_otel_test_support::relay::string_attribute; - use opentelemetry_proto::tonic::common::v1::{AnyValue, any_value}; - use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs}; - use opentelemetry_proto::tonic::metrics::v1::ResourceMetrics; - use opentelemetry_proto::tonic::resource::v1::Resource; - - let resource = || { - Some(Resource { - attributes: vec![ - string_attribute("service.name", "unit-agent"), - string_attribute(SANDBOX_ID_KEY, "evil"), - ], - ..Default::default() - }) - }; - let logs = opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest { - resource_logs: vec![ResourceLogs { - resource: resource(), - scope_logs: vec![ScopeLogs { - log_records: vec![LogRecord { - body: Some(AnyValue { - value: Some(any_value::Value::StringValue("agent-log".into())), - }), - ..Default::default() - }], - ..Default::default() - }], - ..Default::default() - }], - }; - let metrics = - opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest { - resource_metrics: vec![ResourceMetrics { - resource: resource(), - ..Default::default() - }], - }; - (logs, metrics) - } - #[tokio::test] async fn logs_and_metrics_reach_a_grpc_collector_with_attribution() { let collector = OtlpTestServer::start().await; @@ -963,7 +921,7 @@ mod tests { let (mut client, boundary) = tokio::io::duplex(64 * 1024); tokio::spawn(reserved.handler.serve(Box::new(boundary)).unwrap()); - let (logs, metrics) = export_requests(); + let (logs, metrics) = logs_and_metrics_requests(); for (path, body) in [ ("/v1/logs", logs.encode_to_vec()), ("/v1/metrics", metrics.encode_to_vec()), @@ -1020,7 +978,7 @@ mod tests { let (mut client, boundary) = tokio::io::duplex(64 * 1024); tokio::spawn(reserved.handler.serve(Box::new(boundary)).unwrap()); - let (logs, metrics) = export_requests(); + let (logs, metrics) = logs_and_metrics_requests(); for (path, body) in [ ("/v1/metrics", metrics.encode_to_vec()), ("/v1/logs", logs.encode_to_vec()), diff --git a/crates/openshell-supervisor/src/otlp_relay/receiver.rs b/crates/openshell-supervisor/src/otlp_relay/receiver.rs index 75a09abe92..c625b4124c 100644 --- a/crates/openshell-supervisor/src/otlp_relay/receiver.rs +++ b/crates/openshell-supervisor/src/otlp_relay/receiver.rs @@ -610,7 +610,8 @@ mod tests { use super::super::buffer::{BatchReceiver, new_buffer}; use super::super::enrichment::test_util::{ - encoded_request, encoded_request_with_large_span, resource_attributes, + encoded_request, encoded_request_with_large_span, logs_and_metrics_requests, + resource_attributes, }; use super::super::{BUFFER_CAPACITY, enrichment}; use super::test_util::{connect, read_head, request, request_with_headers, send}; @@ -668,36 +669,12 @@ mod tests { #[tokio::test] async fn logs_and_metrics_are_enriched_and_buffered() { - use openshell_otel_test_support::relay::string_attribute; use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest; use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest; - use opentelemetry_proto::tonic::logs::v1::ResourceLogs; - use opentelemetry_proto::tonic::metrics::v1::ResourceMetrics; use opentelemetry_proto::tonic::resource::v1::Resource; - let resource = || { - Some(Resource { - attributes: vec![ - string_attribute("service.name", "unit-agent"), - string_attribute(enrichment::SANDBOX_ID_KEY, "spoofed"), - ], - ..Default::default() - }) - }; - let logs = ExportLogsServiceRequest { - resource_logs: vec![ResourceLogs { - resource: resource(), - ..Default::default() - }], - } - .encode_to_vec(); - let metrics = ExportMetricsServiceRequest { - resource_metrics: vec![ResourceMetrics { - resource: resource(), - ..Default::default() - }], - } - .encode_to_vec(); + let (logs, metrics) = logs_and_metrics_requests(); + let (logs, metrics) = (logs.encode_to_vec(), metrics.encode_to_vec()); let (server, _handle, mut rx) = start(BUFFER_CAPACITY); let mut client = connect(&server); From a561522894b6514a0f6ed9332fe7707b5d0132cf Mon Sep 17 00:00:00 2001 From: Eric Curtin Date: Fri, 27 Nov 2026 10:09:54 +0000 Subject: [PATCH 3/4] fix(supervisor): address relay review feedback Signed-off-by: Eric Curtin --- crates/openshell-core/src/sandbox_env.rs | 6 + crates/openshell-sandbox/README.md | 4 +- crates/openshell-sandbox/src/child_env.rs | 14 +- crates/openshell-sandbox/src/process.rs | 5 + crates/openshell-supervisor/README.md | 2 +- .../src/otlp_relay/buffer.rs | 69 ++++--- .../src/otlp_relay/enrichment.rs | 4 +- .../src/otlp_relay/mod.rs | 177 ++++++++++++++---- .../src/otlp_relay/receiver.rs | 9 +- docs/how-it-works/gateways/configuration.mdx | 10 +- 10 files changed, 221 insertions(+), 79 deletions(-) diff --git a/crates/openshell-core/src/sandbox_env.rs b/crates/openshell-core/src/sandbox_env.rs index c691642904..185f4d09c8 100644 --- a/crates/openshell-core/src/sandbox_env.rs +++ b/crates/openshell-core/src/sandbox_env.rs @@ -544,6 +544,12 @@ pub const OTEL_EXPORTER_OTLP_COMPRESSION: &str = "OTEL_EXPORTER_OTLP_COMPRESSION /// every trace export. pub const OTEL_EXPORTER_OTLP_TRACES_COMPRESSION: &str = "OTEL_EXPORTER_OTLP_TRACES_COMPRESSION"; +/// Logs-specific compression variable, set to `none` like the traces one. +pub const OTEL_EXPORTER_OTLP_LOGS_COMPRESSION: &str = "OTEL_EXPORTER_OTLP_LOGS_COMPRESSION"; + +/// Metrics-specific compression variable, set to `none` like the traces one. +pub const OTEL_EXPORTER_OTLP_METRICS_COMPRESSION: &str = "OTEL_EXPORTER_OTLP_METRICS_COMPRESSION"; + /// Reserved destination agent processes export OTLP to. /// /// This address is never routed. A workload `connect()` to any non-loopback diff --git a/crates/openshell-sandbox/README.md b/crates/openshell-sandbox/README.md index 1f2bce2033..a4a86408bd 100644 --- a/crates/openshell-sandbox/README.md +++ b/crates/openshell-sandbox/README.md @@ -59,8 +59,8 @@ dropped. When `AgentSpec::otlp_relay_active` is set, `child_env::apply_otlp_relay_env` gives every workload process (main, exec, and SSH) `OTEL_EXPORTER_OTLP_ENDPOINT` pointing at the relay address, `OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf`, and -`none` for `OTEL_EXPORTER_OTLP_COMPRESSION` and -`OTEL_EXPORTER_OTLP_TRACES_COMPRESSION`, and removes any inherited +`none` for `OTEL_EXPORTER_OTLP_COMPRESSION` and the traces, logs, and metrics +compression variables, and removes any inherited `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`. These defaults apply after the provider variables. If the creation request or a per-exec environment names a generic or traces-specific OTLP endpoint, the runtime injects nothing, and the diff --git a/crates/openshell-sandbox/src/child_env.rs b/crates/openshell-sandbox/src/child_env.rs index 5d9c90a20f..b726925d41 100644 --- a/crates/openshell-sandbox/src/child_env.rs +++ b/crates/openshell-sandbox/src/child_env.rs @@ -6,8 +6,10 @@ use std::hash::BuildHasher; use std::path::Path; use openshell_core::sandbox_env::{ - OTEL_EXPORTER_OTLP_COMPRESSION, OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_PROTOCOL, - OTEL_EXPORTER_OTLP_TRACES_COMPRESSION, OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, OTLP_RELAY_ENDPOINT, + OTEL_EXPORTER_OTLP_COMPRESSION, OTEL_EXPORTER_OTLP_ENDPOINT, + OTEL_EXPORTER_OTLP_LOGS_COMPRESSION, OTEL_EXPORTER_OTLP_METRICS_COMPRESSION, + OTEL_EXPORTER_OTLP_PROTOCOL, OTEL_EXPORTER_OTLP_TRACES_COMPRESSION, + OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, OTLP_RELAY_ENDPOINT, }; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -59,16 +61,18 @@ const OTLP_ENDPOINT_VARS: [&str; 2] = [ /// Only the generic endpoint and protocol are set. Signal-specific variables /// take precedence over them in every SDK, so an endpoint the workload sets /// later at any layer, generic or traces-specific, wins over this default. -/// Compression is disabled for both the generic and the traces-specific +/// Compression is disabled for the generic and every signal-specific /// variable because the relay refuses compressed bodies, and a `gzip` value /// from the image or the creation request would otherwise make every export /// fail. -pub fn otlp_relay_env_vars() -> [(&'static str, &'static str); 4] { +pub fn otlp_relay_env_vars() -> [(&'static str, &'static str); 6] { [ (OTEL_EXPORTER_OTLP_ENDPOINT, OTLP_RELAY_ENDPOINT), (OTEL_EXPORTER_OTLP_PROTOCOL, "http/protobuf"), (OTEL_EXPORTER_OTLP_COMPRESSION, "none"), (OTEL_EXPORTER_OTLP_TRACES_COMPRESSION, "none"), + (OTEL_EXPORTER_OTLP_LOGS_COMPRESSION, "none"), + (OTEL_EXPORTER_OTLP_METRICS_COMPRESSION, "none"), ] } @@ -231,6 +235,8 @@ mod tests { ("OTEL_EXPORTER_OTLP_PROTOCOL", "http/protobuf"), ("OTEL_EXPORTER_OTLP_COMPRESSION", "none"), ("OTEL_EXPORTER_OTLP_TRACES_COMPRESSION", "none"), + ("OTEL_EXPORTER_OTLP_LOGS_COMPRESSION", "none"), + ("OTEL_EXPORTER_OTLP_METRICS_COMPRESSION", "none"), ] ); } diff --git a/crates/openshell-sandbox/src/process.rs b/crates/openshell-sandbox/src/process.rs index 4967d20086..c62bc8e06a 100644 --- a/crates/openshell-sandbox/src/process.rs +++ b/crates/openshell-sandbox/src/process.rs @@ -1389,6 +1389,7 @@ mod tests { fn canonical_process_sees_relay_endpoint_and_never_the_collector() { use openshell_core::sandbox_env::{ OTEL_EXPORTER_OTLP_COMPRESSION, OTEL_EXPORTER_OTLP_ENDPOINT, + OTEL_EXPORTER_OTLP_LOGS_COMPRESSION, OTEL_EXPORTER_OTLP_METRICS_COMPRESSION, OTEL_EXPORTER_OTLP_PROTOCOL, OTEL_EXPORTER_OTLP_TRACES_COMPRESSION, OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, OTLP_RELAY_ENDPOINT, }; @@ -1460,6 +1461,8 @@ mod tests { HashMap::from([ (OTEL_EXPORTER_OTLP_PROTOCOL.into(), "grpc".into()), (OTEL_EXPORTER_OTLP_TRACES_COMPRESSION.into(), "gzip".into()), + (OTEL_EXPORTER_OTLP_LOGS_COMPRESSION.into(), "gzip".into()), + (OTEL_EXPORTER_OTLP_METRICS_COMPRESSION.into(), "gzip".into()), ]), provider_redirect(), true, @@ -1467,6 +1470,8 @@ mod tests { for key in [ OTEL_EXPORTER_OTLP_COMPRESSION, OTEL_EXPORTER_OTLP_TRACES_COMPRESSION, + OTEL_EXPORTER_OTLP_LOGS_COMPRESSION, + OTEL_EXPORTER_OTLP_METRICS_COMPRESSION, ] { assert_eq!( get(&variables, key).as_deref(), diff --git a/crates/openshell-supervisor/README.md b/crates/openshell-supervisor/README.md index 201ca2cc96..b782d063b2 100644 --- a/crates/openshell-supervisor/README.md +++ b/crates/openshell-supervisor/README.md @@ -134,7 +134,7 @@ Console JSON is installed independently of optional file appenders and uses an I The `otlp_relay` module forwards the workload's OTLP/HTTP protobuf trace, log, and metrics exports to the collector named by `OPENSHELL_OTLP_AGENT_ENDPOINT`, over the transport named by `OPENSHELL_OTLP_AGENT_PROTOCOL` (`grpc` when unset, or `http/protobuf`). Each export carries the collector headers from the launch bundle's `agent_otlp_headers` and, for an `https` collector, verifies it and authenticates with `agent_otlp_tls`; the supervisor's own span and OCSF exporters use the `traces_` and `ocsf_` fields the same way. The gateway sets those variables only when `[openshell.gateway.otlp.agent]` is enabled, so trace export alone leaves the relay inactive. The workload exports to the reserved address `192.0.0.8:4318`; the sandbox broker stages that connection to the supervisor, and the network proxy hands the stream to the relay's HTTP/1.1 receiver through the generic reserved-destination hook instead of evaluating policy. The receiver replaces the `openshell.sandbox.id` and `openshell.telemetry.source=agent` resource attributes, pushes the re-encoded batch into the bounded buffer of its signal, and a single export task forwards the encoded batches to the collector with a lazy connection. -Limits are fixed: 2 MiB per request body, at most 512 `ResourceSpans` entries, 256 KiB of encoded `Resource` fields, and 8192 resource attributes per request (each of these answers 413), a 10 second header-read timeout, 16 concurrent connections, 32 buffered batches, and a 5 second deadline per export attempt. Only the resources are decoded; spans are copied byte for byte, at most two requests at a time. Worst-case memory attributable to the agent is about 67 MiB of buffered batches, plus 32 MiB of bodies awaiting enrichment across the 16 connections, plus about 12 MiB for the two enrichments in progress, plus about 4 MiB for the batch being exported and its encoded copy. A full buffer answers 503 with `Retry-After`. Without an agent endpoint nothing starts and the proxy refuses the relay address. After the agent exits, `run_sandbox_with_backend` flushes buffered batches for up to 5 seconds before it reports the exit to the gateway, then logs a final summary of rejected and failed counts. Flushes skip the wait while the most recent export failed, and batches still pending when the relay is dropped without a flush count as failed. The supervisor tells the sandbox runtime through `AgentSpec::otlp_relay_active` whether the relay runs, and the runtime injects the generic `OTEL_EXPORTER_OTLP_*` defaults only then. +Limits are fixed: 2 MiB per request body, at most 512 `ResourceSpans` entries, 256 KiB of encoded `Resource` fields, and 8192 resource attributes per request (each of these answers 413), a 10 second header-read timeout, 16 concurrent connections, 32 buffered trace batches (8 each for logs and metrics), and a 5 second deadline per export attempt. Only the resources are decoded; spans are copied byte for byte, at most two requests at a time. Worst-case memory attributable to the agent is about 100 MiB of buffered batches, plus 32 MiB of bodies awaiting enrichment across the 16 connections, plus about 12 MiB for the two enrichments in progress, plus about 4 MiB for the batch being exported and its encoded copy. A full buffer answers 503 with `Retry-After`. Without an agent endpoint nothing starts and the proxy refuses the relay address. After the agent exits, `run_sandbox_with_backend` flushes buffered batches for up to 5 seconds before it reports the exit to the gateway, then logs a final summary of rejected and failed counts. Flushes skip the wait while the most recent export failed, and batches still pending when the relay is dropped without a flush count as failed. The supervisor tells the sandbox runtime through `AgentSpec::otlp_relay_active` whether the relay runs, and the runtime injects the generic `OTEL_EXPORTER_OTLP_*` defaults only then. ## Safe runtime and parent liveness diff --git a/crates/openshell-supervisor/src/otlp_relay/buffer.rs b/crates/openshell-supervisor/src/otlp_relay/buffer.rs index b01e500e59..573b3b0b42 100644 --- a/crates/openshell-supervisor/src/otlp_relay/buffer.rs +++ b/crates/openshell-supervisor/src/otlp_relay/buffer.rs @@ -58,12 +58,11 @@ pub struct BatchReceiver { impl BatchReceiver { /// Next buffered batch, or `None` once every sender has been dropped and - /// the buffer is drained. Traces go before logs and logs before metrics - /// when several are waiting; arrival order holds within a signal. + /// the buffer is drained. When several signals are waiting, tokio picks + /// one at random, so none starves; arrival order holds within a signal. pub async fn recv(&mut self) -> Option<(Signal, Bytes)> { let [traces, logs, metrics] = &mut self.queues; tokio::select! { - biased; Some(batch) = traces.recv() => Some((Signal::Traces, batch)), Some(batch) = logs.recv() => Some((Signal::Logs, batch)), Some(batch) = metrics.recv() => Some((Signal::Metrics, batch)), @@ -72,17 +71,20 @@ impl BatchReceiver { } } +/// Queue size of `signal` for a buffer of `capacity` trace batches: logs and +/// metrics get a quarter of that, rounded up. +pub fn queue_capacity(signal: Signal, capacity: usize) -> usize { + match signal { + Signal::Traces => capacity, + Signal::Logs | Signal::Metrics => capacity.div_ceil(4), + } +} + /// Creates a buffer holding at most `capacity` trace batches and a quarter /// of that, rounded up, for each of logs and metrics. pub fn new_buffer(capacity: usize) -> (BatchSender, BatchReceiver) { let (senders, receivers): (Vec<_>, Vec<_>) = Signal::ALL - .map(|signal| { - let capacity = match signal { - Signal::Traces => capacity, - Signal::Logs | Signal::Metrics => capacity.div_ceil(4), - }; - mpsc::channel(capacity) - }) + .map(|signal| mpsc::channel(queue_capacity(signal, capacity))) .into_iter() .unzip(); ( @@ -118,18 +120,37 @@ mod tests { #[tokio::test] async fn a_full_signal_does_not_block_the_others() { let (tx, mut rx) = new_buffer(32); - for _ in 0..8 { - tx.try_send(Signal::Logs, Bytes::from_static(b"l")).unwrap(); + for signal in [Signal::Logs, Signal::Metrics] { + for _ in 0..8 { + tx.try_send(signal, Bytes::from_static(b"x")).unwrap(); + } + assert_eq!( + tx.try_send(signal, Bytes::from_static(b"x")), + Err(SendError::BufferFull) + ); } - assert_eq!( - tx.try_send(Signal::Logs, Bytes::from_static(b"l")), - Err(SendError::BufferFull) - ); + tx.try_send(T, Bytes::from_static(b"t")).unwrap(); + let mut seen = Vec::new(); + for _ in 0..17 { + seen.push(rx.recv().await.unwrap().0); + } + assert_eq!(seen.iter().filter(|s| **s == T).count(), 1); + } + + #[tokio::test] + async fn a_busy_signal_does_not_starve_the_others() { + let (tx, mut rx) = new_buffer(32); + for _ in 0..32 { + tx.try_send(T, Bytes::from_static(b"t")).unwrap(); + } + tx.try_send(Signal::Logs, Bytes::from_static(b"l")).unwrap(); tx.try_send(Signal::Metrics, Bytes::from_static(b"m")) .unwrap(); - tx.try_send(T, Bytes::from_static(b"t")).unwrap(); - assert_eq!(rx.recv().await.unwrap().0, T); - assert_eq!(rx.recv().await.unwrap().0, Signal::Logs); + let mut seen = Vec::new(); + for _ in 0..16 { + seen.push(rx.recv().await.unwrap().0); + } + assert!(seen.contains(&Signal::Logs) && seen.contains(&Signal::Metrics)); } #[tokio::test] @@ -139,10 +160,14 @@ mod tests { tx.try_send(Signal::Metrics, Bytes::from_static(b"b")) .unwrap(); drop(tx); - assert_eq!(rx.recv().await.unwrap(), (T, Bytes::from_static(b"a"))); + let mut got = vec![rx.recv().await.unwrap(), rx.recv().await.unwrap()]; + got.sort_by_key(|(signal, _)| signal.index()); assert_eq!( - rx.recv().await.unwrap(), - (Signal::Metrics, Bytes::from_static(b"b")) + got, + [ + (T, Bytes::from_static(b"a")), + (Signal::Metrics, Bytes::from_static(b"b")) + ] ); assert!(rx.recv().await.is_none()); } diff --git a/crates/openshell-supervisor/src/otlp_relay/enrichment.rs b/crates/openshell-supervisor/src/otlp_relay/enrichment.rs index 136073504e..613a3678d8 100644 --- a/crates/openshell-supervisor/src/otlp_relay/enrichment.rs +++ b/crates/openshell-supervisor/src/otlp_relay/enrichment.rs @@ -121,7 +121,7 @@ impl std::fmt::Display for EnrichError { match self { Self::Malformed(error) => write!(f, "malformed OTLP export request: {error}"), Self::TooManyResourceSpans => { - write!(f, "more than {MAX_RESOURCE_SPANS} resource_spans entries") + write!(f, "more than {MAX_RESOURCE_SPANS} resource entries") } Self::TooManyResourceAttributes => { write!(f, "more than {MAX_RESOURCE_ATTRIBUTES} resource attributes") @@ -174,7 +174,7 @@ fn enrich_to_vec(raw: &[u8], sandbox_id: &str) -> Result, EnrichError> { if tag == RESOURCE_SPANS_TAG { if wire_type != WireType::LengthDelimited { return Err(EnrichError::Malformed( - "resource_spans is not length-delimited".into(), + "resource entry is not length-delimited".into(), )); } entries += 1; diff --git a/crates/openshell-supervisor/src/otlp_relay/mod.rs b/crates/openshell-supervisor/src/otlp_relay/mod.rs index 8d8c2de1fa..441d74ac83 100644 --- a/crates/openshell-supervisor/src/otlp_relay/mod.rs +++ b/crates/openshell-supervisor/src/otlp_relay/mod.rs @@ -74,6 +74,14 @@ impl Signal { } } + const fn name(self) -> &'static str { + match self { + Self::Traces => "traces", + Self::Logs => "logs", + Self::Metrics => "metrics", + } + } + const fn index(self) -> usize { self as usize } @@ -111,7 +119,8 @@ pub const MAX_CONCURRENT_CONNECTIONS: usize = 16; pub const ENRICHMENT_CONCURRENCY: usize = 2; /// Number of enriched trace batches held between receipt and export. Logs /// and metrics each get a quarter of it in a buffer of their own, so a chatty -/// signal cannot crowd out the others. +/// signal cannot fill the others' buffers; the export task drains them +/// round robin. pub const BUFFER_CAPACITY: usize = 32; /// Deadline for one export attempt to the collector. pub const EXPORT_TIMEOUT: Duration = Duration::from_secs(5); @@ -141,6 +150,11 @@ struct SignalCounts { exported: AtomicU64, rejected: AtomicU64, export_failures: AtomicU64, + /// Whether the most recent export of this signal failed. Cleared by the + /// next success. + last_export_failed: AtomicBool, + first_rejection_logged: AtomicBool, + first_failure_logged: AtomicBool, } impl SignalCounts { @@ -171,11 +185,6 @@ impl SignalCounts { #[derive(Debug, Default)] pub struct RelayCounters { signals: [SignalCounts; Signal::ALL.len()], - /// Whether the most recent export attempt failed. Cleared by the next - /// success; flushes skip waiting while it is set. - last_export_failed: AtomicBool, - first_rejection_logged: AtomicBool, - first_failure_logged: AtomicBool, final_summary_logged: AtomicBool, } @@ -190,43 +199,54 @@ impl RelayCounters { } /// Records one export request refused with 503 because the buffer was - /// full. Warns on the first occurrence only. + /// full. Warns on the first occurrence per signal only. pub fn record_rejection(&self, signal: Signal) { - self.counts(signal).rejected.fetch_add(1, Ordering::Relaxed); - if !self.first_rejection_logged.swap(true, Ordering::Relaxed) { + let counts = self.counts(signal); + counts.rejected.fetch_add(1, Ordering::Relaxed); + if !counts.first_rejection_logged.swap(true, Ordering::Relaxed) { warn!( - buffer_capacity = BUFFER_CAPACITY, + signal = signal.name(), + buffer_capacity = buffer::queue_capacity(signal, BUFFER_CAPACITY), "OTLP relay rejected an agent export: buffer full" ); } } /// Records one export attempt that failed or timed out. Warns on the - /// first occurrence only. + /// first occurrence per signal only. pub fn record_export_failure( &self, signal: Signal, endpoint: &str, error: &dyn std::fmt::Display, ) { - self.counts(signal) - .export_failures - .fetch_add(1, Ordering::Relaxed); - self.last_export_failed.store(true, Ordering::Relaxed); - if !self.first_failure_logged.swap(true, Ordering::Relaxed) { - warn!(endpoint, %error, "OTLP relay export to collector failed"); + let counts = self.counts(signal); + counts.export_failures.fetch_add(1, Ordering::Relaxed); + counts.last_export_failed.store(true, Ordering::Relaxed); + if !counts.first_failure_logged.swap(true, Ordering::Relaxed) { + warn!( + signal = signal.name(), + endpoint, + %error, + "OTLP relay export to collector failed" + ); } } /// Records one batch delivered to the collector. pub fn record_export_success(&self, signal: Signal) { - self.counts(signal).exported.fetch_add(1, Ordering::Relaxed); - self.last_export_failed.store(false, Ordering::Relaxed); + let counts = self.counts(signal); + counts.exported.fetch_add(1, Ordering::Relaxed); + counts.last_export_failed.store(false, Ordering::Relaxed); } - /// Whether the most recent export attempt failed. - fn last_export_failed(&self) -> bool { - self.last_export_failed.load(Ordering::Relaxed) + /// Whether batches are pending and the most recent export of every + /// signal that has some failed. A collector that rejects only logs or + /// metrics does not count, so trace batches still get flushed. + fn collector_down(&self) -> bool { + let mut pending = self.signals.iter().filter(|counts| counts.pending() > 0); + pending.clone().next().is_some() + && pending.all(|counts| counts.last_export_failed.load(Ordering::Relaxed)) } /// Current counts over all signals. @@ -287,16 +307,16 @@ impl RelayCounters { ); } - /// Logs the final summary once, and only when something was rejected or - /// failed (FR-009). Called from `shutdown` and, for lifecycle paths that + /// Logs the final summary once, when anything was exported, rejected or + /// failed. Called from `shutdown` and, for lifecycle paths that /// drop the relay without shutting it down, from `Drop`. fn log_final_summary(&self) { let CounterSnapshot { + exported, rejected, export_failures, - .. } = self.snapshot(); - if (rejected > 0 || export_failures > 0) + if (exported > 0 || rejected > 0 || export_failures > 0) && !self.final_summary_logged.swap(true, Ordering::Relaxed) { self.log_summary(); @@ -604,11 +624,11 @@ impl OtlpRelay { /// supervisor stays up for exec sessions afterwards, so their traces /// are still relayed; [`Self::shutdown`] runs at final teardown. /// - /// Returns at once when the most recent export failed: a collector that - /// is down would only run the clock out, and trace delivery must not + /// Returns at once when the most recent export of every pending signal + /// failed: a collector that is down would only run the clock out, and trace delivery must not /// delay the exit report. pub async fn flush(&self, bound: Duration) { - if self.counters.last_export_failed() { + if self.counters.collector_down() { let pending = self.counters.pending(); if pending > 0 { warn!( @@ -642,7 +662,8 @@ impl OtlpRelay { /// collector for at most `flush_bound`, and logs the final summary. /// Never fails; batches still pending at the deadline are discarded and /// counted as export failures. Like [`Self::flush`], it does not wait for - /// the collector when the most recent export failed. + /// the collector when the most recent export of every pending signal + /// failed. pub async fn shutdown(mut self, flush_bound: Duration) { let started = Instant::now(); let exported_before = self.counters.snapshot().exported; @@ -653,7 +674,7 @@ impl OtlpRelay { } self.server.close_buffer(); - if self.counters.last_export_failed() { + if self.counters.collector_down() { self.export_task.abort(); let _ = (&mut self.export_task).await; let discarded = self.counters.discard_pending(); @@ -961,7 +982,17 @@ mod tests { "spoofed attribution keys were appended to, not replaced: {:?}", received.duplicate_resource_keys ); - assert_eq!(relay.counters.snapshot().exported, 2); + wait_until(Duration::from_secs(5), || relay.counters.pending() == 0).await; + let exported = |signal| relay.counters.counts(signal).snapshot().exported; + assert_eq!( + [ + exported(Signal::Traces), + exported(Signal::Logs), + exported(Signal::Metrics) + ], + [0, 1, 1] + ); + relay.flush(Duration::from_secs(1)).await; } #[tokio::test] @@ -1357,10 +1388,42 @@ mod tests { #[tokio::test] async fn a_successful_export_clears_the_failure_flag() { let counters = RelayCounters::default(); + counters.record_accepted(Signal::Traces); counters.record_export_failure(Signal::Traces, "http://collector:4317", &"boom"); - assert!(counters.last_export_failed()); + counters.record_accepted(Signal::Traces); + assert!(counters.collector_down()); counters.record_export_success(Signal::Traces); - assert!(!counters.last_export_failed()); + counters.record_accepted(Signal::Traces); + assert!(!counters.collector_down()); + } + + #[tokio::test] + async fn a_failing_signal_does_not_mark_the_collector_down_for_the_others() { + let counters = RelayCounters::default(); + counters.record_accepted(Signal::Traces); + counters.record_accepted(Signal::Logs); + counters.record_export_failure(Signal::Logs, "http://collector:4317", &"404"); + assert_eq!(counters.counts(Signal::Logs).pending(), 0); + assert!(!counters.collector_down(), "traces never failed"); + counters.record_export_failure(Signal::Traces, "http://collector:4317", &"down"); + counters.record_accepted(Signal::Traces); + assert!(counters.collector_down()); + } + + #[tokio::test] + async fn flush_delivers_traces_after_a_logs_export_failure() { + let collector = OtlpTestServer::start().await; + let (relay, _reserved, gate) = gated(collector.endpoint()); + assert_eq!(post(&relay, "last-span").await, 200); + relay + .counters + .record_export_failure(Signal::Logs, collector.endpoint(), &"404"); + gate.send_replace(true); + relay.flush(FLUSH_TIMEOUT).await; + assert_eq!(relay.counters.counts(Signal::Traces).snapshot().exported, 1); + relay.shutdown(FLUSH_TIMEOUT).await; + let received = collector.shutdown().await; + assert!(received.spans.iter().any(|span| span.name == "last-span")); } #[tokio::test] @@ -1423,6 +1486,44 @@ mod tests { 1 ); assert_eq!(counters.snapshot().rejected, 10); + + counters.record_rejection(Signal::Logs); + let warnings = logs.events( + tracing::Level::WARN, + "OTLP relay rejected an agent export: buffer full", + ); + assert_eq!(warnings.len(), 2, "the latch is per signal"); + assert_eq!(warnings[1].field("buffer_capacity"), Some(8)); + } + + #[tokio::test] + async fn summary_names_the_counts_of_each_signal() { + let logs = LogCapture::default(); + let _guard = logs.install(); + let counters = RelayCounters::default(); + counters.record_export_success(Signal::Logs); + counters.record_rejection(Signal::Metrics); + counters.record_rejection(Signal::Metrics); + counters.record_export_failure(Signal::Traces, "http://collector:4317", &"boom"); + counters.log_final_summary(); + let summary = &logs.events(tracing::Level::INFO, "OTLP relay summary")[0]; + assert_eq!(summary.field("logs_exported"), Some(1)); + assert_eq!(summary.field("metrics_rejected"), Some(2)); + assert_eq!(summary.field("traces_export_failures"), Some(1)); + assert_eq!(summary.field("logs_rejected"), Some(0)); + assert_eq!(summary.field("metrics_exported"), Some(0)); + } + + #[tokio::test] + async fn final_summary_is_logged_when_batches_were_only_exported() { + let logs = LogCapture::default(); + let _guard = logs.install(); + let counters = RelayCounters::default(); + counters.log_final_summary(); + assert_eq!(logs.count(tracing::Level::INFO, "OTLP relay summary"), 0); + counters.record_export_success(Signal::Logs); + counters.log_final_summary(); + assert_eq!(logs.count(tracing::Level::INFO, "OTLP relay summary"), 1); } #[tokio::test] @@ -1592,11 +1693,9 @@ mod tests { logs.count(tracing::Level::INFO, "OTLP relay flushed before exit"), 1 ); - assert_eq!( - logs.count(tracing::Level::INFO, "OTLP relay summary"), - 0, - "no final summary when nothing was rejected or failed" - ); + let summaries = logs.events(tracing::Level::INFO, "OTLP relay summary"); + assert_eq!(summaries.len(), 1, "exported batches get a final summary"); + assert_eq!(summaries[0].field("traces_exported"), Some(3)); } #[tokio::test] diff --git a/crates/openshell-supervisor/src/otlp_relay/receiver.rs b/crates/openshell-supervisor/src/otlp_relay/receiver.rs index c625b4124c..19a95bbeec 100644 --- a/crates/openshell-supervisor/src/otlp_relay/receiver.rs +++ b/crates/openshell-supervisor/src/otlp_relay/receiver.rs @@ -699,16 +699,17 @@ mod tests { enrichment::SOURCE_KEY.to_string(), "service.name".to_string(), ]; - let (signal, batch) = rx.recv().await.expect("logs buffered"); + let mut batches = [rx.recv().await.unwrap(), rx.recv().await.unwrap()]; + batches.sort_by_key(|(signal, _)| signal.index()); + let [(signal, batch), (metrics_signal, metrics_batch)] = batches; assert_eq!(signal, Signal::Logs); let decoded = ExportLogsServiceRequest::decode(batch).unwrap(); assert_eq!( attributes(decoded.resource_logs[0].resource.clone()), expected ); - let (signal, batch) = rx.recv().await.expect("metrics buffered"); - assert_eq!(signal, Signal::Metrics); - let decoded = ExportMetricsServiceRequest::decode(batch).unwrap(); + assert_eq!(metrics_signal, Signal::Metrics); + let decoded = ExportMetricsServiceRequest::decode(metrics_batch).unwrap(); assert_eq!( attributes(decoded.resource_metrics[0].resource.clone()), expected diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index 4b54e95a6c..eb8d78fc3f 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -1107,7 +1107,7 @@ Metrics include `openshell_ocsf_otlp_queued_total`, `openshell_ocsf_otlp_exporte ### Agent trace relay -Set `enabled = true` in `[openshell.gateway.otlp.agent]` to have each sandbox forward the workload's own traces, logs, and metrics. It defaults to `false`, so trace export alone never changes the workload environment. They go to the table's collector, or to the `[openshell.gateway.otlp]` collector when it has no `endpoint`, and that collector must be reachable from sandboxes. Use `protocol = "http/protobuf"` for trace backends that accept only OTLP/HTTP, and `headers` for the ones that need them. For example, MLflow accepts traces directly when each request names an experiment: +Set `enabled = true` in `[openshell.gateway.otlp.agent]` to have each sandbox forward the workload's own traces, logs, and metrics. It defaults to `false`, so trace export alone never changes the workload environment. They go to the table's collector, or to the `[openshell.gateway.otlp]` collector when it has no `endpoint`, and that collector must be reachable from sandboxes. It must accept traces, logs, and metrics: the relay forwards all three, and a backend that serves only traces rejects the other two. Releases before the relay forwarded logs and metrics acknowledged and dropped them, so after an upgrade a trace-only backend logs a failed export for each batch the agent still sends. Have such an agent switch the other exporters off, for example with `OTEL_LOGS_EXPORTER=none` and `OTEL_METRICS_EXPORTER=none`. Use `protocol = "http/protobuf"` for trace backends that accept only OTLP/HTTP, and `headers` for the ones that need them. For example, MLflow accepts traces directly when each request names an experiment, but not logs or metrics: ```toml [openshell.gateway.otlp.agent] @@ -1117,13 +1117,13 @@ protocol = "http/protobuf" headers = { x-mlflow-experiment-id = "0" } ``` -While the relay is active, the sandbox runtime sets `OTEL_EXPORTER_OTLP_ENDPOINT=http://192.0.0.8:4318` and `OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf` in every workload process, and sets `OTEL_EXPORTER_OTLP_COMPRESSION` and `OTEL_EXPORTER_OTLP_TRACES_COMPRESSION` to `none`, so a standard OpenTelemetry SDK exports without configuration. These are lowest-precedence defaults. They are not set when the sandbox creation request or an environment passed to `openshell sandbox exec` names `OTEL_EXPORTER_OTLP_ENDPOINT` or `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`, or when the image `ENV` names one for the main process, since `openshell sandbox exec` sessions do not inherit the image environment, and an endpoint the workload sets itself, for example with a shell `export`, takes precedence over them. A workload that exports elsewhere does so subject to the sandbox's network policy, and its traces carry no relay attribution. Provider credentials cannot redirect traces. While the relay is off, nothing is injected. The relay forwards logs and metrics too, so an SDK that exports them, for example with `OTEL_LOGS_EXPORTER=otlp` and `OTEL_METRICS_EXPORTER=otlp`, needs no other setting. The address is a reserved label rather than a network destination: the supervisor serves it inside the sandbox boundary and forwards accepted batches to the collector over the configured `protocol`. The collector's address is never visible inside the sandbox. +While the relay is active, the sandbox runtime sets `OTEL_EXPORTER_OTLP_ENDPOINT=http://192.0.0.8:4318` and `OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf` in every workload process, and sets `OTEL_EXPORTER_OTLP_COMPRESSION` and the traces, logs, and metrics compression variables to `none`, so a standard OpenTelemetry SDK exports without configuration. These are lowest-precedence defaults. They are not set when the sandbox creation request or an environment passed to `openshell sandbox exec` names `OTEL_EXPORTER_OTLP_ENDPOINT` or `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`, or when the image `ENV` names one for the main process, since `openshell sandbox exec` sessions do not inherit the image environment, and an endpoint the workload sets itself, for example with a shell `export`, takes precedence over them. A workload that exports elsewhere does so subject to the sandbox's network policy, and its traces carry no relay attribution. Provider credentials cannot redirect traces, but an endpoint variable for logs or metrics that a provider sets still sends that signal past the relay. While the relay is off, nothing is injected. The relay forwards logs and metrics too, so an SDK that exports them, for example with `OTEL_LOGS_EXPORTER=otlp` and `OTEL_METRICS_EXPORTER=otlp`, needs no other setting. The address is a reserved label rather than a network destination: the supervisor serves it inside the sandbox boundary and forwards accepted batches to the collector over the configured `protocol`. The collector's address is never visible inside the sandbox. -Every forwarded resource carries `openshell.sandbox.id`, with the same value as the supervisor's own spans, and `openshell.telemetry.source=agent`. Values the agent supplies for those two keys are replaced at the resource level; span and scope attributes pass through unchanged, so filter and join on the resource attributes. Filter on `openshell.telemetry.source` to separate agent telemetry from infrastructure telemetry, and join on `openshell.sandbox.id` to correlate them. +Every forwarded resource carries `openshell.sandbox.id`, with the same value as the supervisor's own spans, and `openshell.telemetry.source=agent`. Values the agent supplies for those two keys are replaced at the resource level; span and scope attributes pass through unchanged, so filter and join on the resource attributes. Filter on `openshell.telemetry.source` to separate agent telemetry from infrastructure telemetry, and join on `openshell.sandbox.id` to correlate them. The agent can send any log record or metric through the relay, including one that imitates an OCSF event. When `[openshell.gateway.otlp.agent]` and OCSF export share a collector, drop `openshell.telemetry.source=agent` from audit pipelines, or give the agent relay its own `endpoint`. -Agents must export as OTLP/HTTP protobuf with compression disabled. The relay answers 415 to JSON bodies and to any `Content-Encoding` other than `identity`, 413 to bodies larger than 2 MiB, to requests with more than 512 `ResourceSpans`, `ResourceLogs`, or `ResourceMetrics` entries, and to requests whose resource attributes exceed 8192 in number or 256 KiB in total, 408 to requests whose body does not arrive within 30 seconds, and 503 with `Retry-After` while that signal's buffer is full, which standard SDKs retry with backoff. Traces buffer 32 batches, and logs and metrics buffer 8 each, so one signal cannot crowd out the others. Error responses carry a protobuf `google.rpc.Status` whose message states the reason. While the relay is off, connections to the relay address are refused immediately. +Agents must export as OTLP/HTTP protobuf with compression disabled. The relay answers 415 to JSON bodies and to any `Content-Encoding` other than `identity`, 413 to bodies larger than 2 MiB, to requests with more than 512 `ResourceSpans`, `ResourceLogs`, or `ResourceMetrics` entries, and to requests whose resource attributes exceed 8192 in number or 256 KiB in total, 408 to requests whose body does not arrive within 30 seconds, and 503 with `Retry-After` while that signal's buffer is full, which standard SDKs retry with backoff. Traces buffer 32 batches, and logs and metrics buffer 8 each, so one signal cannot fill the others' buffers, and the relay exports them in no fixed order. Error responses carry a protobuf `google.rpc.Status` whose message states the reason. While the relay is off, connections to the relay address are refused immediately. -Delivery is best-effort. The relay answers 200 once a batch is buffered and makes one export attempt per batch, so a batch is lost if the collector is unavailable at that moment. The supervisor logs the first failed export and a periodic summary of failures. Before the sandbox reports that its main process exited, and before a suspended sandbox's supervisor exits, the relay flushes buffered batches for up to 5 seconds, and skips that wait when its most recent export failed. It keeps serving `openshell sandbox exec` sessions after the main process exits and flushes once more when the sandbox is torn down. +Delivery is best-effort. The relay answers 200 once a batch is buffered and makes one export attempt per batch, so a batch is lost if the collector is unavailable at that moment. The supervisor logs the first failed export of each signal, a periodic summary of failures, and a final summary with per-signal exported, rejected, and failed counts when the sandbox exits. Before the sandbox reports that its main process exited, and before a suspended sandbox's supervisor exits, the relay flushes buffered batches for up to 5 seconds, and skips that wait when its most recent export failed. It keeps serving `openshell sandbox exec` sessions after the main process exits and flushes once more when the sandbox is torn down. ### Tuning From a495c81f68b7458fc6ebe91dc618f5541e50d02b Mon Sep 17 00:00:00 2001 From: Eric Curtin Date: Tue, 1 Dec 2026 10:21:59 +0000 Subject: [PATCH 4/4] fix(sandbox): relay-guard logs and metrics endpoints Signed-off-by: Eric Curtin --- crates/openshell-core/src/sandbox_env.rs | 6 ++++ crates/openshell-sandbox/README.md | 6 ++-- crates/openshell-sandbox/src/child_env.rs | 36 +++++++++++++++----- crates/openshell-sandbox/src/process.rs | 27 ++++++++++++--- docs/how-it-works/gateways/configuration.mdx | 2 +- 5 files changed, 59 insertions(+), 18 deletions(-) diff --git a/crates/openshell-core/src/sandbox_env.rs b/crates/openshell-core/src/sandbox_env.rs index 185f4d09c8..30607fe577 100644 --- a/crates/openshell-core/src/sandbox_env.rs +++ b/crates/openshell-core/src/sandbox_env.rs @@ -530,6 +530,12 @@ pub const OTEL_EXPORTER_OTLP_PROTOCOL: &str = "OTEL_EXPORTER_OTLP_PROTOCOL"; /// has chosen where traces go, so the relay default is left out. pub const OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: &str = "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"; +/// Logs-specific endpoint variable. Never injected; handled like the traces one. +pub const OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: &str = "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT"; + +/// Metrics-specific endpoint variable. Never injected; handled like the traces one. +pub const OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: &str = "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"; + /// Standard OpenTelemetry environment variable for OTLP exporter compression. /// /// Set to `none` alongside [`OTEL_EXPORTER_OTLP_ENDPOINT`], because the diff --git a/crates/openshell-sandbox/README.md b/crates/openshell-sandbox/README.md index a4a86408bd..f293129c19 100644 --- a/crates/openshell-sandbox/README.md +++ b/crates/openshell-sandbox/README.md @@ -60,10 +60,10 @@ When `AgentSpec::otlp_relay_active` is set, `child_env::apply_otlp_relay_env` gives every workload process (main, exec, and SSH) `OTEL_EXPORTER_OTLP_ENDPOINT` pointing at the relay address, `OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf`, and `none` for `OTEL_EXPORTER_OTLP_COMPRESSION` and the traces, logs, and metrics -compression variables, and removes any inherited -`OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`. These defaults apply after the provider +compression variables, and removes any inherited traces, logs, or +metrics endpoint variable. These defaults apply after the provider variables. If the creation request or a per-exec environment names a generic -or traces-specific OTLP endpoint, the runtime injects nothing, and the +or signal-specific OTLP endpoint, the runtime injects nothing, and the workload exports to that endpoint under the sandbox's network policy. An endpoint in the image `ENV` does the same for the main process; exec children start from a cleared environment (`ChildEnvironment::Cleared`), never see the diff --git a/crates/openshell-sandbox/src/child_env.rs b/crates/openshell-sandbox/src/child_env.rs index b726925d41..6e8e228840 100644 --- a/crates/openshell-sandbox/src/child_env.rs +++ b/crates/openshell-sandbox/src/child_env.rs @@ -7,7 +7,8 @@ use std::path::Path; use openshell_core::sandbox_env::{ OTEL_EXPORTER_OTLP_COMPRESSION, OTEL_EXPORTER_OTLP_ENDPOINT, - OTEL_EXPORTER_OTLP_LOGS_COMPRESSION, OTEL_EXPORTER_OTLP_METRICS_COMPRESSION, + OTEL_EXPORTER_OTLP_LOGS_COMPRESSION, OTEL_EXPORTER_OTLP_LOGS_ENDPOINT, + OTEL_EXPORTER_OTLP_METRICS_COMPRESSION, OTEL_EXPORTER_OTLP_METRICS_ENDPOINT, OTEL_EXPORTER_OTLP_PROTOCOL, OTEL_EXPORTER_OTLP_TRACES_COMPRESSION, OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, OTLP_RELAY_ENDPOINT, }; @@ -48,11 +49,13 @@ pub fn tls_env_vars_for_mode( .collect() } -/// Variables that name where an OpenTelemetry SDK exports traces. A layer of -/// the workload environment that sets one has chosen a destination. -const OTLP_ENDPOINT_VARS: [&str; 2] = [ +/// Variables that name where an OpenTelemetry SDK exports. A layer of the +/// workload environment that sets one has chosen a destination. +const OTLP_ENDPOINT_VARS: [&str; 4] = [ OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, + OTEL_EXPORTER_OTLP_LOGS_ENDPOINT, + OTEL_EXPORTER_OTLP_METRICS_ENDPOINT, ]; /// OpenTelemetry exporter variables that point agent SDKs at the @@ -88,7 +91,7 @@ pub enum ChildEnvironment { } /// Whether one layer of the workload environment names an OTLP endpoint, -/// generic or traces-specific. +/// generic or signal-specific. pub fn names_otlp_endpoint(environment: &HashMap) -> bool { OTLP_ENDPOINT_VARS .iter() @@ -122,8 +125,8 @@ fn relay_default_applies( /// counts for a child that inherits the sandbox environment; a child started /// from a cleared environment never sees the image's endpoint, so the relay /// default still applies to it. When the default is injected, a -/// traces-specific endpoint can only have come from a provider, and is -/// removed so a provider cannot redirect traces. +/// signal-specific endpoint can only have come from a provider, and is +/// removed so a provider cannot redirect that signal. pub fn apply_otlp_relay_env( cmd: &mut impl EnvTarget, relay_active: bool, @@ -136,7 +139,13 @@ pub fn apply_otlp_relay_env( }) { return; } - cmd.remove_var(OTEL_EXPORTER_OTLP_TRACES_ENDPOINT); + for key in [ + OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, + OTEL_EXPORTER_OTLP_LOGS_ENDPOINT, + OTEL_EXPORTER_OTLP_METRICS_ENDPOINT, + ] { + cmd.remove_var(key); + } for (key, value) in otlp_relay_env_vars() { cmd.set_var(key, value); } @@ -271,7 +280,14 @@ mod tests { .map(String::as_str), Some("http://192.0.0.8:4318") ); - assert_eq!(env.removed, ["OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"]); + assert_eq!( + env.removed, + [ + "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", + "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT", + "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT" + ] + ); let mut env = RecordedEnv::default(); apply_otlp_relay_env( @@ -315,6 +331,8 @@ mod tests { for key in [ "OTEL_EXPORTER_OTLP_ENDPOINT", "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", + "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT", + "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT", ] { let value = "http://collector.example:4318".to_string(); let declared = HashMap::from([(key.to_string(), value.clone())]); diff --git a/crates/openshell-sandbox/src/process.rs b/crates/openshell-sandbox/src/process.rs index c62bc8e06a..cd766a1fb2 100644 --- a/crates/openshell-sandbox/src/process.rs +++ b/crates/openshell-sandbox/src/process.rs @@ -1231,6 +1231,8 @@ mod tests { for key in [ openshell_core::sandbox_env::OTEL_EXPORTER_OTLP_ENDPOINT, openshell_core::sandbox_env::OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, + openshell_core::sandbox_env::OTEL_EXPORTER_OTLP_LOGS_ENDPOINT, + openshell_core::sandbox_env::OTEL_EXPORTER_OTLP_METRICS_ENDPOINT, ] { command.env_remove(key); } @@ -1389,7 +1391,8 @@ mod tests { fn canonical_process_sees_relay_endpoint_and_never_the_collector() { use openshell_core::sandbox_env::{ OTEL_EXPORTER_OTLP_COMPRESSION, OTEL_EXPORTER_OTLP_ENDPOINT, - OTEL_EXPORTER_OTLP_LOGS_COMPRESSION, OTEL_EXPORTER_OTLP_METRICS_COMPRESSION, + OTEL_EXPORTER_OTLP_LOGS_COMPRESSION, OTEL_EXPORTER_OTLP_LOGS_ENDPOINT, + OTEL_EXPORTER_OTLP_METRICS_COMPRESSION, OTEL_EXPORTER_OTLP_METRICS_ENDPOINT, OTEL_EXPORTER_OTLP_PROTOCOL, OTEL_EXPORTER_OTLP_TRACES_COMPRESSION, OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, OTLP_RELAY_ENDPOINT, }; @@ -1451,6 +1454,14 @@ mod tests { OTEL_EXPORTER_OTLP_TRACES_ENDPOINT.to_string(), "http://provider.invalid/v1/traces".to_string(), ), + ( + OTEL_EXPORTER_OTLP_LOGS_ENDPOINT.to_string(), + "http://provider.invalid/v1/logs".to_string(), + ), + ( + OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.to_string(), + "http://provider.invalid/v1/metrics".to_string(), + ), ]) }; @@ -1489,10 +1500,16 @@ mod tests { Some("http/protobuf"), "a declared protocol without an endpoint is replaced: {variables:?}" ); - assert!( - !variables.contains_key(OTEL_EXPORTER_OTLP_TRACES_ENDPOINT), - "no signal-specific endpoint is injected, and a provider's is removed: {variables:?}" - ); + for key in [ + OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, + OTEL_EXPORTER_OTLP_LOGS_ENDPOINT, + OTEL_EXPORTER_OTLP_METRICS_ENDPOINT, + ] { + assert!( + !variables.contains_key(key), + "no signal-specific endpoint is injected, and a provider's is removed: {variables:?}" + ); + } assert!( !variables .values() diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index eb8d78fc3f..acbcf1f1ff 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -1117,7 +1117,7 @@ protocol = "http/protobuf" headers = { x-mlflow-experiment-id = "0" } ``` -While the relay is active, the sandbox runtime sets `OTEL_EXPORTER_OTLP_ENDPOINT=http://192.0.0.8:4318` and `OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf` in every workload process, and sets `OTEL_EXPORTER_OTLP_COMPRESSION` and the traces, logs, and metrics compression variables to `none`, so a standard OpenTelemetry SDK exports without configuration. These are lowest-precedence defaults. They are not set when the sandbox creation request or an environment passed to `openshell sandbox exec` names `OTEL_EXPORTER_OTLP_ENDPOINT` or `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`, or when the image `ENV` names one for the main process, since `openshell sandbox exec` sessions do not inherit the image environment, and an endpoint the workload sets itself, for example with a shell `export`, takes precedence over them. A workload that exports elsewhere does so subject to the sandbox's network policy, and its traces carry no relay attribution. Provider credentials cannot redirect traces, but an endpoint variable for logs or metrics that a provider sets still sends that signal past the relay. While the relay is off, nothing is injected. The relay forwards logs and metrics too, so an SDK that exports them, for example with `OTEL_LOGS_EXPORTER=otlp` and `OTEL_METRICS_EXPORTER=otlp`, needs no other setting. The address is a reserved label rather than a network destination: the supervisor serves it inside the sandbox boundary and forwards accepted batches to the collector over the configured `protocol`. The collector's address is never visible inside the sandbox. +While the relay is active, the sandbox runtime sets `OTEL_EXPORTER_OTLP_ENDPOINT=http://192.0.0.8:4318` and `OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf` in every workload process, and sets `OTEL_EXPORTER_OTLP_COMPRESSION` and the traces, logs, and metrics compression variables to `none`, so a standard OpenTelemetry SDK exports without configuration. These are lowest-precedence defaults. They are not set when the sandbox creation request or an environment passed to `openshell sandbox exec` names `OTEL_EXPORTER_OTLP_ENDPOINT` or a traces, logs, or metrics endpoint variable, or when the image `ENV` names one for the main process, since `openshell sandbox exec` sessions do not inherit the image environment, and an endpoint the workload sets itself, for example with a shell `export`, takes precedence over them. A workload that exports elsewhere does so subject to the sandbox's network policy, and its traces carry no relay attribution. Provider credentials cannot redirect traces, logs, or metrics. While the relay is off, nothing is injected. The relay forwards logs and metrics too, so an SDK that exports them, for example with `OTEL_LOGS_EXPORTER=otlp` and `OTEL_METRICS_EXPORTER=otlp`, needs no other setting. The address is a reserved label rather than a network destination: the supervisor serves it inside the sandbox boundary and forwards accepted batches to the collector over the configured `protocol`. The collector's address is never visible inside the sandbox. Every forwarded resource carries `openshell.sandbox.id`, with the same value as the supervisor's own spans, and `openshell.telemetry.source=agent`. Values the agent supplies for those two keys are replaced at the resource level; span and scope attributes pass through unchanged, so filter and join on the resource attributes. Filter on `openshell.telemetry.source` to separate agent telemetry from infrastructure telemetry, and join on `openshell.sandbox.id` to correlate them. The agent can send any log record or metric through the relay, including one that imitates an OCSF event. When `[openshell.gateway.otlp.agent]` and OCSF export share a collector, drop `openshell.telemetry.source=agent` from audit pipelines, or give the agent relay its own `endpoint`.