From a255c8174c3f80a35e52eab87dda16b89a7fd5e1 Mon Sep 17 00:00:00 2001 From: Eitan Geiger Date: Wed, 18 Nov 2026 21:13:28 +0200 Subject: [PATCH 1/6] feat(supervisor-network): measure connections and policy evaluation Count connection admissions at the final decision, including the middleware gate for SQL passthrough. Bound policy-name labels and distinguish quarantine denials from requests that matched no policy. Measure policy evaluation and direct or proxied dials separately, with sub-millisecond buckets for local work. Expose active proxied connections by inspection type and classify upstream proxy authentication failures as connect errors. Signed-off-by: Eitan Geiger --- .../src/l7/relay.rs | 18 +- .../openshell-supervisor-network/src/lib.rs | 1 + .../src/metrics.rs | 508 ++++++++++++++++++ .../openshell-supervisor-network/src/opa.rs | 16 + .../openshell-supervisor-network/src/proxy.rs | 86 +-- .../src/proxy/egress.rs | 24 + .../src/proxy/relay.rs | 20 + .../src/upstream_proxy.rs | 1 + 8 files changed, 641 insertions(+), 33 deletions(-) create mode 100644 crates/openshell-supervisor-network/src/metrics.rs diff --git a/crates/openshell-supervisor-network/src/l7/relay.rs b/crates/openshell-supervisor-network/src/l7/relay.rs index 33d71d867c..530b6482f4 100644 --- a/crates/openshell-supervisor-network/src/l7/relay.rs +++ b/crates/openshell-supervisor-network/src/l7/relay.rs @@ -1444,6 +1444,8 @@ where } L7Protocol::Graphql => relay_graphql(config, &engine, client, upstream, ctx).await, L7Protocol::Sql => { + use crate::metrics::{self, InspectionType, Outcome, Policy, Scope}; + if close_if_stale(engine.generation_guard(), ctx) { return Ok(()); } @@ -1451,15 +1453,25 @@ where // chain can never inspect this stream: gate it like any other // uninspectable protocol. let chain = engine.query_middleware_chain(&middleware_network_input(ctx))?; - match uninspectable_traffic_gate(&chain) { + let outcome = match uninspectable_traffic_gate(&chain) { UninspectableTrafficGate::Deny => { emit_middleware_uninspectable(ctx, "sql passthrough", true); - return Ok(()); + Outcome::Deny } UninspectableTrafficGate::BypassWithFinding => { emit_middleware_uninspectable(ctx, "sql passthrough", false); + Outcome::FailOpen } - UninspectableTrafficGate::Unrestricted => {} + UninspectableTrafficGate::Unrestricted => Outcome::Allow, + }; + metrics::decision( + Scope::Connection, + outcome, + InspectionType::Tcp, + Policy::from(Some(ctx.policy_name.as_str())), + ); + if matches!(outcome, Outcome::Deny) { + return Ok(()); } // SQL provider is Phase 3 — fall through to passthrough with warning { diff --git a/crates/openshell-supervisor-network/src/lib.rs b/crates/openshell-supervisor-network/src/lib.rs index 74a6698b92..f513a53961 100644 --- a/crates/openshell-supervisor-network/src/lib.rs +++ b/crates/openshell-supervisor-network/src/lib.rs @@ -16,6 +16,7 @@ pub mod host; pub mod identity; pub mod identity_source; pub mod l7; +pub mod metrics; pub mod opa; pub(crate) mod policy_dns; pub mod policy_local; diff --git a/crates/openshell-supervisor-network/src/metrics.rs b/crates/openshell-supervisor-network/src/metrics.rs new file mode 100644 index 0000000000..8bf53544fa --- /dev/null +++ b/crates/openshell-supervisor-network/src/metrics.rs @@ -0,0 +1,508 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Bounded, process-wide supervisor egress metrics. + +use std::collections::HashSet; +use std::future::Future; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::Instant; + +use opentelemetry::metrics::{Counter, Histogram, Meter, ObservableGauge}; +use opentelemetry::{Context, KeyValue}; + +use crate::l7::L7Protocol; + +const LATENCY_BUCKETS_SECONDS: [f64; 17] = [ + 0.0001, 0.00025, 0.0005, 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, + 5.0, 10.0, 15.0, +]; +const MAX_POLICY_NAMES: usize = 16; +const MAX_POLICY_NAME_BYTES: usize = 128; + +static METRICS: OnceLock = OnceLock::new(); + +/// Installs the process's egress instruments before starting any proxies. +pub fn install(meter: &Meter) { + METRICS.get_or_init(|| Metrics::new(meter)); +} + +#[derive(Debug, Clone, Copy)] +pub(crate) enum Scope { + Connection, +} + +impl Scope { + fn label(self) -> &'static str { + match self { + Self::Connection => "connection", + } + } +} + +#[derive(Debug, Clone, Copy)] +pub(crate) enum InspectionType { + Tcp, + Http, + Rest, + Graphql, + JsonRpc, + Mcp, + Websocket, + Unknown, +} + +impl InspectionType { + const ALL: [Self; 8] = [ + Self::Tcp, + Self::Http, + Self::Rest, + Self::Graphql, + Self::JsonRpc, + Self::Mcp, + Self::Websocket, + Self::Unknown, + ]; + + pub(crate) fn from_protocol(protocol: L7Protocol) -> Self { + match protocol { + L7Protocol::Rest => Self::Rest, + L7Protocol::Graphql => Self::Graphql, + L7Protocol::JsonRpc => Self::JsonRpc, + L7Protocol::Mcp => Self::Mcp, + L7Protocol::Websocket => Self::Websocket, + L7Protocol::Sql => Self::Tcp, // The SQL route uses raw passthrough. + } + } + + pub(crate) fn label(self) -> &'static str { + match self { + Self::Tcp => "tcp", + Self::Http => "http", + Self::Rest => "rest", + Self::Graphql => "graphql", + Self::JsonRpc => "json-rpc", + Self::Mcp => "mcp", + Self::Websocket => "websocket", + Self::Unknown => "unknown", + } + } +} + +#[derive(Debug, Clone, Copy)] +pub(crate) enum Outcome { + Allow, + Deny, + FailOpen, +} + +impl Outcome { + pub(crate) fn label(self) -> &'static str { + match self { + Self::Allow => "allow", + Self::Deny => "deny", + Self::FailOpen => "fail_open", + } + } +} + +#[derive(Debug, Clone, Copy)] +pub(crate) enum ResultLabel { + Success, + Deny, + Error, + Timeout, + Cancelled, +} + +impl ResultLabel { + pub(crate) fn label(self) -> &'static str { + match self { + Self::Success => "success", + Self::Deny => "deny", + Self::Error => "error", + Self::Timeout => "timeout", + Self::Cancelled => "cancelled", + } + } + + pub(crate) fn from_io_error(error: &std::io::Error) -> Self { + match error.kind() { + std::io::ErrorKind::TimedOut => Self::Timeout, + _ => Self::Error, + } + } +} + +#[derive(Debug, Clone, Copy)] +pub(crate) enum Route { + Direct, + Proxy, +} + +impl Route { + fn label(self) -> &'static str { + match self { + Self::Direct => "direct", + Self::Proxy => "proxy", + } + } +} + +pub(crate) enum Policy<'a> { + Named(&'a str), + NoMatch, + Unattributed, +} + +impl<'a> From> for Policy<'a> { + fn from(name: Option<&'a str>) -> Self { + name.filter(|name| !name.is_empty() && *name != "-") + .map_or(Self::Unattributed, Self::Named) + } +} + +struct Metrics { + decisions: Counter, + policy_evaluation: Histogram, + upstream_connect: Histogram, + policy_names: Mutex>>, + connections: Arc<[AtomicU64; InspectionType::ALL.len()]>, + _active_connections: ObservableGauge, +} + +impl Metrics { + fn new(meter: &Meter) -> Self { + let histogram = |name, description| { + meter + .f64_histogram(name) + .with_description(description) + .with_unit("s") + .with_boundaries(LATENCY_BUCKETS_SECONDS.to_vec()) + .build() + }; + let connections: Arc<[AtomicU64; InspectionType::ALL.len()]> = + Arc::new(std::array::from_fn(|_| AtomicU64::new(0))); + let active = Arc::clone(&connections); + let active_connections = meter + .u64_observable_gauge("openshell_supervisor_connections_active") + .with_description("Live proxied connections.") + .with_callback(move |observer| { + for inspection in InspectionType::ALL { + observer.observe( + active[inspection as usize].load(Ordering::Relaxed), + &[KeyValue::new("inspection_type", inspection.label())], + ); + } + }) + .build(); + Self { + decisions: meter + .u64_counter("openshell_supervisor_egress_decisions_total") + .with_description("Final egress admission decisions.") + .build(), + policy_evaluation: histogram( + "openshell_supervisor_policy_evaluation_duration_seconds", + "Time spent evaluating egress policy.", + ), + upstream_connect: histogram( + "openshell_supervisor_upstream_connect_duration_seconds", + "Time spent establishing an upstream connection.", + ), + policy_names: Mutex::new(HashSet::new()), + connections, + _active_connections: active_connections, + } + } + + fn policy_label(&self, policy: Policy<'_>) -> Arc { + let name = match policy { + Policy::NoMatch => return Arc::from("no_match"), + Policy::Unattributed => return Arc::from("unattributed"), + Policy::Named(name) if name.len() > MAX_POLICY_NAME_BYTES => { + return Arc::from("overflow"); + } + Policy::Named(name) => name, + }; + let mut names = self + .policy_names + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let name = if matches!(name, "no_match" | "unattributed" | "overflow") + || name.starts_with("name:") + { + std::borrow::Cow::Owned(format!("name:{name}")) + } else { + std::borrow::Cow::Borrowed(name) + }; + if let Some(existing) = names.get(name.as_ref()) { + return Arc::clone(existing); + } + if names.len() >= MAX_POLICY_NAMES { + return Arc::from("overflow"); + } + let name = Arc::::from(name.as_ref()); + names.insert(Arc::clone(&name)); + name + } +} + +pub(crate) fn decision( + scope: Scope, + outcome: Outcome, + inspection: InspectionType, + policy: Policy<'_>, +) { + if let Some(metrics) = METRICS.get() { + metrics.decisions.add( + 1, + &[ + KeyValue::new("scope", scope.label()), + KeyValue::new("outcome", outcome.label()), + KeyValue::new("inspection_type", inspection.label()), + KeyValue::new("policy", metrics.policy_label(policy)), + ], + ); + } +} + +pub(crate) struct ActiveConnection(Option<&'static AtomicU64>); + +impl ActiveConnection { + pub(crate) fn new(inspection: InspectionType) -> Self { + let count = METRICS + .get() + .map(|metrics| &metrics.connections[inspection as usize]); + if let Some(count) = count { + count.fetch_add(1, Ordering::Relaxed); + } + Self(count) + } +} + +impl Drop for ActiveConnection { + fn drop(&mut self) { + if let Some(count) = self.0 { + count.fetch_sub(1, Ordering::Relaxed); + } + } +} + +#[derive(Debug, Clone, Copy)] +pub(crate) enum Stage { + PolicyEvaluation(Scope), + UpstreamConnect(Route), +} + +pub(crate) async fn connect( + route: Route, + operation: impl Future>, +) -> std::io::Result { + let timer = Timer::new(Stage::UpstreamConnect(route)); + let result = operation.await; + let label = result + .as_ref() + .map_or_else(ResultLabel::from_io_error, |_| ResultLabel::Success); + tracing::Span::current().record("openshell.egress.result", label.label()); + timer.finish(label); + result +} + +pub(crate) fn evaluate( + scope: Scope, + operation: impl FnOnce() -> Result, + allowed: impl FnOnce(&T) -> bool, +) -> Result { + let timer = Timer::new(Stage::PolicyEvaluation(scope)); + let decision = operation(); + let result = match decision.as_ref().map(allowed) { + Ok(true) => ResultLabel::Success, + Ok(false) => ResultLabel::Deny, + Err(_) => ResultLabel::Error, + }; + tracing::Span::current().record("openshell.egress.result", result.label()); + timer.finish(result); + decision +} + +#[derive(Debug)] +pub(crate) struct Timer { + stage: Stage, + start: Option<(Instant, Context)>, +} + +impl Timer { + pub(crate) fn new(stage: Stage) -> Self { + Self { + stage, + start: METRICS.get().map(|_| (Instant::now(), Context::current())), + } + } + + pub(crate) fn finish(mut self, result: ResultLabel) { + self.record(result); + } + + fn record(&mut self, result: ResultLabel) { + let (Some(metrics), Some((started, context))) = (METRICS.get(), self.start.take()) else { + return; + }; + let seconds = started.elapsed().as_secs_f64(); + let _active_context = context.attach(); + let result = KeyValue::new("result", result.label()); + match self.stage { + Stage::PolicyEvaluation(scope) => { + metrics + .policy_evaluation + .record(seconds, &[KeyValue::new("scope", scope.label()), result]); + } + Stage::UpstreamConnect(route) => { + metrics + .upstream_connect + .record(seconds, &[KeyValue::new("route", route.label()), result]); + } + } + } +} + +impl Drop for Timer { + fn drop(&mut self) { + self.record(ResultLabel::Cancelled); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use opentelemetry::metrics::MeterProvider as _; + use opentelemetry_sdk::metrics::data::{AggregatedMetrics, MetricData}; + use opentelemetry_sdk::metrics::{InMemoryMetricExporter, PeriodicReader, SdkMeterProvider}; + + #[test] + fn policy_labels_are_bounded_for_the_process_lifetime() { + let provider = SdkMeterProvider::builder().build(); + let metrics = Metrics::new(&provider.meter("supervisor-metrics-test")); + + assert_eq!(&*metrics.policy_label(Policy::NoMatch), "no_match"); + assert_eq!(&*metrics.policy_label(Policy::Unattributed), "unattributed"); + for policy in ["overflow", "no_match", "unattributed", "name:overflow"] { + assert_eq!( + &*metrics.policy_label(Policy::Named(policy)), + format!("name:{policy}"), + ); + } + for index in 4..MAX_POLICY_NAMES { + let policy = index.to_string(); + assert_eq!(&*metrics.policy_label(Policy::Named(&policy)), policy); + } + assert_eq!(&*metrics.policy_label(Policy::Named("16")), "overflow"); + assert_eq!(&*metrics.policy_label(Policy::Named("4")), "4"); + } + + #[tokio::test] + async fn histograms_and_decisions_record_without_a_sampled_span() { + let exporter = InMemoryMetricExporter::default(); + let reader = PeriodicReader::builder(exporter.clone()).build(); + let provider = SdkMeterProvider::builder().with_reader(reader).build(); + install(&provider.meter("supervisor-metrics-test")); + + let connection = ActiveConnection::new(InspectionType::Unknown); + Timer::new(Stage::PolicyEvaluation(Scope::Connection)).finish(ResultLabel::Deny); + drop(Timer::new(Stage::UpstreamConnect(Route::Proxy))); + for kind in [ + std::io::ErrorKind::PermissionDenied, + std::io::ErrorKind::TimedOut, + ] { + let error = connect(Route::Proxy, async { Err::<(), _>(kind.into()) }) + .await + .unwrap_err(); + assert_eq!(error.kind(), kind); + } + decision( + Scope::Connection, + Outcome::Deny, + InspectionType::Unknown, + Policy::Unattributed, + ); + provider.force_flush().unwrap(); + + let records = exporter.get_finished_metrics().unwrap(); + let instruments = records[0] + .scope_metrics() + .flat_map(|scope| scope.metrics()) + .collect::>(); + for (name, result) in [ + ( + "openshell_supervisor_policy_evaluation_duration_seconds", + "deny", + ), + ( + "openshell_supervisor_upstream_connect_duration_seconds", + "cancelled", + ), + ( + "openshell_supervisor_upstream_connect_duration_seconds", + "error", + ), + ( + "openshell_supervisor_upstream_connect_duration_seconds", + "timeout", + ), + ] { + let histogram = instruments + .iter() + .find(|metric| metric.name() == name) + .unwrap(); + let AggregatedMetrics::F64(MetricData::Histogram(histogram)) = histogram.data() else { + panic!("{name} should export an explicit histogram"); + }; + assert!(histogram.data_points().any(|point| { + point.count() > 0 + && point.bounds().eq(LATENCY_BUCKETS_SECONDS) + && point + .attributes() + .any(|kv| kv.key.as_str() == "result" && kv.value.as_str() == result) + })); + } + let decisions = instruments + .iter() + .find(|metric| metric.name() == "openshell_supervisor_egress_decisions_total") + .unwrap(); + let AggregatedMetrics::U64(MetricData::Sum(decisions)) = decisions.data() else { + panic!("Decision counter should export a sum"); + }; + assert!(decisions.is_monotonic()); + assert!(decisions.data_points().any(|point| point.value() > 0)); + + let active_connections = + |records: &[opentelemetry_sdk::metrics::data::ResourceMetrics]| { + let gauge = records + .last() + .unwrap() + .scope_metrics() + .flat_map(|scope| scope.metrics()) + .find(|metric| metric.name() == "openshell_supervisor_connections_active") + .unwrap(); + let AggregatedMetrics::U64(MetricData::Gauge(gauge)) = gauge.data() else { + panic!("Connection count should export a gauge"); + }; + gauge + .data_points() + .find(|point| { + point.attributes().any(|kv| { + kv.key.as_str() == "inspection_type" && kv.value.as_str() == "unknown" + }) + }) + .unwrap() + .value() + }; + assert_eq!(active_connections(&records), 1); + drop(connection); + provider.force_flush().unwrap(); + assert_eq!( + active_connections(&exporter.get_finished_metrics().unwrap()), + 0 + ); + } +} diff --git a/crates/openshell-supervisor-network/src/opa.rs b/crates/openshell-supervisor-network/src/opa.rs index 72748c8027..c50ba852b9 100644 --- a/crates/openshell-supervisor-network/src/opa.rs +++ b/crates/openshell-supervisor-network/src/opa.rs @@ -134,6 +134,8 @@ pub struct PolicyDnsEligibilitySnapshot { #[derive(Debug, Clone)] pub struct EgressAuthorization { pub action: NetworkAction, + /// Whether the policy engine evaluated the request. + pub(crate) policy_evaluated: bool, pub endpoint_configs: Vec, pub matched_endpoints: Vec, pub exact_declared_endpoint_host: bool, @@ -630,6 +632,15 @@ impl OpaEngine { /// Authorize egress and return all connection metadata from one Rego result /// evaluated against one policy generation. pub fn authorize_egress(&self, input: &NetworkInput) -> Result { + use crate::metrics::{Scope, evaluate}; + evaluate( + Scope::Connection, + || self.authorize_egress_inner(input), + |decision| matches!(decision.action, NetworkAction::Allow { .. }), + ) + } + + fn authorize_egress_inner(&self, input: &NetworkInput) -> Result { #[cfg(test)] record_test_opa_query(); @@ -649,6 +660,7 @@ impl OpaEngine { if let Some(reason) = fail_closed_reason { return Ok(EgressAuthorization { action: NetworkAction::Deny { reason }, + policy_evaluated: false, endpoint_configs: Vec::new(), matched_endpoints: Vec::new(), exact_declared_endpoint_host: false, @@ -688,6 +700,7 @@ impl OpaEngine { Ok(EgressAuthorization { action, + policy_evaluated: true, endpoint_configs, matched_endpoints, exact_declared_endpoint_host, @@ -9052,6 +9065,9 @@ network_policies: reason: "candidate policy validation failed: conflicting tls".to_string() } ); + let authorization = engine.authorize_egress(&input).unwrap(); + assert_eq!(authorization.action, action); + assert!(!authorization.policy_evaluated); } #[test] diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index 3a1e381e33..ca879be9c3 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -17,6 +17,7 @@ use openshell_sandbox_backend::test_support as rpc_test; use crate::identity::{BinaryIdentityCache, SuppliedIdentityError}; use crate::l7::correlation::{HttpOutcome, RequestStage}; use crate::l7::tls::ProxyTlsState; +use crate::metrics::{InspectionType, Outcome, Scope}; use crate::opa::{NetworkAction, OpaEngine, PolicyGenerationGuard}; #[cfg(test)] use crate::policy_dns::SocketTrustedResolver; @@ -824,6 +825,7 @@ async fn preauthorize_transparent_open( }); let mut decision = supplied_authorization.decision; if let NetworkAction::Deny { reason } = &decision.action { + decision.record_admission(Scope::Connection, Outcome::Deny, InspectionType::Unknown); let (denial, status_detail) = supplied_authorization.denial.map_or( (TcpOpenDenial::PolicyDenied, "transparent_tcp_policy_denied"), |denial| match denial { @@ -1266,6 +1268,7 @@ async fn handle_transparent_tcp_connection( .map_err(|error| miette::miette!("identity resolution task panicked: {error}"))?; if let NetworkAction::Deny { reason } = &decision.action { + decision.record_admission(Scope::Connection, Outcome::Deny, InspectionType::Tcp); emit_transparent_policy_denial(&decision, workload_addr, &host, port); emit_denial( &denial_tx, @@ -1454,6 +1457,7 @@ async fn handle_transparent_tcp_connection( } )); emit_activity(&activity_tx, false, "transparent_tcp"); + decision.record_admission(Scope::Connection, Outcome::Allow, InspectionType::Tcp); relay::relay_tcp(&mut client, &mut upstream, &generation_guard, &ctx).await } @@ -2410,6 +2414,7 @@ async fn deny_connect_destination( where C: TokioAsyncWrite + Unpin, { + decision.record_admission(Scope::Connection, Outcome::Deny, InspectionType::Unknown); let detail = destination_denial_detail(denial.kind); egress_emit!(build_connect_destination_deny_ocsf_event( denial, peer_addr, host, port, binary, pid, ancestors, cmdline, @@ -2927,6 +2932,7 @@ async fn handle_mediated_connection( // Allowed connections are logged after the L7 config check (below) // so we can distinguish CONNECT (L4-only) from CONNECT_L7 (L7 follows). if matches!(decision.action, NetworkAction::Deny { .. }) { + decision.record_admission(Scope::Connection, Outcome::Deny, InspectionType::Unknown); let event = NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(ActivityId::Open) .action(ActionId::Denied) @@ -3106,6 +3112,7 @@ async fn handle_mediated_connection( if refuse_connect_when_tls_unavailable(&mut client, tls_state.is_some(), effective_tls_skip) .await? { + decision.record_admission(Scope::Connection, Outcome::Deny, InspectionType::Unknown); if let Some(observer) = connect_endpoint_observer.as_ref() { observer.observe(EndpointResult::TlsFailed); } @@ -3216,9 +3223,11 @@ async fn handle_mediated_connection( // Gate a `tls: skip` tunnel before `200 Connection Established`, so a // denial is a plain 403. Policy validation rejects fail-closed middleware // overlapping `tls: skip` endpoints; this runtime gate is defense in depth. + let mut raw_admission = Outcome::Allow; if effective_tls_skip { match middleware_uninspectable_gate(&opa_engine, &ctx)? { crate::l7::middleware::UninspectableTrafficGate::Deny => { + decision.record_admission(Scope::Connection, Outcome::Deny, InspectionType::Tcp); crate::l7::middleware::emit_middleware_uninspectable(&ctx, "tls-skip tunnel", true); respond( &mut client, @@ -3233,6 +3242,7 @@ async fn handle_mediated_connection( return Ok(()); } crate::l7::middleware::UninspectableTrafficGate::BypassWithFinding => { + raw_admission = Outcome::FailOpen; crate::l7::middleware::emit_middleware_uninspectable( &ctx, "tls-skip tunnel", @@ -3317,6 +3327,7 @@ async fn handle_mediated_connection( else { return Ok(()); }; + decision.record_admission(Scope::Connection, raw_admission, InspectionType::Tcp); relay::relay_tcp(&mut client, &mut upstream, &generation_guard, &ctx).await?; return Ok(()); } @@ -3475,6 +3486,7 @@ async fn handle_mediated_connection( if let Some(protocol_detail) = unsupported_l7_tunnel_protocol_detail(tunnel_protocol, requirement) { + decision.record_admission(Scope::Connection, Outcome::Deny, InspectionType::Unknown); if requirement == InspectionRequirement::RequiredMiddleware { crate::l7::middleware::emit_middleware_uninspectable(&ctx, protocol_detail, true); } @@ -3533,6 +3545,14 @@ async fn handle_mediated_connection( else { return Ok(()); }; + let outcome = if middleware_gate + == crate::l7::middleware::UninspectableTrafficGate::BypassWithFinding + { + Outcome::FailOpen + } else { + Outcome::Allow + }; + decision.record_admission(Scope::Connection, outcome, InspectionType::Tcp); relay::relay_tcp(&mut client, &mut upstream, &generation_guard, &ctx).await?; } @@ -4745,33 +4765,30 @@ async fn dial_upstream( port: u16, addrs: &[SocketAddr], ) -> std::io::Result { + use crate::metrics::{Route, connect}; + if let Some(cfg) = upstream_proxy.as_ref() { return match cfg.decision(host_lc, port, addrs) { upstream_proxy::ProxyDecision::Proxy(endpoint) => { - if cfg.connect_by_hostname() { - upstream_proxy::connect_via( - endpoint, - raw_host_lc, - port, - upstream_proxy::ConnectTarget::Hostname, - ) - .await - } else { - // Try every validated address in order, matching the - // fallback the direct path's `TcpStream::connect` does. - upstream_proxy::connect_via_validated(endpoint, host_lc, port, addrs).await - } - } - upstream_proxy::ProxyDecision::Direct(direct_addrs) => { - Ok(upstream_proxy::PrefixedStream::without_prefix( - connect_tcp_nodelay_best_effort(&direct_addrs[..]).await?, - )) + connect(Route::Proxy, async { + if cfg.connect_by_hostname() { + upstream_proxy::connect_via( + endpoint, + raw_host_lc, + port, + upstream_proxy::ConnectTarget::Hostname, + ) + .await + } else { + upstream_proxy::connect_via_validated(endpoint, host_lc, port, addrs).await + } + }) + .await } + upstream_proxy::ProxyDecision::Direct(direct_addrs) => dial_direct(&direct_addrs).await, }; } - Ok(upstream_proxy::PrefixedStream::without_prefix( - connect_tcp_nodelay_best_effort(addrs).await?, - )) + dial_direct(addrs).await } /// Dial a policy-DNS-correlated transparent TCP destination. @@ -4787,21 +4804,30 @@ async fn dial_transparent_upstream( port: u16, addrs: &[SocketAddr], ) -> std::io::Result { + use crate::metrics::{Route, connect}; + if let Some(cfg) = upstream_proxy.as_ref() { return match cfg.decision(host_lc, port, addrs) { upstream_proxy::ProxyDecision::Proxy(endpoint) => { - upstream_proxy::connect_via_validated(endpoint, host_lc, port, addrs).await - } - upstream_proxy::ProxyDecision::Direct(direct_addrs) => { - Ok(upstream_proxy::PrefixedStream::without_prefix( - connect_tcp_nodelay_best_effort(&direct_addrs[..]).await?, - )) + connect( + Route::Proxy, + upstream_proxy::connect_via_validated(endpoint, host_lc, port, addrs), + ) + .await } + upstream_proxy::ProxyDecision::Direct(direct_addrs) => dial_direct(&direct_addrs).await, }; } - Ok(upstream_proxy::PrefixedStream::without_prefix( - connect_tcp_nodelay_best_effort(addrs).await?, - )) + dial_direct(addrs).await +} + +async fn dial_direct(addrs: &[SocketAddr]) -> std::io::Result { + crate::metrics::connect( + crate::metrics::Route::Direct, + connect_tcp_nodelay_best_effort(addrs), + ) + .await + .map(upstream_proxy::PrefixedStream::without_prefix) } /// Resolve a host:port using the supervisor resolver, then reject if any diff --git a/crates/openshell-supervisor-network/src/proxy/egress.rs b/crates/openshell-supervisor-network/src/proxy/egress.rs index 77b89a9b7e..9e8f6c7a23 100644 --- a/crates/openshell-supervisor-network/src/proxy/egress.rs +++ b/crates/openshell-supervisor-network/src/proxy/egress.rs @@ -44,6 +44,8 @@ pub(super) struct EndpointDecision { pub(super) matched_endpoints: Vec, /// Whether policy matched the requested hostname exactly (not by glob). pub(super) exact_declared_host: bool, + /// Whether this snapshot came from a completed evaluator call. + policy_evaluated: bool, } impl Default for EndpointDecision { @@ -55,6 +57,7 @@ impl Default for EndpointDecision { policy_configs: Vec::new(), matched_endpoints: Vec::new(), exact_declared_host: false, + policy_evaluated: false, } } } @@ -65,6 +68,7 @@ impl EndpointDecision { policy_configs: authorization.endpoint_configs.clone(), matched_endpoints: authorization.matched_endpoints.clone(), exact_declared_host: authorization.exact_declared_endpoint_host, + policy_evaluated: authorization.policy_evaluated, ..Self::default() } } @@ -170,6 +174,24 @@ pub(super) struct EgressDecision { pub(super) cmdline_paths: Vec, } +impl EgressDecision { + pub(super) fn record_admission( + &self, + scope: crate::metrics::Scope, + outcome: crate::metrics::Outcome, + inspection_type: crate::metrics::InspectionType, + ) { + use crate::metrics::Policy; + + let policy = match &self.action { + NetworkAction::Allow { matched_policy } => Policy::from(matched_policy.as_deref()), + NetworkAction::Deny { .. } if self.endpoint.policy_evaluated => Policy::NoMatch, + NetworkAction::Deny { .. } => Policy::Unattributed, + }; + crate::metrics::decision(scope, outcome, inspection_type, policy); + } +} + pub(super) fn connect_span(intent: &EgressIntent) -> tracing::Span { tracing::debug_span!( "supervisor.egress.connect", @@ -187,6 +209,7 @@ pub(super) fn dial_span(parent: &tracing::Span) -> tracing::Span { tracing::debug_span!( parent: parent, "supervisor.egress.dial", + openshell.egress.result = tracing::field::Empty, otel.status_code = tracing::field::Empty, ) } @@ -206,6 +229,7 @@ pub(super) fn traced_authorization( "supervisor.egress.authorize", openshell.policy.decision = tracing::field::Empty, openshell.policy.name = tracing::field::Empty, + openshell.egress.result = tracing::field::Empty, ); let result = span.in_scope(|| authorize(intent)); match &decision(&result).action { diff --git a/crates/openshell-supervisor-network/src/proxy/relay.rs b/crates/openshell-supervisor-network/src/proxy/relay.rs index e53e546d81..f91c5b7a53 100644 --- a/crates/openshell-supervisor-network/src/proxy/relay.rs +++ b/crates/openshell-supervisor-network/src/proxy/relay.rs @@ -257,6 +257,25 @@ where C: AsyncRead + AsyncWrite + Unpin + Send, U: AsyncRead + AsyncWrite + Unpin + Send, { + use crate::metrics::{self, ActiveConnection, InspectionType, Outcome, Policy, Scope}; + + let protocol = match &context.policy { + PreparedHttpPolicy::Inspect { configs, .. } if configs.len() == 1 => { + Some(configs[0].protocol) + } + _ => None, + }; + let inspection = protocol.map_or(InspectionType::Http, InspectionType::from_protocol); + let _connection = ActiveConnection::new(inspection); + if protocol != Some(crate::l7::L7Protocol::Sql) { + metrics::decision( + Scope::Connection, + Outcome::Allow, + inspection, + Policy::from(Some(context.request.policy_name.as_str())), + ); + } + match context.policy { PreparedHttpPolicy::Inspect { configs, evaluator } if configs.len() == 1 => { let generation_guard = evaluator.generation_guard().clone(); @@ -348,6 +367,7 @@ where C: AsyncRead + AsyncWrite + Unpin, U: AsyncRead + AsyncWrite + Unpin, { + let _connection = crate::metrics::ActiveConnection::new(crate::metrics::InspectionType::Tcp); tokio::select! { result = tokio::io::copy_bidirectional(client, upstream) => { result.into_diagnostic()?; diff --git a/crates/openshell-supervisor-network/src/upstream_proxy.rs b/crates/openshell-supervisor-network/src/upstream_proxy.rs index 86b1ddf770..29a6b24fc2 100644 --- a/crates/openshell-supervisor-network/src/upstream_proxy.rs +++ b/crates/openshell-supervisor-network/src/upstream_proxy.rs @@ -2188,6 +2188,7 @@ mod tests { let err = connect_via(&endpoint, "api.example.com", 443, ConnectTarget::Hostname) .await .unwrap_err(); + assert_eq!(err.kind(), ErrorKind::Other); assert!(err.to_string().contains("407"), "{err}"); } From 90e70dccf778203a5de520e49b0d8c67cb7f963f Mon Sep 17 00:00:00 2001 From: Eitan Geiger Date: Wed, 18 Nov 2026 21:13:28 +0200 Subject: [PATCH 2/6] feat(supervisor-network): measure request and message inspection Record one final admission per inspected HTTP request or WebSocket text message. An enforced denial takes precedence over fail-open, which takes precedence over audit. Time inspection up to forwarding or a terminal result, excluding destination lookup and dial time. Classify a failed forward dial as an error or timeout and malformed WebSocket messages as inspection errors. Signed-off-by: Eitan Geiger --- .../src/l7/correlation.rs | 89 ++++++++- .../src/l7/middleware.rs | 10 + .../src/l7/relay.rs | 74 +++++--- .../src/l7/request_trace.rs | 85 +++++++++ .../src/l7/rest.rs | 9 + .../src/l7/websocket.rs | 177 +++++++++++++++--- .../src/metrics.rs | 61 +++++- .../openshell-supervisor-network/src/proxy.rs | 35 +++- .../src/proxy/tests/request_trace.rs | 31 ++- 9 files changed, 505 insertions(+), 66 deletions(-) diff --git a/crates/openshell-supervisor-network/src/l7/correlation.rs b/crates/openshell-supervisor-network/src/l7/correlation.rs index 1d4cfe36fa..23318faa95 100644 --- a/crates/openshell-supervisor-network/src/l7/correlation.rs +++ b/crates/openshell-supervisor-network/src/l7/correlation.rs @@ -83,6 +83,12 @@ pub fn record_current_failure(outcome: HttpOutcome, reason: &'static str) { } } +pub(super) fn note_current_fail_open() { + if let Some(scope) = current_request() { + scope.note_admission(crate::metrics::Outcome::FailOpen); + } +} + fn enrich_request(event: &mut openshell_ocsf::BaseEventData) { let Some(scope) = current_request().filter(|scope| scope.inspected) else { return; @@ -96,6 +102,19 @@ fn enrich_request(event: &mut openshell_ocsf::BaseEventData) { .entry("http_event_kind") .or_insert_with(|| event_kind.into()); fields.insert("request_sequence".into(), sequence.into()); + let finished_inspection = scope + .trace + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_ref() + .and_then(RequestTrace::finished_inspection); + if let Some((inspection, result, outcome)) = finished_inspection { + fields.insert("egress_inspection_type".into(), inspection.label().into()); + fields.insert("egress_result".into(), result.label().into()); + if let Some(outcome) = outcome { + fields.insert("egress_outcome".into(), outcome.label().into()); + } + } } } @@ -137,6 +156,17 @@ impl RequestScope { .map_or_else(tracing::Span::none, RequestTrace::span) } + fn note_admission(&self, outcome: crate::metrics::Outcome) { + if let Some(trace) = self + .trace + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_mut() + { + trace.note_admission(outcome); + } + } + fn record_failure(&self, outcome: HttpOutcome, reason: &'static str) { if let Some(trace) = self .trace @@ -144,6 +174,9 @@ impl RequestScope { .unwrap_or_else(std::sync::PoisonError::into_inner) .as_mut() { + if reason == "policy_reloaded" { + trace.finish_inspection(crate::metrics::ResultLabel::Cancelled); + } trace.record_outcome(outcome); trace.record_failure_reason(reason); } @@ -257,7 +290,8 @@ impl RequestCorrelation { } fn build(method: &str, raw_header: &[u8], ctx: &L7EvalContext, request_id: String) -> Self { - let trace = RequestTrace::new(&request_id, method, &ctx.host, ctx.port, raw_header); + let mut trace = RequestTrace::new(&request_id, method, &ctx.host, ctx.port, raw_header); + trace.start_inspection(&ctx.policy_name); Self::install(RequestScope { request_id, inspected: true, @@ -295,6 +329,7 @@ impl RequestCorrelation { .unwrap_or_else(std::sync::PoisonError::into_inner) .as_mut() { + trace.finish_inspection(crate::metrics::ResultLabel::Error); trace.record_unclassified_failure(); } let captured = CapturedRequestError { @@ -314,6 +349,50 @@ impl RequestCorrelation { .map_or_else(tracing::Span::none, |trace| trace.stage(stage)) } + pub(crate) fn select_inspector(&self, protocol: crate::l7::L7Protocol, policy: &str) { + if let Some(trace) = self + .scope + .trace + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_mut() + { + trace.select_inspector( + crate::metrics::InspectionType::from_protocol(protocol), + policy, + ); + } + } + + pub(crate) fn note_admission(&self, outcome: crate::metrics::Outcome) { + self.scope.note_admission(outcome); + } + + pub(crate) fn inspection_timer(&self, update: impl FnOnce(&mut crate::metrics::Timer)) { + if let Some(timer) = self + .scope + .trace + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_mut() + .and_then(RequestTrace::inspection_timer) + { + update(timer); + } + } + + pub(crate) fn finish_inspection(&self, result: crate::metrics::ResultLabel) { + if let Some(trace) = self + .scope + .trace + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_mut() + { + trace.finish_inspection(result); + } + } + /// Record a stage's actual result without exporting its potentially /// sensitive error value or changing cancellation behavior. pub(crate) fn run_stage( @@ -430,6 +509,14 @@ impl RequestCorrelation { outcome: HttpOutcome, reason: Option<&'static str>, ) { + if matches!(outcome, HttpOutcome::PlatformError) { + let result = if matches!(status, 408 | 504) { + crate::metrics::ResultLabel::Timeout + } else { + crate::metrics::ResultLabel::Error + }; + self.finish_inspection(result); + } self.record_outcome(outcome); self.record_response_status(status); if let Some(reason) = reason { diff --git a/crates/openshell-supervisor-network/src/l7/middleware.rs b/crates/openshell-supervisor-network/src/l7/middleware.rs index 52c6dbe967..07a51ffede 100644 --- a/crates/openshell-supervisor-network/src/l7/middleware.rs +++ b/crates/openshell-supervisor-network/src/l7/middleware.rs @@ -1155,6 +1155,9 @@ async fn apply_protocol1_middleware_chain Vec { let applied = diagnostics.applied(); + if allowed && applied.iter().any(|invocation| invocation.failed) { + crate::l7::correlation::note_current_fail_open(); + } let req = crate::l7::provider::L7Request { action: action.to_string(), target: target.to_string(), @@ -2079,6 +2088,7 @@ pub(super) fn resolve_unbuffered_body( .iter() .all(|entry| entry.on_error() == openshell_supervisor_middleware::OnError::FailOpen); if recoverable && all_fail_open { + crate::l7::correlation::note_current_fail_open(); emit_middleware_body_unavailable(ctx, false); return MiddlewareApplyResult::Allowed(req); } diff --git a/crates/openshell-supervisor-network/src/l7/relay.rs b/crates/openshell-supervisor-network/src/l7/relay.rs index 530b6482f4..7db7b6c7a4 100644 --- a/crates/openshell-supervisor-network/src/l7/relay.rs +++ b/crates/openshell-supervisor-network/src/l7/relay.rs @@ -1609,6 +1609,7 @@ where .map_err(&capture_error)?; return Ok(()); }; + correlation.select_inspector(config.protocol, &ctx.policy_name); let observer = EndpointObserver::begin_captured( ctx.endpoint_observation_tx.as_ref(), config, @@ -1816,12 +1817,12 @@ where return Ok(()); } - let decision_str = match (allowed, config.enforcement) { - (_, _) if force_deny => "deny", - (true, _) => "allow", - (false, EnforcementMode::Audit) => "audit", - (false, EnforcementMode::Enforce) => "deny", - }; + let admission = crate::metrics::Outcome::policy( + allowed, + force_deny || config.enforcement == EnforcementMode::Enforce, + ); + correlation.note_admission(admission); + let decision_str = admission.label(); let engine_type = engine_type_for_protocol(config.protocol); let protocol_summary = l7_protocol_log_summary(graphql_info.as_ref(), jsonrpc_info.as_ref()); @@ -2595,6 +2596,7 @@ where } }; let correlation = RequestCorrelation::new(&req, ctx); + correlation.select_inspector(config.protocol, &ctx.policy_name); let capture_error = |error| correlation.capture_error(error); if !request_authority_matches_endpoint(&req, ctx) { reject_request_authority_mismatch(client, ctx, &req.action, Some(&correlation)) @@ -2687,11 +2689,15 @@ where .any(|l| l.to_ascii_lowercase().starts_with("upgrade:")) }; - let decision_str = match (allowed, config.enforcement, is_upgrade_request) { - (true, _, true) => "allow_upgrade", - (true, _, false) => "allow", - (false, EnforcementMode::Audit, _) => "audit", - (false, EnforcementMode::Enforce, _) => "deny", + let admission = crate::metrics::Outcome::policy( + allowed, + config.enforcement == EnforcementMode::Enforce, + ); + correlation.note_admission(admission); + let decision_str = if allowed && is_upgrade_request { + "allow_upgrade" + } else { + admission.label() }; // Log every L7 decision as an OCSF HTTP Activity event. @@ -3151,6 +3157,7 @@ where let req = parsed.request; let jsonrpc_info = parsed.info; let correlation = RequestCorrelation::new(&req, ctx); + correlation.select_inspector(config.protocol, &ctx.policy_name); let capture_error = |error| correlation.capture_error(error); let observer = EndpointObserver::begin_captured( ctx.endpoint_observation_tx.as_ref(), @@ -3249,12 +3256,12 @@ where return Ok(()); } - let decision_str = match (allowed, config.enforcement) { - (_, _) if force_deny => "deny", - (true, _) => "allow", - (false, EnforcementMode::Audit) => "audit", - (false, EnforcementMode::Enforce) => "deny", - }; + let admission = crate::metrics::Outcome::policy( + allowed, + force_deny || config.enforcement == EnforcementMode::Enforce, + ); + correlation.note_admission(admission); + let decision_str = admission.label(); { let (action_id, disposition_id, severity) = match decision_str { @@ -3523,6 +3530,7 @@ where } }; let correlation = RequestCorrelation::new(&req, ctx); + correlation.select_inspector(config.protocol, &ctx.policy_name); let capture_error = |error| correlation.capture_error(error); if !request_authority_matches_endpoint(&req, ctx) { @@ -3626,12 +3634,12 @@ where return Ok(()); } - let decision_str = match (allowed, config.enforcement) { - (_, _) if force_deny => "deny", - (true, _) => "allow", - (false, EnforcementMode::Audit) => "audit", - (false, EnforcementMode::Enforce) => "deny", - }; + let admission = crate::metrics::Outcome::policy( + allowed, + force_deny || config.enforcement == EnforcementMode::Enforce, + ); + correlation.note_admission(admission); + let decision_str = admission.label(); { let (action_id, disposition_id, severity) = match decision_str { @@ -4323,6 +4331,15 @@ fn evaluate_l7_request_once( engine: &TunnelPolicyEngine, ctx: &L7EvalContext, request: &L7RequestInfo, +) -> Result<(bool, String)> { + evaluate_l7_in_scope(crate::metrics::Scope::Request, engine, ctx, request) +} + +pub(super) fn evaluate_l7_in_scope( + scope: crate::metrics::Scope, + engine: &TunnelPolicyEngine, + ctx: &L7EvalContext, + request: &L7RequestInfo, ) -> Result<(bool, String)> { if engine.is_stale() { return Err(miette!( @@ -4331,7 +4348,18 @@ fn evaluate_l7_request_once( engine.current_generation(), )); } + crate::metrics::evaluate( + scope, + || evaluate_l7_policy(engine, ctx, request), + |(allowed, _)| *allowed, + ) +} +fn evaluate_l7_policy( + engine: &TunnelPolicyEngine, + ctx: &L7EvalContext, + request: &L7RequestInfo, +) -> Result<(bool, String)> { let input = l7_request_policy_input(ctx, request); let mut engine = engine diff --git a/crates/openshell-supervisor-network/src/l7/request_trace.rs b/crates/openshell-supervisor-network/src/l7/request_trace.rs index 1d9c36a509..8d871976ec 100644 --- a/crates/openshell-supervisor-network/src/l7/request_trace.rs +++ b/crates/openshell-supervisor-network/src/l7/request_trace.rs @@ -11,6 +11,7 @@ use tracing::Span; use tracing_opentelemetry::OpenTelemetrySpanExt as _; use super::correlation::HttpOutcome; +use crate::metrics::{self, InspectionType, Outcome, Policy, ResultLabel, Scope, Stage, Timer}; const MAX_TRACEPARENT_BYTES: usize = 256; @@ -19,6 +20,11 @@ pub(super) struct RequestTrace { span: Span, outcome: &'static str, failure_reason: Option<&'static str>, + inspection: Option, + inspection_result: Option<(ResultLabel, Option)>, + inspection_type: InspectionType, + policy: String, + admission: Outcome, } #[derive(Debug, Clone, Copy)] @@ -67,6 +73,9 @@ impl RequestTrace { server.port = i64::from(port), openshell.request.outcome = tracing::field::Empty, openshell.request.failure_reason = tracing::field::Empty, + openshell.egress.outcome = tracing::field::Empty, + openshell.egress.inspection_type = tracing::field::Empty, + openshell.egress.result = tracing::field::Empty, http.response.status_code = tracing::field::Empty, otel.kind = "server", otel.status_code = tracing::field::Empty, @@ -84,9 +93,80 @@ impl RequestTrace { span, outcome: "incomplete", failure_reason: None, + inspection: None, + inspection_result: None, + inspection_type: InspectionType::Http, + policy: String::new(), + admission: Outcome::Allow, } } + pub(super) fn start_inspection(&mut self, policy: &str) { + self.policy.push_str(policy); + self.inspection = Some( + self.span + .in_scope(|| Timer::new(Stage::Inspection(Scope::Request, self.inspection_type))), + ); + } + + pub(super) fn select_inspector(&mut self, inspection_type: InspectionType, policy: &str) { + self.inspection_type = inspection_type; + self.policy.clear(); + self.policy.push_str(policy); + if let Some(timer) = self.inspection.as_mut() { + timer.set_stage(Stage::Inspection(Scope::Request, inspection_type)); + } + } + + pub(super) fn note_admission(&mut self, outcome: Outcome) { + match outcome { + Outcome::Audit if !matches!(self.admission, Outcome::FailOpen) => { + self.admission = outcome; + } + Outcome::FailOpen => self.admission = outcome, + _ => {} + } + } + + pub(super) fn inspection_timer(&mut self) -> Option<&mut Timer> { + self.inspection.as_mut() + } + + pub(super) fn finished_inspection( + &self, + ) -> Option<(InspectionType, ResultLabel, Option)> { + let (result, outcome) = self.inspection_result?; + Some((self.inspection_type, result, outcome)) + } + + pub(super) fn finish_inspection(&mut self, result: ResultLabel) { + let Some(timer) = self.inspection.take() else { + return; + }; + let outcome = match result { + ResultLabel::Success => Some(self.admission), + ResultLabel::Deny => Some(Outcome::Deny), + _ => None, + }; + self.inspection_result = Some((result, outcome)); + self.span.record("openshell.egress.result", result.label()); + self.span.record( + "openshell.egress.inspection_type", + self.inspection_type.label(), + ); + if let Some(outcome) = outcome { + self.span + .record("openshell.egress.outcome", outcome.label()); + metrics::decision( + Scope::Request, + outcome, + self.inspection_type, + Policy::from(Some(self.policy.as_str())), + ); + } + timer.finish(result); + } + pub(super) fn span(&self) -> Span { self.span.clone() } @@ -101,6 +181,7 @@ impl RequestTrace { otel.name = stage.name(), otel.status_code = tracing::field::Empty, openshell.request.failure_reason = tracing::field::Empty, + openshell.egress.result = tracing::field::Empty, ) } @@ -110,6 +191,9 @@ impl RequestTrace { } pub(super) fn record_outcome(&mut self, outcome: HttpOutcome) { + if matches!(outcome, HttpOutcome::Denied) { + self.finish_inspection(ResultLabel::Deny); + } let outcome = match outcome { _ if self.outcome == "failed" => "failed", HttpOutcome::Allowed if self.outcome == "denied" => "denied", @@ -137,6 +221,7 @@ impl RequestTrace { impl Drop for RequestTrace { fn drop(&mut self) { + self.finish_inspection(ResultLabel::Cancelled); // Finalize exported timing after the request's child stages. self.span.in_scope(|| { self.span.record("openshell.request.outcome", self.outcome); diff --git a/crates/openshell-supervisor-network/src/l7/rest.rs b/crates/openshell-supervisor-network/src/l7/rest.rs index caec858eaf..1158e4de22 100644 --- a/crates/openshell-supervisor-network/src/l7/rest.rs +++ b/crates/openshell-supervisor-network/src/l7/rest.rs @@ -993,6 +993,7 @@ where observer, correlation, request_span: None, + started_forwarding: false, track_request_span: live_body.is_none(), }; let upstream = &mut observed_upstream; @@ -1503,6 +1504,7 @@ struct ObservedUpstream<'a, U> { observer: Option<&'a EndpointObserver>, correlation: Option<&'a RequestCorrelation>, request_span: Option, + started_forwarding: bool, track_request_span: bool, } @@ -1542,6 +1544,12 @@ impl AsyncWrite for ObservedUpstream<'_, U> { buf: &[u8], ) -> std::task::Poll> { let this = self.get_mut(); + if !this.started_forwarding && !buf.is_empty() { + this.started_forwarding = true; + if let Some(correlation) = this.correlation { + correlation.finish_inspection(crate::metrics::ResultLabel::Success); + } + } let result = if this.track_request_span { let span = this.request_span.get_or_insert_with(|| { this.correlation @@ -7094,6 +7102,7 @@ mod tests { observer: Some(&observer), correlation: None, request_span: None, + started_forwarding: false, track_request_span: true, }; let mut client = Vec::new(); diff --git a/crates/openshell-supervisor-network/src/l7/websocket.rs b/crates/openshell-supervisor-network/src/l7/websocket.rs index ba39c99961..0c5792bcc9 100644 --- a/crates/openshell-supervisor-network/src/l7/websocket.rs +++ b/crates/openshell-supervisor-network/src/l7/websocket.rs @@ -6,8 +6,9 @@ //! The relay parses only client-to-server frames. Server-to-client bytes stay //! raw passthrough so inspection and rewriting cannot expose response payloads. -use crate::l7::relay::{L7EvalContext, evaluate_l7_request}; +use crate::l7::relay::{L7EvalContext, evaluate_l7_in_scope}; use crate::l7::{EnforcementMode, L7RequestInfo}; +use crate::metrics::{self, InspectionType, Outcome, Policy, ResultLabel, Scope, Stage, Timer}; use crate::opa::{PolicyGenerationGuard, TunnelPolicyEngine}; use crate::telemetry::egress_emit; use flate2::{Compress, Compression, Decompress, FlushCompress, FlushDecompress, Status}; @@ -1211,6 +1212,89 @@ async fn relay_text_payload_with_before_credential_write( options: &mut RelayOptions<'_>, before_credential_write: F, ) -> WebSocketRelayResult<()> +where + W: AsyncWrite + Unpin, + F: Future, +{ + let inspection = if options + .inspector + .as_ref() + .is_some_and(|inspector| inspector.graphql_policy) + { + InspectionType::Graphql + } else { + InspectionType::Websocket + }; + let mut metrics = MessageInspection { + timer: Some(Timer::new(Stage::Inspection(Scope::Message, inspection))), + inspection, + outcome: Outcome::Allow, + }; + let result = relay_text_payload_inner( + writer, + frame, + payload, + admission, + force_reframe, + compressed, + host, + port, + options, + before_credential_write, + &mut metrics, + ) + .await; + if let Err(error) = &result { + let (outcome, label) = match error.cause { + WebSocketTerminationCause::PolicyDenial + | WebSocketTerminationCause::MiddlewareDenial => { + (Some(Outcome::Deny), ResultLabel::Deny) + } + WebSocketTerminationCause::PolicyReload + | WebSocketTerminationCause::DownstreamDisconnect => (None, ResultLabel::Cancelled), + _ => (None, ResultLabel::Error), + }; + metrics.finish(options.policy_name, outcome, label); + } + result +} + +struct MessageInspection { + timer: Option, + inspection: InspectionType, + outcome: Outcome, +} + +impl MessageInspection { + fn finish(&mut self, policy: &str, outcome: Option, result: ResultLabel) { + if let Some(timer) = self.timer.take() { + if let Some(outcome) = outcome { + metrics::decision( + Scope::Message, + outcome, + self.inspection, + Policy::from(Some(policy)), + ); + } + timer.finish(result); + } + } +} + +#[allow(clippy::too_many_arguments)] +async fn relay_text_payload_inner( + writer: &mut W, + frame: &FrameHeader, + payload: Vec, + admission: Option, + force_reframe: bool, + compressed: bool, + host: &str, + port: u16, + options: &mut RelayOptions<'_>, + before_credential_write: F, + metrics: &mut MessageInspection, +) -> WebSocketRelayResult<()> where W: AsyncWrite + Unpin, F: Future, @@ -1258,8 +1342,13 @@ where // Built-in transport/GraphQL inspection sees the original unresolved // message. External transformations run next, then policy is re-evaluated // before credential material is introduced. - if let Some(inspector) = options.inspector.as_ref() { - inspect_websocket_text_message(host, port, options.policy_name, inspector, &text)?; + if let Some(inspector) = options.inspector.as_ref() + && matches!( + inspect_websocket_text_message(host, port, options.policy_name, inspector, &text)?, + Outcome::Audit + ) + { + metrics.outcome = Outcome::Audit; } ensure_generation_current(host, port, options)?; @@ -1297,11 +1386,26 @@ where .invocations .iter() .any(|invocation| invocation.transformed); + if outcome.invocations.iter().any(|invocation| { + matches!( + invocation.outcome, + openshell_supervisor_middleware::WebSocketInvocationOutcome::FailOpen + ) + }) { + metrics.outcome = Outcome::FailOpen; + } text = outcome.payload; } - if middleware_transformed && let Some(inspector) = options.inspector.as_ref() { - inspect_websocket_text_message(host, port, options.policy_name, inspector, &text)?; + if middleware_transformed + && let Some(inspector) = options.inspector.as_ref() + && matches!( + inspect_websocket_text_message(host, port, options.policy_name, inspector, &text)?, + Outcome::Audit + ) + && !matches!(metrics.outcome, Outcome::FailOpen) + { + metrics.outcome = Outcome::Audit; } ensure_generation_current(host, port, options)?; @@ -1345,6 +1449,11 @@ where )) })?; apply_mask(&mut payload, mask_key); + metrics.finish( + options.policy_name, + Some(metrics.outcome), + ResultLabel::Success, + ); return write_text_frame_guarded( writer, &frame.raw_header, @@ -1376,6 +1485,11 @@ where error, )) })?; + metrics.finish( + options.policy_name, + Some(metrics.outcome), + ResultLabel::Success, + ); return write_masked_text_frame_guarded( writer, 0x40, @@ -1387,6 +1501,11 @@ where ) .await; } + metrics.finish( + options.policy_name, + Some(metrics.outcome), + ResultLabel::Success, + ); write_masked_text_frame_guarded( writer, 0, @@ -1422,7 +1541,7 @@ fn inspect_websocket_text_message( policy_name: &str, inspector: &InspectionOptions<'_>, text: &str, -) -> WebSocketRelayResult<()> { +) -> WebSocketRelayResult { if inspector.graphql_policy { return inspect_graphql_websocket_message(host, port, policy_name, inspector, text); } @@ -1434,19 +1553,20 @@ fn inspect_websocket_text_message( graphql: None, jsonrpc: None, }; - let (allowed, reason) = evaluate_l7_request(inspector.engine, inspector.ctx, &request_info) - .map_err(|error| terminate(WebSocketTerminationCause::PolicyReload, error))?; - let decision = match (allowed, inspector.enforcement) { - (true, _) => "allow", - (false, EnforcementMode::Audit) => "audit", - (false, EnforcementMode::Enforce) => "deny", - }; + let (allowed, reason) = evaluate_l7_in_scope( + Scope::Message, + inspector.engine, + inspector.ctx, + &request_info, + ) + .map_err(|error| terminate(WebSocketTerminationCause::PolicyReload, error))?; + let decision = Outcome::policy(allowed, inspector.enforcement == EnforcementMode::Enforce); emit_websocket_l7_event( host, port, policy_name, &request_info, - decision, + decision.label(), &reason, None, ); @@ -1456,7 +1576,7 @@ fn inspect_websocket_text_message( miette!("websocket text message denied by policy"), )); } - Ok(()) + Ok(decision) } fn inspect_graphql_websocket_message( @@ -1465,7 +1585,7 @@ fn inspect_graphql_websocket_message( policy_name: &str, inspector: &InspectionOptions<'_>, text: &str, -) -> WebSocketRelayResult<()> { +) -> WebSocketRelayResult { match classify_graphql_websocket_message(text) { GraphqlWebSocketMessage::Control { message_type } => { let request_info = L7RequestInfo { @@ -1484,7 +1604,7 @@ fn inspect_graphql_websocket_message( &format!("GraphQL WebSocket control message {message_type}"), None, ); - Ok(()) + Ok(Outcome::Allow) } GraphqlWebSocketMessage::Operation { message_type, @@ -1505,22 +1625,25 @@ fn inspect_graphql_websocket_message( let (allowed, reason) = if let Some(reason) = parse_error_reason { (false, reason) } else { - evaluate_l7_request(inspector.engine, inspector.ctx, &request_info) - .map_err(|error| terminate(WebSocketTerminationCause::PolicyReload, error))? - }; - let decision = match (allowed, inspector.enforcement) { - (_, _) if force_deny => "deny", - (true, _) => "allow", - (false, EnforcementMode::Audit) => "audit", - (false, EnforcementMode::Enforce) => "deny", + evaluate_l7_in_scope( + Scope::Message, + inspector.engine, + inspector.ctx, + &request_info, + ) + .map_err(|error| terminate(WebSocketTerminationCause::PolicyReload, error))? }; + let decision = Outcome::policy( + allowed, + force_deny || inspector.enforcement == EnforcementMode::Enforce, + ); let reason = format!("graphql_ws_type={message_type} {reason}"); emit_websocket_l7_event( host, port, policy_name, &request_info, - decision, + decision.label(), &reason, Some(&graphql), ); @@ -1530,7 +1653,7 @@ fn inspect_graphql_websocket_message( miette!("websocket GraphQL message denied by policy"), )); } - Ok(()) + Ok(decision) } } } diff --git a/crates/openshell-supervisor-network/src/metrics.rs b/crates/openshell-supervisor-network/src/metrics.rs index 8bf53544fa..4e0f3e20e8 100644 --- a/crates/openshell-supervisor-network/src/metrics.rs +++ b/crates/openshell-supervisor-network/src/metrics.rs @@ -7,7 +7,7 @@ use std::collections::HashSet; use std::future::Future; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; -use std::time::Instant; +use std::time::{Duration, Instant}; use opentelemetry::metrics::{Counter, Histogram, Meter, ObservableGauge}; use opentelemetry::{Context, KeyValue}; @@ -31,12 +31,16 @@ pub fn install(meter: &Meter) { #[derive(Debug, Clone, Copy)] pub(crate) enum Scope { Connection, + Request, + Message, } impl Scope { fn label(self) -> &'static str { match self { Self::Connection => "connection", + Self::Request => "request", + Self::Message => "message", } } } @@ -94,6 +98,7 @@ impl InspectionType { pub(crate) enum Outcome { Allow, Deny, + Audit, FailOpen, } @@ -102,9 +107,18 @@ impl Outcome { match self { Self::Allow => "allow", Self::Deny => "deny", + Self::Audit => "audit", Self::FailOpen => "fail_open", } } + + pub(crate) fn policy(allowed: bool, enforce: bool) -> Self { + match (allowed, enforce) { + (true, _) => Self::Allow, + (false, true) => Self::Deny, + (false, false) => Self::Audit, + } + } } #[derive(Debug, Clone, Copy)] @@ -166,6 +180,7 @@ impl<'a> From> for Policy<'a> { struct Metrics { decisions: Counter, policy_evaluation: Histogram, + request_inspection: Histogram, upstream_connect: Histogram, policy_names: Mutex>>, connections: Arc<[AtomicU64; InspectionType::ALL.len()]>, @@ -206,6 +221,10 @@ impl Metrics { "openshell_supervisor_policy_evaluation_duration_seconds", "Time spent evaluating egress policy.", ), + request_inspection: histogram( + "openshell_supervisor_request_inspection_duration_seconds", + "Time spent inspecting a request or message before forwarding.", + ), upstream_connect: histogram( "openshell_supervisor_upstream_connect_duration_seconds", "Time spent establishing an upstream connection.", @@ -292,6 +311,7 @@ impl Drop for ActiveConnection { #[derive(Debug, Clone, Copy)] pub(crate) enum Stage { PolicyEvaluation(Scope), + Inspection(Scope, InspectionType), UpstreamConnect(Route), } @@ -330,6 +350,8 @@ pub(crate) fn evaluate( pub(crate) struct Timer { stage: Stage, start: Option<(Instant, Context)>, + pause: Option, + excluded: Duration, } impl Timer { @@ -337,6 +359,8 @@ impl Timer { Self { stage, start: METRICS.get().map(|_| (Instant::now(), Context::current())), + pause: None, + excluded: Duration::ZERO, } } @@ -344,11 +368,30 @@ impl Timer { self.record(result); } + pub(crate) fn set_stage(&mut self, stage: Stage) { + self.stage = stage; + } + + pub(crate) fn pause(&mut self) { + if self.start.is_some() { + self.pause = Some(Instant::now()); + } + } + + pub(crate) fn resume(&mut self) { + if let Some(paused) = self.pause.take() { + self.excluded += paused.elapsed(); + } + } + fn record(&mut self, result: ResultLabel) { let (Some(metrics), Some((started, context))) = (METRICS.get(), self.start.take()) else { return; }; - let seconds = started.elapsed().as_secs_f64(); + let ended = self.pause.unwrap_or_else(Instant::now); + let seconds = (ended - started) + .saturating_sub(self.excluded) + .as_secs_f64(); let _active_context = context.attach(); let result = KeyValue::new("result", result.label()); match self.stage { @@ -357,6 +400,14 @@ impl Timer { .policy_evaluation .record(seconds, &[KeyValue::new("scope", scope.label()), result]); } + Stage::Inspection(scope, inspection) => metrics.request_inspection.record( + seconds, + &[ + KeyValue::new("scope", scope.label()), + KeyValue::new("inspection_type", inspection.label()), + result, + ], + ), Stage::UpstreamConnect(route) => { metrics .upstream_connect @@ -409,6 +460,8 @@ mod tests { let connection = ActiveConnection::new(InspectionType::Unknown); Timer::new(Stage::PolicyEvaluation(Scope::Connection)).finish(ResultLabel::Deny); + Timer::new(Stage::Inspection(Scope::Request, InspectionType::Rest)) + .finish(ResultLabel::Success); drop(Timer::new(Stage::UpstreamConnect(Route::Proxy))); for kind in [ std::io::ErrorKind::PermissionDenied, @@ -437,6 +490,10 @@ mod tests { "openshell_supervisor_policy_evaluation_duration_seconds", "deny", ), + ( + "openshell_supervisor_request_inspection_duration_seconds", + "success", + ), ( "openshell_supervisor_upstream_connect_duration_seconds", "cancelled", diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index ca879be9c3..1d1a8a1dcb 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -17,7 +17,7 @@ use openshell_sandbox_backend::test_support as rpc_test; use crate::identity::{BinaryIdentityCache, SuppliedIdentityError}; use crate::l7::correlation::{HttpOutcome, RequestStage}; use crate::l7::tls::ProxyTlsState; -use crate::metrics::{InspectionType, Outcome, Scope}; +use crate::metrics::{ActiveConnection, InspectionType, Outcome, ResultLabel, Scope}; use crate::opa::{NetworkAction, OpaEngine, PolicyGenerationGuard}; #[cfg(test)] use crate::policy_dns::SocketTrustedResolver; @@ -2477,6 +2477,7 @@ where correlation.record_rejection(403, HttpOutcome::Denied, None); correlation.emit(event); } else { + decision.record_admission(Scope::Request, Outcome::Deny, InspectionType::Http); crate::telemetry::emit_decision([event], Some(connect_span)); } @@ -5859,6 +5860,7 @@ async fn handle_forward_proxy_inner( let matched_policy = match &decision.action { NetworkAction::Allow { matched_policy } => matched_policy.clone(), NetworkAction::Deny { reason } => { + decision.record_admission(Scope::Request, Outcome::Deny, InspectionType::Http); crate::telemetry::emit_decision( [build_forward_policy_deny_ocsf_event( workload_addr, @@ -6156,6 +6158,7 @@ async fn handle_forward_proxy_inner( .await?; return Ok(()); }; + correlation.select_inspector(l7_config.config.protocol, &l7_ctx.policy_name); endpoint_observer = crate::l7::EndpointObserver::begin_captured( l7_ctx.endpoint_observation_tx.as_ref(), &l7_config.config, @@ -6433,12 +6436,12 @@ async fn handle_forward_proxy_inner( |reason| (false, reason), ); - let decision_str = match (allowed, l7_config.config.enforcement) { - (_, _) if force_deny => "deny", - (true, _) => "allow", - (false, crate::l7::EnforcementMode::Audit) => "audit", - (false, crate::l7::EnforcementMode::Enforce) => "deny", - }; + let admission = Outcome::policy( + allowed, + force_deny || l7_config.config.enforcement == crate::l7::EnforcementMode::Enforce, + ); + correlation.note_admission(admission); + let decision_str = admission.label(); { let (action_id, disposition_id, severity) = match decision_str { @@ -6586,6 +6589,7 @@ async fn handle_forward_proxy_inner( } else { egress::resolve_span(&connect_span) }; + correlation.inspection_timer(crate::metrics::Timer::pause); let resolved = validate_destination(DestinationRequest { host: &raw_host, port, @@ -6594,6 +6598,7 @@ async fn handle_forward_proxy_inner( }) .instrument(resolve_span.clone()) .await; + correlation.inspection_timer(crate::metrics::Timer::resume); if inspected { if resolved.is_err() { egress::mark_error(&resolve_span); @@ -7153,7 +7158,11 @@ async fn handle_forward_proxy_inner( } else { egress::dial_span(&connect_span) }; - let dial_result = connector.connect().instrument(dial_span.clone()).await; + correlation.inspection_timer(crate::metrics::Timer::pause); + let dial_result = crate::metrics::connect(crate::metrics::Route::Direct, connector.connect()) + .instrument(dial_span.clone()) + .await; + correlation.inspection_timer(crate::metrics::Timer::resume); let mut upstream = match dial_result { Ok(s) => { if inspected { @@ -7164,6 +7173,7 @@ async fn handle_forward_proxy_inner( Err(e) => { egress::mark_error(&dial_span); if inspected { + correlation.finish_inspection(ResultLabel::from_io_error(&e)); dial_span.record( "openshell.request.failure_reason", "upstream_connect_failed", @@ -7254,6 +7264,15 @@ async fn handle_forward_proxy_inner( let signing_region = forward_upgrade_config .as_ref() .map_or("", |config| config.signing_region.as_str()); + let inspection = forward_upgrade_config + .as_ref() + .map_or(InspectionType::Http, |config| { + InspectionType::from_protocol(config.protocol) + }); + let _connection = ActiveConnection::new(inspection); + if !inspected { + decision.record_admission(Scope::Request, Outcome::Allow, InspectionType::Http); + } let outcome_result = relay_rewritten_forward_request( method, &upstream_target, diff --git a/crates/openshell-supervisor-network/src/proxy/tests/request_trace.rs b/crates/openshell-supervisor-network/src/proxy/tests/request_trace.rs index 86aa709cec..6586f396b7 100644 --- a/crates/openshell-supervisor-network/src/proxy/tests/request_trace.rs +++ b/crates/openshell-supervisor-network/src/proxy/tests/request_trace.rs @@ -18,6 +18,7 @@ enum Outcome { MalformedQueryPolicyDenied, AuditDenied, UnresolvedCredential, + UpstreamConnectFailed, UpstreamClosed, } @@ -328,8 +329,15 @@ network_policies: } async fn forward_case(ip: Ipv4Addr, outcome: Outcome, sampler: Option) { - let listener = TcpListener::bind((ip, 0)).await.unwrap(); - let port = listener.local_addr().unwrap().port(); + let connect_failed = matches!(outcome, Outcome::UpstreamConnectFailed); + let upstream = tokio::net::TcpSocket::new_v4().unwrap(); + upstream.bind((ip, 0).into()).unwrap(); + let port = upstream.local_addr().unwrap().port(); + let listener = if connect_failed { + None + } else { + Some(upstream.listen(128).unwrap()) + }; let policy_denied = matches!( outcome, Outcome::PolicyDenied | Outcome::MalformedQueryPolicyDenied @@ -437,6 +445,7 @@ network_policies: result }, async { + let Some(listener) = &listener else { return }; if policy_denied || credential_failure { assert!( tokio::time::timeout( @@ -481,6 +490,8 @@ network_policies: 403 } else if credential_failure { 500 + } else if connect_failed { + 502 } else { 200 }); @@ -497,7 +508,10 @@ network_policies: let decision = match outcome { Outcome::PolicyDenied | Outcome::MalformedQueryPolicyDenied => "deny", Outcome::AuditDenied => "audit", - Outcome::Allowed | Outcome::UnresolvedCredential | Outcome::UpstreamClosed => "allow", + Outcome::Allowed + | Outcome::UnresolvedCredential + | Outcome::UpstreamConnectFailed + | Outcome::UpstreamClosed => "allow", }; assert!( record["message"] @@ -512,7 +526,11 @@ network_policies: assert_eq!(control["http_request"]["url"]["path"], path); assert!(control.get("http_response").is_none()); } - if !policy_denied && !credential_failure { + if connect_failed { + let failure = &records[1]; + assert_eq!(failure["unmapped"]["egress_result"], "error"); + assert!(failure["unmapped"].get("egress_outcome").is_none()); + } else if !policy_denied && !credential_failure { let forwarded = &records[1]; assert!( forwarded["message"] @@ -646,7 +664,9 @@ network_policies: matches!(root.status, opentelemetry::trace::Status::Error { .. }), matches!( outcome, - Outcome::UpstreamClosed | Outcome::UnresolvedCredential + Outcome::UpstreamClosed + | Outcome::UpstreamConnectFailed + | Outcome::UnresolvedCredential ), "a policy refusal is an outcome, not an operational tracing failure" ); @@ -692,6 +712,7 @@ async fn inspected_forward_traces_all_outcomes_without_sampling_or_export_depend Outcome::PolicyDenied, Outcome::AuditDenied, Outcome::UnresolvedCredential, + Outcome::UpstreamConnectFailed, Outcome::UpstreamClosed, ] { for sampler in [Some(Sampler::AlwaysOn), Some(Sampler::AlwaysOff), None] { From 49a0dd57eb57bc7e8cd5d454e3c333818b83d54f Mon Sep 17 00:00:00 2001 From: Eitan Geiger Date: Wed, 18 Nov 2026 21:13:28 +0200 Subject: [PATCH 3/6] feat(gateway): deliver supervisor metrics configuration Add an opt-in supervisor_metrics collector to gateway TOML. Inherit the base OTLP collector settings when the table omits an endpoint, or use the table's collector settings when it specifies one. Pass endpoints through supervisor launch settings and credentials through the trusted auth bundle. Send equivalent settings to shared supervisors on the authenticated assignment stream and omit the credential-bearing payload from debug formatting. Signed-off-by: Eitan Geiger --- crates/openshell-core/build.rs | 1 + crates/openshell-core/src/jwt.rs | 19 +++++ crates/openshell-core/src/proto/mod.rs | 11 +++ crates/openshell-core/src/sandbox_env.rs | 45 +++++++++- crates/openshell-driver-docker/src/tests.rs | 2 + crates/openshell-driver-podman/src/driver.rs | 3 + .../openshell-driver-podman/src/isolation.rs | 2 + crates/openshell-driver-vm/src/driver.rs | 2 + crates/openshell-gateway/src/vm.rs | 11 +++ .../openshell-server/src/auth/sandbox_jwt.rs | 2 + crates/openshell-server/src/compute/mod.rs | 1 + crates/openshell-server/src/config_file.rs | 83 +++++++++++++------ crates/openshell-server/src/lib.rs | 21 +++++ crates/openshell-server/src/otel_tracing.rs | 11 ++- .../src/persistence/mutation_lock_pg_tests.rs | 4 + crates/openshell-server/src/ssh_identity.rs | 2 + .../src/controller.rs | 9 ++ .../src/backend_setup/tests.rs | 2 + .../src/legacy_startup_regression_tests.rs | 2 + crates/openshell-supervisor/src/lib.rs | 2 + crates/openshell-supervisor/src/main.rs | 2 + .../openshell-supervisor/src/shared_host.rs | 1 + proto/supervisor_host.proto | 4 + 23 files changed, 213 insertions(+), 29 deletions(-) diff --git a/crates/openshell-core/build.rs b/crates/openshell-core/build.rs index 2779e78fb9..c1c1d6e157 100644 --- a/crates/openshell-core/build.rs +++ b/crates/openshell-core/build.rs @@ -52,6 +52,7 @@ fn main() -> Result<(), Box> { let mut proto_config = tonic_prost_build::Config::new(); // Keep optional grant evidence off sandbox lifecycle futures' stacks. proto_config.boxed(".openshell.v1.SandboxStatus.last_token_grant_failure"); + proto_config.skip_debug([".openshell.supervisor.host.v1.HostAccepted"]); let proto_include = if use_vendored_protoc { proto_config.protoc_executable(protoc_bin_vendored::protoc_bin_path()?); Some(protoc_bin_vendored::include_path()?) diff --git a/crates/openshell-core/src/jwt.rs b/crates/openshell-core/src/jwt.rs index 84ffe98ec0..ff48d99434 100644 --- a/crates/openshell-core/src/jwt.rs +++ b/crates/openshell-core/src/jwt.rs @@ -514,6 +514,9 @@ mod session { /// the gateway configures them. Never delivered to the workload. #[serde(default, skip_serializing_if = "Option::is_none")] pub agent_otlp_headers: Option, + /// Headers for the supervisor's metrics collector. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metrics_otlp_headers: Option, /// TLS material for the supervisor's collectors, each distinct /// material once, present only when the gateway configures it. /// Never delivered to the workload. @@ -526,6 +529,8 @@ mod session { pub ocsf_otlp_tls: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub agent_otlp_tls: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metrics_otlp_tls: Option, } /// Gateway-created authentication input trusted by a compute driver. @@ -591,6 +596,7 @@ mod session { self.traces_otlp_tls, self.ocsf_otlp_tls, self.agent_otlp_tls, + self.metrics_otlp_tls, ]; if references .into_iter() @@ -617,6 +623,11 @@ mod session { self.otlp_credentials(self.agent_otlp_headers.as_ref(), self.agent_otlp_tls) } + /// What the supervisor's metrics export sends its collector. + pub fn metrics_otlp(&self) -> OtlpExportCredentials<'_> { + self.otlp_credentials(self.metrics_otlp_headers.as_ref(), self.metrics_otlp_tls) + } + /// [`Self::validate`] rejects a `tls` index outside `otlp_tls`. fn otlp_credentials<'a>( &'a self, @@ -654,10 +665,12 @@ mod session { .field("traces_otlp_headers", &self.traces_otlp_headers) .field("ocsf_otlp_headers", &self.ocsf_otlp_headers) .field("agent_otlp_headers", &self.agent_otlp_headers) + .field("metrics_otlp_headers", &self.metrics_otlp_headers) .field("otlp_tls", &self.otlp_tls) .field("traces_otlp_tls", &self.traces_otlp_tls) .field("ocsf_otlp_tls", &self.ocsf_otlp_tls) .field("agent_otlp_tls", &self.agent_otlp_tls) + .field("metrics_otlp_tls", &self.metrics_otlp_tls) .finish() } } @@ -1790,10 +1803,12 @@ mod tests { ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, + metrics_otlp_headers: None, agent_otlp_headers: None, otlp_tls: Vec::new(), traces_otlp_tls: None, ocsf_otlp_tls: None, + metrics_otlp_tls: None, agent_otlp_tls: None, }; bundle.validate().expect("non-expiring auth bundle"); @@ -1938,10 +1953,12 @@ mod tests { ssh_host_private_key: None, traces_otlp_headers: headers("traces"), ocsf_otlp_headers: headers("ocsf"), + metrics_otlp_headers: None, agent_otlp_headers: headers("agent"), otlp_tls: vec![tls("agent"), tls("ocsf"), tls("traces")], traces_otlp_tls: Some(2), ocsf_otlp_tls: Some(1), + metrics_otlp_tls: None, agent_otlp_tls: Some(0), }; @@ -1983,6 +2000,7 @@ mod tests { ocsf_otlp_headers: Some(SecretOtlpHeaders::new( "authorization=collector-token".to_string(), )), + metrics_otlp_headers: None, agent_otlp_headers: Some(SecretOtlpHeaders::new( "authorization=agent-token".to_string(), )), @@ -1995,6 +2013,7 @@ mod tests { }], traces_otlp_tls: None, ocsf_otlp_tls: None, + metrics_otlp_tls: None, agent_otlp_tls: Some(0), }; diff --git a/crates/openshell-core/src/proto/mod.rs b/crates/openshell-core/src/proto/mod.rs index fb200cadac..3b643a5866 100644 --- a/crates/openshell-core/src/proto/mod.rs +++ b/crates/openshell-core/src/proto/mod.rs @@ -87,6 +87,17 @@ pub mod supervisor_host { pub use super::generated::openshell::supervisor::host::v1; } +impl std::fmt::Debug for supervisor_host::v1::HostAccepted { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("HostAccepted") + .field("session_id", &self.session_id) + .field("heartbeat_interval", &self.heartbeat_interval) + .field("peer_endpoint", &self.peer_endpoint) + .finish_non_exhaustive() + } +} + pub use datamodel::v1::*; pub use gateway_interceptor::v1::*; pub use middleware::v1::*; diff --git a/crates/openshell-core/src/sandbox_env.rs b/crates/openshell-core/src/sandbox_env.rs index c691642904..9e9fc53ea3 100644 --- a/crates/openshell-core/src/sandbox_env.rs +++ b/crates/openshell-core/src/sandbox_env.rs @@ -54,6 +54,11 @@ pub const OTLP_AGENT_ENDPOINT: &str = "OPENSHELL_OTLP_AGENT_ENDPOINT"; /// gRPC. pub const OTLP_AGENT_PROTOCOL: &str = "OPENSHELL_OTLP_AGENT_PROTOCOL"; +/// Collector for the supervisor's own egress metrics. +pub const OTLP_METRICS_ENDPOINT: &str = "OPENSHELL_OTLP_METRICS_ENDPOINT"; +/// Transport to the supervisor metrics collector. +pub const OTLP_METRICS_PROTOCOL: &str = "OPENSHELL_OTLP_METRICS_PROTOCOL"; + /// Name of the gateway that launched the sandbox, reported as /// `openshell.gateway.name` on supervisor telemetry. pub const GATEWAY_NAME: &str = "OPENSHELL_GATEWAY_NAME"; @@ -109,12 +114,22 @@ impl From for openshell_otel::Protocol { } /// One OTLP collector that a supervisor exports to. -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct OtlpExport { pub endpoint: String, pub protocol: OtlpProtocol, } +/// Trusted metrics setup sent to each shared supervisor on its assignment stream. +#[cfg(feature = "jwt")] +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct SharedSupervisorMetrics { + pub collector: OtlpExport, + pub gateway_name: String, + pub headers: Option, + pub tls: Option, +} + impl OtlpExport { fn environment( &self, @@ -137,13 +152,18 @@ pub struct SupervisorOtlp { pub ocsf: Option, /// Relayed workload traces. pub agent: Option, + /// Supervisor egress metrics. + pub metrics: Option, } impl SupervisorOtlp { /// Whether no export is configured. #[must_use] pub fn is_empty(&self) -> bool { - self.traces.is_none() && self.ocsf.is_none() && self.agent.is_none() + self.traces.is_none() + && self.ocsf.is_none() + && self.agent.is_none() + && self.metrics.is_none() } /// The supervisor environment variables for these exports. @@ -160,7 +180,11 @@ impl SupervisorOtlp { .agent .iter() .flat_map(|export| export.environment(OTLP_AGENT_ENDPOINT, OTLP_AGENT_PROTOCOL)); - traces.chain(ocsf).chain(agent).collect() + let metrics = self + .metrics + .iter() + .flat_map(|export| export.environment(OTLP_METRICS_ENDPOINT, OTLP_METRICS_PROTOCOL)); + traces.chain(ocsf).chain(agent).chain(metrics).collect() } /// Applies `rewrite` to every collector endpoint, for drivers whose @@ -177,6 +201,7 @@ impl SupervisorOtlp { traces: map(self.traces), ocsf: map(self.ocsf), agent: map(self.agent), + metrics: map(self.metrics), } } } @@ -193,6 +218,8 @@ pub const OTLP_OCSF_ENDPOINT_FLAG: &str = "otlp-ocsf-endpoint"; pub const OTLP_OCSF_PROTOCOL_FLAG: &str = "otlp-ocsf-protocol"; pub const OTLP_AGENT_ENDPOINT_FLAG: &str = "otlp-agent-endpoint"; pub const OTLP_AGENT_PROTOCOL_FLAG: &str = "otlp-agent-protocol"; +pub const OTLP_METRICS_ENDPOINT_FLAG: &str = "otlp-metrics-endpoint"; +pub const OTLP_METRICS_PROTOCOL_FLAG: &str = "otlp-metrics-protocol"; /// The OTLP flags every compute driver takes, flattened into its arguments. #[cfg(feature = "clap")] @@ -242,6 +269,14 @@ pub struct SupervisorOtlpArgs { /// Transport to the agent trace relay's collector: `grpc` or `http/protobuf`. #[arg(long = OTLP_AGENT_PROTOCOL_FLAG, env = OTLP_AGENT_PROTOCOL, default_value_t)] pub agent_protocol: OtlpProtocol, + + /// Collector for the supervisors' egress metrics. + #[arg(long = OTLP_METRICS_ENDPOINT_FLAG, env = OTLP_METRICS_ENDPOINT)] + pub metrics_endpoint: Option, + + /// Transport for supervisor metrics. + #[arg(long = OTLP_METRICS_PROTOCOL_FLAG, env = OTLP_METRICS_PROTOCOL, default_value_t)] + pub metrics_protocol: OtlpProtocol, } #[cfg(feature = "clap")] @@ -258,6 +293,7 @@ impl SupervisorOtlpArgs { traces: export(&self.endpoint, self.protocol), ocsf: export(&self.ocsf_endpoint, self.ocsf_protocol), agent: export(&self.agent_endpoint, self.agent_protocol), + metrics: export(&self.metrics_endpoint, self.metrics_protocol), } } @@ -641,6 +677,7 @@ mod tests { endpoint: "http://agents:4318".into(), protocol: OtlpProtocol::HttpProtobuf, }), + metrics: None, } ); assert_eq!( @@ -722,6 +759,7 @@ mod tests { traces: export("http://traces:4317", OtlpProtocol::Grpc), ocsf: export("http://siem:4318", OtlpProtocol::HttpProtobuf), agent: export("http://agents:4318", OtlpProtocol::HttpProtobuf), + metrics: None, }; assert_eq!( otlp.environment(), @@ -748,6 +786,7 @@ mod tests { traces: export("http://127.0.0.1:4317"), ocsf: None, agent: export("http://127.0.0.1:4318"), + metrics: None, } .map_endpoints(|endpoint| endpoint.replace("127.0.0.1", "host.internal")); assert_eq!(otlp.traces, export("http://host.internal:4317")); diff --git a/crates/openshell-driver-docker/src/tests.rs b/crates/openshell-driver-docker/src/tests.rs index 40972a0c79..efd87229d9 100644 --- a/crates/openshell-driver-docker/src/tests.rs +++ b/crates/openshell-driver-docker/src/tests.rs @@ -66,10 +66,12 @@ pub fn test_launch_authentication() -> Vec { ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, + metrics_otlp_headers: None, agent_otlp_headers: None, otlp_tls: Vec::new(), traces_otlp_tls: None, ocsf_otlp_tls: None, + metrics_otlp_tls: None, agent_otlp_tls: None, }, gateway_id: "gateway-test".to_string(), diff --git a/crates/openshell-driver-podman/src/driver.rs b/crates/openshell-driver-podman/src/driver.rs index 6bea5b7f16..b0c56fd17b 100644 --- a/crates/openshell-driver-podman/src/driver.rs +++ b/crates/openshell-driver-podman/src/driver.rs @@ -2700,10 +2700,12 @@ mod tests { ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, + metrics_otlp_headers: None, agent_otlp_headers: None, otlp_tls: Vec::new(), traces_otlp_tls: None, ocsf_otlp_tls: None, + metrics_otlp_tls: None, agent_otlp_tls: None, }, gateway_id: "gateway-test".to_string(), @@ -3549,6 +3551,7 @@ mod tests { traces: export(OtlpProtocol::Grpc), ocsf: export(OtlpProtocol::HttpProtobuf), agent: export(OtlpProtocol::HttpProtobuf), + metrics: None, } } diff --git a/crates/openshell-driver-podman/src/isolation.rs b/crates/openshell-driver-podman/src/isolation.rs index f9fc790588..c1e241e607 100644 --- a/crates/openshell-driver-podman/src/isolation.rs +++ b/crates/openshell-driver-podman/src/isolation.rs @@ -473,10 +473,12 @@ mod tests { ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, + metrics_otlp_headers: None, agent_otlp_headers: None, otlp_tls: Vec::new(), traces_otlp_tls: None, ocsf_otlp_tls: None, + metrics_otlp_tls: None, agent_otlp_tls: None, }, gateway_id: "gateway-test".to_string(), diff --git a/crates/openshell-driver-vm/src/driver.rs b/crates/openshell-driver-vm/src/driver.rs index 528c786b60..0c483ecc82 100644 --- a/crates/openshell-driver-vm/src/driver.rs +++ b/crates/openshell-driver-vm/src/driver.rs @@ -11259,10 +11259,12 @@ mod tests { ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, + metrics_otlp_headers: None, agent_otlp_headers: None, otlp_tls: Vec::new(), traces_otlp_tls: None, ocsf_otlp_tls: None, + metrics_otlp_tls: None, agent_otlp_tls: None, }, gateway_id: "gateway-a".to_string(), diff --git a/crates/openshell-gateway/src/vm.rs b/crates/openshell-gateway/src/vm.rs index 1f64a329a2..0960857f42 100644 --- a/crates/openshell-gateway/src/vm.rs +++ b/crates/openshell-gateway/src/vm.rs @@ -729,6 +729,12 @@ fn append_otlp_args(command: &mut Command, otlp_config: Option<&OtlpConfig>, gat sandbox_env::OTLP_AGENT_ENDPOINT_FLAG, sandbox_env::OTLP_AGENT_PROTOCOL_FLAG, ); + append_otlp_export_args( + command, + otlp.metrics.as_ref(), + sandbox_env::OTLP_METRICS_ENDPOINT_FLAG, + sandbox_env::OTLP_METRICS_PROTOCOL_FLAG, + ); if let Some(traces) = otlp_config.and_then(|otlp| otlp.traces.as_ref()) { let collector = &traces.collector; for (flag, path) in [ @@ -947,6 +953,7 @@ mod tests { traces: Some(OtlpTracesConfig { collector }), ocsf: None, agent: None, + supervisor_metrics: None, }; let mut command = tokio::process::Command::new("openshell-driver-vm"); append_otlp_args(&mut command, Some(&otlp), "production-us-west"); @@ -985,6 +992,7 @@ mod tests { }), ocsf: None, agent: None, + supervisor_metrics: None, }), "production-us-west", ); @@ -1018,6 +1026,7 @@ mod tests { }), ocsf: None, agent: None, + supervisor_metrics: None, }), "production-us-west", ); @@ -1054,6 +1063,7 @@ mod tests { schema_version: Some("2.0".into()), }), agent: None, + supervisor_metrics: None, }), "production-us-west", ); @@ -1092,6 +1102,7 @@ mod tests { OtlpProtocol::HttpProtobuf, ), }), + supervisor_metrics: None, }), "production-us-west", ); diff --git a/crates/openshell-server/src/auth/sandbox_jwt.rs b/crates/openshell-server/src/auth/sandbox_jwt.rs index 5d37d6c8a5..aa7f340009 100644 --- a/crates/openshell-server/src/auth/sandbox_jwt.rs +++ b/crates/openshell-server/src/auth/sandbox_jwt.rs @@ -267,10 +267,12 @@ impl SandboxSessionJwtAuthority { ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, + metrics_otlp_headers: None, agent_otlp_headers: None, otlp_tls: Vec::new(), traces_otlp_tls: None, ocsf_otlp_tls: None, + metrics_otlp_tls: None, agent_otlp_tls: None, }, gateway_id: self.gateway_id.clone(), diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index bd0f9235d4..505d493975 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -13972,6 +13972,7 @@ mod tests { traces: secret("authorization=traces"), ocsf: secret("authorization=Bearer%20secret"), agent: secret("x-mlflow-experiment-id=0"), + metrics: None, }); runtime.configure_supervisor_otlp_tls(crate::otel_tracing::SupervisorOtlpTls { materials: vec![openshell_core::jwt::OtlpTlsMaterial { diff --git a/crates/openshell-server/src/config_file.rs b/crates/openshell-server/src/config_file.rs index b0f1972914..94072a3426 100644 --- a/crates/openshell-server/src/config_file.rs +++ b/crates/openshell-server/src/config_file.rs @@ -364,6 +364,7 @@ pub struct MetricsTlsFileConfig { /// `endpoint` is the collector for every enabled signal, and on its own /// enables trace export. `[otlp.traces]` overrides the trace endpoint; /// `[otlp.metrics]` with `enabled = true` exports gateway metrics; +/// `[otlp.supervisor_metrics]` with `enabled = true` exports supervisor metrics; /// `[otlp.ocsf]` with `enabled = true` exports OCSF events as log records; and /// `[otlp.agent]` with `enabled = true` relays workload traces. Each signal /// can use a different endpoint. SDK tuning knobs are deliberately absent — @@ -405,6 +406,14 @@ pub struct OtlpConfig { serialize_with = "serialize_enabled" )] pub agent: Option, + + /// Export of supervisor egress metrics, when enabled. + #[serde( + default, + skip_serializing_if = "Option::is_none", + serialize_with = "serialize_enabled" + )] + pub supervisor_metrics: Option, } /// Writes `enabled = true` so that a serialized config parses back to the @@ -465,6 +474,10 @@ impl OtlpConfig { traces: self.traces.as_ref().map(|traces| traces.collector.export()), ocsf: self.ocsf.as_ref().map(|ocsf| ocsf.collector.export()), agent: self.agent.as_ref().map(|agent| agent.collector.export()), + metrics: self + .supervisor_metrics + .as_ref() + .map(OtlpCollectorConfig::export), } } } @@ -831,7 +844,7 @@ impl OtlpCollectorConfig { } } - fn export(&self) -> openshell_core::sandbox_env::OtlpExport { + pub(crate) fn export(&self) -> openshell_core::sandbox_env::OtlpExport { openshell_core::sandbox_env::OtlpExport { endpoint: self.endpoint.clone(), protocol: self.protocol, @@ -875,7 +888,7 @@ pub struct AgentOtlpConfig { #[serde(deny_unknown_fields)] struct RawOtlpConfig { #[serde(default)] - metrics: Option, + metrics: Option, #[serde(default)] endpoint: Option, #[serde(default)] @@ -897,33 +910,14 @@ struct RawOtlpConfig { #[serde(default)] ocsf: Option, #[serde(default)] - agent: Option, -} - -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct RawAgentOtlp { - #[serde(default)] - enabled: bool, - #[serde(default)] - endpoint: Option, - #[serde(default)] - protocol: Option, - #[serde(default)] - headers: Option>, - #[serde(default)] - headers_file: Option, + agent: Option, #[serde(default)] - ca_file: Option, - #[serde(default)] - cert_file: Option, - #[serde(default)] - key_file: Option, + supervisor_metrics: Option, } #[derive(Deserialize)] #[serde(deny_unknown_fields)] -struct RawOtlpMetrics { +struct RawEnabledOtlp { #[serde(default)] enabled: bool, #[serde(default)] @@ -1106,7 +1100,19 @@ impl TryFrom for OtlpConfig { }) }) .transpose()?; - if traces.is_none() && metrics.is_none() && ocsf.is_none() && agent.is_none() { + let supervisor_metrics = raw + .supervisor_metrics + .filter(|metrics| metrics.enabled) + .map(|metrics| { + raw_collector!(metrics).resolve("otlp.supervisor_metrics", shared.as_ref()) + }) + .transpose()?; + if traces.is_none() + && metrics.is_none() + && ocsf.is_none() + && agent.is_none() + && supervisor_metrics.is_none() + { return Err("otlp needs an endpoint, or an enabled signal table".to_string()); } let config = Self { @@ -1115,6 +1121,7 @@ impl TryFrom for OtlpConfig { traces, ocsf, agent, + supervisor_metrics, }; let supervisor_tls = config.supervisor_tls_bytes(); if supervisor_tls > MAX_SUPERVISOR_TLS_BYTES { @@ -2212,6 +2219,30 @@ service_name = "openshell-gateway-dev" assert!(otlp.service_name.is_none()); assert_eq!(otlp.ocsf, None); assert!(otlp.metrics.is_none()); + assert_eq!(otlp.supervisor_metrics, None); + } + + #[test] + fn supervisor_metrics_accepts_an_inherited_or_independent_collector() { + let inherited = otlp( + "[openshell.gateway.otlp]\nendpoint = 'https://collector:4318'\n\ + protocol = 'http/protobuf'\n\ + [openshell.gateway.otlp.supervisor_metrics]\nenabled = true\n", + ); + let metrics = inherited.supervisor_otlp().metrics.unwrap(); + assert_eq!(metrics.endpoint, "https://collector:4318"); + assert_eq!(metrics.protocol, OtlpProtocol::HttpProtobuf); + + let independent = otlp( + "[openshell.gateway.otlp.supervisor_metrics]\nenabled = true\n\ + endpoint = 'http://metrics:4317'\n", + ); + assert!(independent.traces.is_none()); + assert!(independent.metrics.is_none()); + assert_eq!( + independent.supervisor_otlp().metrics.unwrap().endpoint, + "http://metrics:4317" + ); } #[test] @@ -2256,6 +2287,7 @@ service_name = "openshell-gateway-dev" assert_eq!(metrics.endpoint, "http://metrics:4318"); assert_eq!(metrics.protocol, OtlpProtocol::HttpProtobuf); assert!(own.traces.is_none()); + assert!(own.supervisor_metrics.is_none()); let error = toml::from_str::( "[metrics]\nenabled = true\n[traces]\nendpoint = 'http://traces:4317'\n", @@ -2393,6 +2425,7 @@ service_name = "openshell-gateway-dev" traces: export("http://shared:4318", OtlpProtocol::HttpProtobuf), ocsf: export("http://shared:4318", OtlpProtocol::HttpProtobuf), agent: export("http://agents:4317", OtlpProtocol::Grpc), + metrics: None, }, "lanes without an endpoint inherit the shared protocol; a lane \ with its own endpoint does not" diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 28ee738848..da1466f974 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -934,6 +934,27 @@ pub(crate) async fn run_server( .as_ref() .and_then(|file| file.openshell.gateway.otlp.as_ref()), )); + if let Some(host) = compute.supervisor_host() + && let Some(otlp) = config_file + .as_ref() + .and_then(|file| file.openshell.gateway.otlp.as_ref()) + && let Some(collector) = otlp.supervisor_metrics.as_ref() + { + let headers = supervisor_otlp_headers(Some(otlp)); + let tls = otel_tracing::supervisor_otlp_tls(Some(otlp)); + let metrics = openshell_core::sandbox_env::SharedSupervisorMetrics { + collector: collector.export(), + gateway_name: config.name.clone(), + headers: headers.metrics, + tls: tls + .metrics + .and_then(|index| tls.materials.get(index).cloned()), + }; + let encoded = serde_json::to_vec(&metrics).map_err(|error| Error::Config { + message: format!("could not encode supervisor metrics settings: {error}"), + })?; + host.set_supervisor_metrics(encoded); + } let gateway_interceptors = if let Some(issuer) = extension_jwt_issuer.as_ref() { let mut slots = BTreeMap::new(); for interceptor in &config.gateway_interceptors { diff --git a/crates/openshell-server/src/otel_tracing.rs b/crates/openshell-server/src/otel_tracing.rs index 301c052d98..4b7a5d8eca 100644 --- a/crates/openshell-server/src/otel_tracing.rs +++ b/crates/openshell-server/src/otel_tracing.rs @@ -335,6 +335,7 @@ pub struct SupervisorOtlpHeaders { pub traces: Option, pub ocsf: Option, pub agent: Option, + pub metrics: Option, } impl SupervisorOtlpHeaders { @@ -342,6 +343,7 @@ impl SupervisorOtlpHeaders { bundle.traces_otlp_headers.clone_from(&self.traces); bundle.ocsf_otlp_headers.clone_from(&self.ocsf); bundle.agent_otlp_headers.clone_from(&self.agent); + bundle.metrics_otlp_headers.clone_from(&self.metrics); } } @@ -407,6 +409,7 @@ fn supervisor_otlp_headers_from( .agent .as_ref() .and_then(|agent| configured(&agent.collector)), + metrics: otlp.supervisor_metrics.as_ref().and_then(configured), } } @@ -419,6 +422,7 @@ pub struct SupervisorOtlpTls { pub traces: Option, pub ocsf: Option, pub agent: Option, + pub metrics: Option, } impl SupervisorOtlpTls { @@ -427,6 +431,7 @@ impl SupervisorOtlpTls { bundle.traces_otlp_tls = self.traces; bundle.ocsf_otlp_tls = self.ocsf; bundle.agent_otlp_tls = self.agent; + bundle.metrics_otlp_tls = self.metrics; } } @@ -453,10 +458,11 @@ pub fn supervisor_otlp_tls(otlp: Option<&OtlpConfig>) -> SupervisorOtlpTls { otlp.traces.as_ref().map(|traces| &traces.collector), otlp.ocsf.as_ref().map(|ocsf| &ocsf.collector), otlp.agent.as_ref().map(|agent| &agent.collector), + otlp.supervisor_metrics.as_ref(), ]; let mut materials = Vec::new(); let mut seen = Vec::new(); - let [traces, ocsf, agent] = lanes.map(|collector| { + let [traces, ocsf, agent, metrics] = lanes.map(|collector| { let collector = collector?; let pem = (collector.tls().ca_pem(), collector.tls().client_identity()); if let Some(index) = seen.iter().position(|seen| *seen == pem) { @@ -471,6 +477,7 @@ pub fn supervisor_otlp_tls(otlp: Option<&OtlpConfig>) -> SupervisorOtlpTls { traces, ocsf, agent, + metrics, } } @@ -819,6 +826,7 @@ mod tests { }), ocsf: None, agent: None, + supervisor_metrics: None, } } @@ -994,6 +1002,7 @@ mod tests { agent: Some(AgentOtlpConfig { collector: collector("https://agents:4318"), }), + supervisor_metrics: None, }; let tls = supervisor_otlp_tls(Some(&otlp)); diff --git a/crates/openshell-server/src/persistence/mutation_lock_pg_tests.rs b/crates/openshell-server/src/persistence/mutation_lock_pg_tests.rs index 636fff35b8..907e19ffda 100644 --- a/crates/openshell-server/src/persistence/mutation_lock_pg_tests.rs +++ b/crates/openshell-server/src/persistence/mutation_lock_pg_tests.rs @@ -92,10 +92,12 @@ async fn postgres_concurrent_sandbox_creates_with_ssh_identity_do_not_exhaust_lo ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, + metrics_otlp_headers: None, agent_otlp_headers: None, otlp_tls: Vec::new(), traces_otlp_tls: None, ocsf_otlp_tls: None, + metrics_otlp_tls: None, agent_otlp_tls: None, }, gateway_id: "gateway".to_string(), @@ -214,10 +216,12 @@ fn ssh_launch_authentication() -> openshell_core::jwt::SandboxLaunchAuthenticati ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, + metrics_otlp_headers: None, agent_otlp_headers: None, otlp_tls: Vec::new(), traces_otlp_tls: None, ocsf_otlp_tls: None, + metrics_otlp_tls: None, agent_otlp_tls: None, }, gateway_id: "gateway".to_string(), diff --git a/crates/openshell-server/src/ssh_identity.rs b/crates/openshell-server/src/ssh_identity.rs index 49a035d615..e89e296895 100644 --- a/crates/openshell-server/src/ssh_identity.rs +++ b/crates/openshell-server/src/ssh_identity.rs @@ -84,10 +84,12 @@ mod tests { ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, + metrics_otlp_headers: None, agent_otlp_headers: None, otlp_tls: Vec::new(), traces_otlp_tls: None, ocsf_otlp_tls: None, + metrics_otlp_tls: None, agent_otlp_tls: None, }, gateway_id: "gateway".to_string(), diff --git a/crates/openshell-supervisor-control/src/controller.rs b/crates/openshell-supervisor-control/src/controller.rs index 71a772b3dd..b5d6cc49a6 100644 --- a/crates/openshell-supervisor-control/src/controller.rs +++ b/crates/openshell-supervisor-control/src/controller.rs @@ -362,6 +362,7 @@ struct Inner { observed: Mutex, /// This replica's peer endpoint, sent in every `HostAccepted`. peer_endpoint: Mutex, + supervisor_metrics: Mutex>, } /// Gateway-owned desired assignments and observed status of the shared @@ -413,6 +414,7 @@ impl SupervisorHostController { membership: watch::Sender::new(0), observed: Mutex::new(Observed::default()), peer_endpoint: Mutex::new(String::new()), + supervisor_metrics: Mutex::new(Vec::new()), }), } } @@ -423,6 +425,11 @@ impl SupervisorHostController { *lock(&self.inner.peer_endpoint) = peer_endpoint; } + /// Set the collector configuration sent to authenticated supervisors. + pub fn set_supervisor_metrics(&self, configuration: Vec) { + *lock(&self.inner.supervisor_metrics) = configuration; + } + /// Offer every instance's runtime `recovery_timeout_secs` instead of /// [`POOL_RECOVERY_TIMEOUT_SECS`]. Call it before any host attaches. pub fn set_recovery_timeout_secs(&self, recovery_timeout_secs: u32) { @@ -873,6 +880,7 @@ impl SupervisorHostController { let expires_at = identity.expires_at; let (session_id, superseded) = self.begin_session(identity, &hello)?; let peer_endpoint = lock(&self.inner.peer_endpoint).clone(); + let supervisor_metrics = lock(&self.inner.supervisor_metrics).clone(); tx.send(Ok(HostGatewayMessage { payload: Some(host_gateway_message::Payload::Accepted(HostAccepted { session_id: session_id.to_string(), @@ -881,6 +889,7 @@ impl SupervisorHostController { nanos: 0, }), peer_endpoint, + supervisor_metrics, })), })) .await diff --git a/crates/openshell-supervisor/src/backend_setup/tests.rs b/crates/openshell-supervisor/src/backend_setup/tests.rs index 822cf1ae26..1239250f0f 100644 --- a/crates/openshell-supervisor/src/backend_setup/tests.rs +++ b/crates/openshell-supervisor/src/backend_setup/tests.rs @@ -161,10 +161,12 @@ impl TestSetup { ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, + metrics_otlp_headers: None, agent_otlp_headers: None, otlp_tls: Vec::new(), traces_otlp_tls: None, ocsf_otlp_tls: None, + metrics_otlp_tls: None, agent_otlp_tls: None, }, sandbox_id: "sandbox-1".to_string(), diff --git a/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs b/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs index a28e0cf4bf..de2532e4b6 100644 --- a/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs +++ b/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs @@ -274,10 +274,12 @@ async fn config_push_regression_legacy_gateway_never_observes_ready_before_workl ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, + metrics_otlp_headers: None, agent_otlp_headers: None, otlp_tls: Vec::new(), traces_otlp_tls: None, ocsf_otlp_tls: None, + metrics_otlp_tls: None, agent_otlp_tls: None, }; let setup = HeldBackendSetup { diff --git a/crates/openshell-supervisor/src/lib.rs b/crates/openshell-supervisor/src/lib.rs index fba41bb4e7..0cfb8fbad9 100644 --- a/crates/openshell-supervisor/src/lib.rs +++ b/crates/openshell-supervisor/src/lib.rs @@ -4758,10 +4758,12 @@ mod tests { ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, + metrics_otlp_headers: None, agent_otlp_headers: None, otlp_tls: Vec::new(), traces_otlp_tls: None, ocsf_otlp_tls: None, + metrics_otlp_tls: None, agent_otlp_tls: None, }; let config = SandboxInstanceConfig { diff --git a/crates/openshell-supervisor/src/main.rs b/crates/openshell-supervisor/src/main.rs index 6c54c03ee9..c2a0cb196e 100644 --- a/crates/openshell-supervisor/src/main.rs +++ b/crates/openshell-supervisor/src/main.rs @@ -1223,10 +1223,12 @@ mod tests { ssh_host_private_key: None, traces_otlp_headers: secret("lane=traces"), ocsf_otlp_headers: secret("lane=ocsf"), + metrics_otlp_headers: None, agent_otlp_headers: secret("lane=agent"), otlp_tls: vec![tls("ocsf-ca"), tls("traces-ca")], traces_otlp_tls: Some(1), ocsf_otlp_tls: Some(0), + metrics_otlp_tls: None, agent_otlp_tls: None, }; diff --git a/crates/openshell-supervisor/src/shared_host.rs b/crates/openshell-supervisor/src/shared_host.rs index 3785deaa8d..900b5af3c8 100644 --- a/crates/openshell-supervisor/src/shared_host.rs +++ b/crates/openshell-supervisor/src/shared_host.rs @@ -2096,6 +2096,7 @@ mod tests { nanos: 0, }), peer_endpoint: peer_endpoint.to_string(), + supervisor_metrics: Vec::new(), }, )) } diff --git a/proto/supervisor_host.proto b/proto/supervisor_host.proto index 3195837eff..55bfeb0c3a 100644 --- a/proto/supervisor_host.proto +++ b/proto/supervisor_host.proto @@ -94,6 +94,10 @@ message HostAccepted { // instances' sessions here so they run on the replica serving this stream. // Empty when the replica has no peer endpoint. string peer_endpoint = 3; + // Optional JSON-encoded OTLP configuration for the host's own metrics. + // Includes collector credentials and is sent only over this authenticated + // supervisor stream. + bytes supervisor_metrics = 4; } // Another gateway replica should serve the host, which dials it at once. The From 5eedd0efb777ccac28093fba921e42274ac42714 Mon Sep 17 00:00:00 2001 From: Eitan Geiger Date: Wed, 18 Nov 2026 21:13:28 +0200 Subject: [PATCH 4/6] feat(supervisor): export egress metrics over OTLP Start an OTLP metrics provider in each configured supervisor runtime. Attach the gateway name and a per-process instance ID as resource attributes for grouping metrics by gateway and supervisor. Register the network instruments and report sandbox assignments with a gauge. Clear the assignment count before flushing on shutdown. Document the gateway opt-in, metric catalog, and admission semantics. Signed-off-by: Eitan Geiger --- crates/openshell-otel/src/lib.rs | 2 + crates/openshell-supervisor/src/lib.rs | 1 + crates/openshell-supervisor/src/main.rs | 39 ++++- crates/openshell-supervisor/src/metrics.rs | 146 ++++++++++++++++++ .../openshell-supervisor/src/shared_host.rs | 51 +++++- docs/how-it-works/gateways/configuration.mdx | 17 ++ docs/observability/gateway-metrics.mdx | 50 ++++++ docs/observability/overview.mdx | 3 +- skills/debug-openshell-cluster/SKILL.md | 1 + 9 files changed, 307 insertions(+), 3 deletions(-) create mode 100644 crates/openshell-supervisor/src/metrics.rs diff --git a/crates/openshell-otel/src/lib.rs b/crates/openshell-otel/src/lib.rs index b8c2f4d79b..154154da9d 100644 --- a/crates/openshell-otel/src/lib.rs +++ b/crates/openshell-otel/src/lib.rs @@ -68,6 +68,8 @@ pub use headers::{encode_otlp_headers, merge_otlp_headers, parse_otlp_headers}; #[cfg(feature = "export")] pub use ocsf::{OcsfOtlp, OcsfOtlpLayer}; #[cfg(feature = "export")] +pub use opentelemetry_sdk::metrics::SdkMeterProvider; +#[cfg(feature = "export")] pub use tls::{MAX_TLS_FILE_BYTES, OtlpTls, TlsError, TlsFileError}; #[cfg(feature = "export")] pub use transport::{ diff --git a/crates/openshell-supervisor/src/lib.rs b/crates/openshell-supervisor/src/lib.rs index 0cfb8fbad9..e736528b5a 100644 --- a/crates/openshell-supervisor/src/lib.rs +++ b/crates/openshell-supervisor/src/lib.rs @@ -24,6 +24,7 @@ mod config_runtime; mod denial_aggregator; mod endpoint_status; mod mechanistic_mapper; +pub mod metrics; mod otlp_relay; mod provider_readiness; pub mod sandbox_instance_host; diff --git a/crates/openshell-supervisor/src/main.rs b/crates/openshell-supervisor/src/main.rs index c2a0cb196e..e1d6a51fef 100644 --- a/crates/openshell-supervisor/src/main.rs +++ b/crates/openshell-supervisor/src/main.rs @@ -7,7 +7,7 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; -use std::sync::atomic::AtomicBool; +use std::sync::atomic::{AtomicBool, Ordering}; use clap::{Parser, ValueEnum}; use miette::{IntoDiagnostic, Result}; @@ -168,6 +168,14 @@ struct Args { #[arg(long, env = openshell_core::sandbox_env::OTLP_AGENT_PROTOCOL, default_value_t)] otlp_agent_protocol: OtlpProtocol, + /// Collector for this supervisor's egress metrics. + #[arg(long, env = openshell_core::sandbox_env::OTLP_METRICS_ENDPOINT)] + otlp_metrics_endpoint: Option, + + /// OTLP transport for egress metrics. + #[arg(long, env = openshell_core::sandbox_env::OTLP_METRICS_PROTOCOL, default_value_t)] + otlp_metrics_protocol: OtlpProtocol, + /// Name of the gateway that launched this sandbox, for telemetry. #[arg(long, env = openshell_core::sandbox_env::GATEWAY_NAME)] gateway_name: Option, @@ -534,6 +542,28 @@ fn main() -> Result<()> { settings.ocsf, ) }); + let sandbox_assigned = Arc::new(AtomicBool::new(isolation_inputs.is_some())); + let metrics = runtime.block_on(async { + let auth = isolation_inputs.as_ref().map(|(_, _, auth, _, _)| auth); + args.otlp_metrics_endpoint + .as_deref() + .map(|endpoint| { + let assigned = sandbox_assigned.clone(); + openshell_supervisor::metrics::start( + endpoint, + args.otlp_metrics_protocol, + auth.map(SupervisorAuthBundle::metrics_otlp) + .unwrap_or_default(), + args.gateway_name.as_deref(), + move || u64::from(assigned.load(Ordering::Relaxed)), + ) + }) + .transpose() + }); + let (metrics_provider, metrics_setup_error) = match metrics { + Ok(provider) => (provider, None), + Err(error) => (None, Some(error)), + }; let otlp_layer_provider = otlp_provider.clone(); let ocsf_layer = ocsf_export.as_ref().map(openshell_otel::OcsfOtlp::layer); @@ -593,6 +623,9 @@ fn main() -> Result<()> { } else if let Some(endpoint) = &args.otlp_ocsf_endpoint { info!(endpoint, protocol = %args.otlp_ocsf_protocol, "OTLP OCSF export enabled"); } + if let Some(error) = metrics_setup_error { + warn!(%error, "OTLP metrics export could not be started"); + } let workdir = args.workdir.clone(); let (command, interactive, await_main_process_attachment) = if !args.command.is_empty() { @@ -734,6 +767,10 @@ fn main() -> Result<()> { { warn!(%error, "OTLP tracer provider shutdown failed"); } + if let Some(provider) = metrics_provider.as_ref() { + sandbox_assigned.store(false, Ordering::Relaxed); + openshell_supervisor::metrics::shutdown(provider); + } std::process::exit(exit_code?); } diff --git a/crates/openshell-supervisor/src/metrics.rs b/crates/openshell-supervisor/src/metrics.rs new file mode 100644 index 0000000000..d52f17ae18 --- /dev/null +++ b/crates/openshell-supervisor/src/metrics.rs @@ -0,0 +1,146 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Process-owned supervisor metrics export. + +use openshell_core::jwt::{OtlpExportCredentials, OtlpTlsMaterial, SecretOtlpHeaders}; +use openshell_core::sandbox_env::OtlpProtocol; +use openshell_otel::{ + CollectorTransport, OtlpExportConfig, OtlpTarget, SdkMeterProvider, ServiceName, SetupError, +}; +use opentelemetry::KeyValue; +use opentelemetry::metrics::MeterProvider as _; + +const SERVICE_NAME: &str = "openshell-supervisor"; + +/// Create the process's metrics provider inside the runtime driving OTLP. +pub fn start( + endpoint: &str, + protocol: OtlpProtocol, + credentials: OtlpExportCredentials<'_>, + gateway_name: Option<&str>, + sandbox_count: impl Fn() -> u64 + Send + Sync + 'static, +) -> Result { + let mut resource_attributes = openshell_otel::gateway_resource_attributes(gateway_name, None); + resource_attributes.push(KeyValue::new( + "service.instance.id", + uuid::Uuid::new_v4().to_string(), + )); + let config = OtlpExportConfig { + endpoint, + service_name: ServiceName::Fixed(SERVICE_NAME), + service_version: Some(openshell_core::VERSION), + resource_attributes, + }; + let transport = CollectorTransport { + protocol: protocol.into(), + headers: credentials + .headers + .map(SecretOtlpHeaders::expose_secret) + .map(openshell_otel::parse_otlp_headers) + .unwrap_or_default(), + tls: credentials + .tls + .map(OtlpTlsMaterial::otlp_tls) + .transpose()? + .unwrap_or_default(), + }; + let provider = OtlpTarget::new(&config)? + .with_transport(&transport) + .meter_provider()?; + let meter = provider.meter(SERVICE_NAME); + openshell_supervisor_network::metrics::install(&meter); + meter + .u64_observable_gauge("openshell_supervisor_sandboxes_active") + .with_description("Sandboxes assigned to this supervisor.") + .with_callback(move |observer| observer.observe(sandbox_count(), &[])) + .build(); + Ok(provider) +} + +/// Flush final metrics with the SDK reader's bounded shutdown wait. +pub fn shutdown(provider: &SdkMeterProvider) { + if let Err(error) = provider.shutdown() { + tracing::warn!(%error, "OTLP metrics provider shutdown failed"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use openshell_otel_test_support::OtlpHttpTestServer; + use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest; + use opentelemetry_proto::tonic::metrics::v1::metric::Data; + use prost::Message as _; + + #[tokio::test(flavor = "multi_thread")] + async fn pushes_supervisor_gauges_and_resource_to_the_collector() { + let mut collector = OtlpHttpTestServer::start().await; + let path = format!("{}/receiver", collector.endpoint()); + let headers = SecretOtlpHeaders::new("x-collector-test=metrics".to_string()); + let count = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(2)); + let provider = start( + &path, + OtlpProtocol::HttpProtobuf, + OtlpExportCredentials { + headers: Some(&headers), + tls: None, + }, + Some("test-gateway"), + { + let count = count.clone(); + move || count.load(std::sync::atomic::Ordering::Relaxed) + }, + ) + .unwrap(); + + for assigned in [2, 1, 0] { + count.store(assigned, std::sync::atomic::Ordering::Relaxed); + let flush = provider.clone(); + tokio::task::spawn_blocking(move || flush.force_flush().unwrap()) + .await + .unwrap(); + let received = collector.next_export().await; + assert_eq!(received.path, "/receiver/v1/metrics"); + assert_eq!(received.headers.get("x-collector-test").unwrap(), "metrics"); + let response = ExportMetricsServiceRequest::decode(received.body).unwrap(); + let resource = &response.resource_metrics[0]; + let attributes = &resource.resource.as_ref().unwrap().attributes; + assert!(attributes.iter().any(|kv| kv.key == "service.instance.id")); + assert!( + attributes + .iter() + .any(|kv| kv.key == "openshell.gateway.name") + ); + let instruments = resource + .scope_metrics + .iter() + .flat_map(|scope| &scope.metrics) + .collect::>(); + let sandboxes = instruments + .iter() + .find(|metric| metric.name == "openshell_supervisor_sandboxes_active") + .unwrap(); + let Some(Data::Gauge(gauge)) = &sandboxes.data else { + panic!("Expected the assigned sandbox gauge"); + }; + let sample = &gauge.data_points[0]; + assert_eq!(sample.attributes, []); + assert_eq!( + sample.value, + Some( + opentelemetry_proto::tonic::metrics::v1::number_data_point::Value::AsInt( + i64::try_from(assigned).unwrap() + ) + ), + ); + assert!(instruments.iter().any(|metric| { + metric.name == "openshell_supervisor_connections_active" + && matches!(metric.data, Some(Data::Gauge(_))) + })); + } + tokio::task::spawn_blocking(move || shutdown(&provider)) + .await + .unwrap(); + } +} diff --git a/crates/openshell-supervisor/src/shared_host.rs b/crates/openshell-supervisor/src/shared_host.rs index 900b5af3c8..c2a2b4e384 100644 --- a/crates/openshell-supervisor/src/shared_host.rs +++ b/crates/openshell-supervisor/src/shared_host.rs @@ -28,7 +28,7 @@ use std::collections::BTreeMap; use std::future::Future; use std::net::SocketAddr; use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, OnceLock}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use miette::Result; @@ -196,6 +196,7 @@ pub struct SharedHost { /// Routes of the latest applied snapshot, so a withdrawal whose cleanup /// failed can be retried without the gateway resending the snapshot. desired_routes: Mutex>>, + metrics_provider: OnceLock, /// This process's identity as a member of the supervisor pool. pool: PoolIdentity, /// Routes of the latest snapshot listed for stopping. Every other route @@ -311,6 +312,7 @@ impl SharedHost { attach_request_timeout: config.attach_request_timeout, rejected: Mutex::new(BTreeMap::new()), desired_routes: Mutex::new(None), + metrics_provider: OnceLock::new(), pool: config.pool, stop_routes: Mutex::new(std::collections::BTreeSet::new()), deferred: Mutex::new(None), @@ -372,6 +374,50 @@ impl SharedHost { /// keep running. pub async fn shut_down(&self) { self.host.relinquish_all().await; + if let Some(provider) = self.metrics_provider.get().cloned() { + *self + .desired_routes + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = None; + let _ = tokio::task::spawn_blocking(move || crate::metrics::shutdown(&provider)).await; + } + } + + fn start_metrics(self: &Arc, configuration: &[u8]) { + if configuration.is_empty() || self.metrics_provider.get().is_some() { + return; + } + let Ok(config) = serde_json::from_slice::< + openshell_core::sandbox_env::SharedSupervisorMetrics, + >(configuration) else { + tracing::warn!("Invalid supervisor metrics settings from gateway"); + return; + }; + let host = Arc::downgrade(self); + let result = crate::metrics::start( + &config.collector.endpoint, + config.collector.protocol, + openshell_core::jwt::OtlpExportCredentials { + headers: config.headers.as_ref(), + tls: config.tls.as_ref(), + }, + Some(&config.gateway_name), + move || host.upgrade().map_or(0, |host| host.assigned_sandboxes()), + ); + match result { + Ok(provider) => { + let _ = self.metrics_provider.set(provider); + } + Err(error) => tracing::warn!(%error, "OTLP metrics export could not be started"), + } + } + + fn assigned_sandboxes(&self) -> u64 { + self.desired_routes + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_ref() + .map_or(0, |routes| routes.len() as u64) } /// Address of the routed runtime listener. @@ -1500,6 +1546,7 @@ async fn run_stream( last_heard = tokio::time::Instant::now(); match payload { Some(host_gateway_message::Payload::Accepted(accepted_message)) => { + host.start_metrics(&accepted_message.supervisor_metrics); accepted = true; host.gateway_connected.send_replace(true); host.gateway_home.send_replace(Some(accepted_message.peer_endpoint.clone())); @@ -1713,6 +1760,7 @@ mod tests { }, }) .unwrap(); + assert_eq!(host.assigned_sandboxes(), 0); let routes = [ "rt-kept-0123456789", "rt-released-012345", @@ -1749,6 +1797,7 @@ mod tests { }) .await .unwrap(); + assert_eq!(host.assigned_sandboxes(), 1); // The kept instance is untouched; the released one ended without // stopping its workload; only the withdrawn one was stopped. diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index 52bb44113d..f126e32351 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -981,6 +981,23 @@ A collector can accept a batch while rejecting some of its records, an OTLP part Metrics include `openshell_ocsf_otlp_queued_total`, `openshell_ocsf_otlp_exported_total`, `openshell_ocsf_otlp_dropped_total` (with a `reason` label of `queue_capacity`, `queue_bytes`, `oversized`, `export_failed`, `serialization`, or `closed`), `openshell_ocsf_otlp_export_errors_total`, and `openshell_ocsf_otlp_retries_total`. +### Supervisor Metrics Export + +Enable supervisor egress metrics in `gateway.toml`. + +```toml +[openshell.gateway.otlp.supervisor_metrics] +enabled = true +endpoint = "https://otel-collector.observability.svc:4317" +``` + +Omit `endpoint` to inherit the full `[openshell.gateway.otlp]` collector +configuration. With its own endpoint, this table accepts the same protocol, +header, and TLS settings as the base collector table. The collector must be +reachable from supervisor processes. In Helm, put the table under +`gatewayConfig`. See [Supervisor Metrics](/observability/gateway-metrics#supervisor-metrics) +for the catalog. + ### 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: diff --git a/docs/observability/gateway-metrics.mdx b/docs/observability/gateway-metrics.mdx index 5f24a9e192..d33a6c5ab0 100644 --- a/docs/observability/gateway-metrics.mdx +++ b/docs/observability/gateway-metrics.mdx @@ -12,6 +12,56 @@ The gateway exports Prometheus metrics for API requests, database readiness, gateway interceptors, the OCSF log file, and multi-replica capacity. Use them to alert on saturation, to follow rollouts, and to choose autoscaling signals. +Supervisors push egress metrics to an OTLP collector. + +## Supervisor Metrics + +Enable [supervisor metrics export](/how-it-works/gateways/configuration#supervisor-metrics-export) +and configure your collector to forward the metrics to your backend. +`openshell.gateway.name` and `service.instance.id` are OTLP resource attributes +for grouping by gateway and supervisor process. + +| Metric | Type | Labels | Measures | +| --- | --- | --- | --- | +| `openshell_supervisor_egress_decisions_total` | Counter | `scope`, `outcome`, `inspection_type`, `policy` | Final egress admission decisions. | +| `openshell_supervisor_policy_evaluation_duration_seconds` | Histogram | `scope`, `result` | Policy evaluation, including input construction and engine lock wait. | +| `openshell_supervisor_request_inspection_duration_seconds` | Histogram | `scope`, `inspection_type`, `result` | Inspection of a request or message before forwarding. | +| `openshell_supervisor_upstream_connect_duration_seconds` | Histogram | `route`, `result` | New upstream connections, including address fallback and proxy negotiation. | +| `openshell_supervisor_connections_active` | Gauge | `inspection_type` | Live proxied connections. | +| `openshell_supervisor_sandboxes_active` | Gauge | | Sandbox assignments held by this supervisor. | + +Decision scopes are `connection`, `request`, and `message`. Outcomes are +`allow`, `deny`, `audit`, and `fail_open`. All histograms use the results +`success`, `deny`, `error`, `timeout`, and `cancelled`, with explicit duration +buckets from 0.1 milliseconds to 15 seconds. Upstream routes are `direct` and +`proxy`. Inspection types are `tcp`, `http`, `rest`, `graphql`, `json-rpc`, +`mcp`, `websocket`, and `unknown`. + +A decision records one outcome. A denial takes precedence over `fail_open`, +which takes precedence over `audit`. CONNECT allows are counted when the tunnel +is admitted to relay, after any required TLS handshake. The OCSF CONNECT allow +records the earlier `200 Connection Established` response. + +A supervisor retains the first 16 distinct attributed policy names of up to +128 bytes for its lifetime. `no_match` means evaluation matched no configured +policy. `unattributed` means the decision has no available policy name. +Additional or longer names use `overflow`. A policy name that collides +with a reserved value is prefixed with `name:`. + +In Prometheus, these queries show decisions by outcome and policy and the 95th +percentile for upstream connects. Adjust the names if your collector renames +the metrics. + +```promql +sum by (outcome, policy) (rate(openshell_supervisor_egress_decisions_total[5m])) +``` + +```promql +histogram_quantile(0.95, sum by (le, route) ( + rate(openshell_supervisor_upstream_connect_duration_seconds_bucket[5m]) +)) +``` + ## Enable the Metrics Endpoint The gateway serves `GET /metrics` in the Prometheus text format on its own diff --git a/docs/observability/overview.mdx b/docs/observability/overview.mdx index d6b5cfe6bd..a5a6d701de 100644 --- a/docs/observability/overview.mdx +++ b/docs/observability/overview.mdx @@ -14,7 +14,8 @@ OpenShell produces three kinds of observability signals: traces, metrics, and OC |---|---|---| | Traces | Gateway, compute drivers, sandbox supervisors | OTLP collector | | Agent traces | Agents, relayed by sandbox supervisors | OTLP collector | -| Metrics | Gateway | Prometheus scrape, optional OTLP push | +| Gateway metrics | Gateway | Prometheus scrape, optional OTLP push | +| Supervisor egress metrics | Sandbox supervisors | OTLP collector | | OCSF events, shorthand | Gateway, sandbox supervisors | Gateway console, `openshell logs`, supervisor log file | | OCSF events, JSONL | Gateway, sandbox supervisors | Local file | | OCSF events, OTLP | Gateway, sandbox supervisors | OTLP collector | diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index 8304a4a58e..9c2506bd0a 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -1646,6 +1646,7 @@ credential failures. | Collector receives no OCSF log records, or `openshell.ocsf.gap` records | `[openshell.gateway.otlp.ocsf]` missing or without `enabled = true`, an unreachable endpoint or one that does not speak the table's `protocol`, or export failures and queue pressure | Check `[openshell.gateway.otlp.ocsf]` for `enabled = true` and the endpoint it resolves to, the gateway's `OTLP exporting enabled` startup log for `ocsf_endpoint` and `ocsf_protocol`, export warnings, and `openshell_ocsf_otlp_*` metrics. See the published [gateway configuration reference](https://docs.nvidia.com/openshell/latest/how-it-works/gateways/configuration). | | Gateway OCSF JSONL stops growing, has gaps, or is rejected by a SIEM | File errors, queue pressure, or shipper falling behind retention | Inspect gateway warnings and `openshell_ocsf_log_*` metrics; check `[openshell.gateway.ocsf_log]`, directory permissions, free space, per-replica paths, and shipper rotation checkpoints. See the published [gateway configuration reference](https://docs.nvidia.com/openshell/latest/how-it-works/gateways/configuration). | | `BatchSpanProcessor.ExportError` repeatedly reports connection refused on `127.0.0.1:4317` | The local gateway started with `OPENSHELL_DEV_OTLP_ENDPOINT` set but no collector is listening, for example because `helm:k3s:forward` stopped | Start the collector forwarding again, or restart the gateway task without `OPENSHELL_DEV_OTLP_ENDPOINT`; inspect the generated `gateway.toml` for `[openshell.gateway.otlp]` | +| Collector receives no supervisor metrics | Supervisor metrics export is off, or the collector cannot receive OTLP from the supervisor | Check `enabled = true` in `[openshell.gateway.otlp.supervisor_metrics]`, the resolved collector endpoint and protocol, and the supervisor's OTLP export warnings. See the published [gateway configuration reference](https://docs.nvidia.com/openshell/latest/how-it-works/gateways/configuration). | | Sandbox log shows `OTLP agent trace relay inactive: not enabled by the gateway` at startup, then `agent OTLP export attempted but the agent trace relay is not enabled` when the agent exports | The gateway does not enable `[openshell.gateway.otlp.agent]`, so the supervisor refuses the workload's OTLP relay address | Set `enabled = true` in `[openshell.gateway.otlp.agent]` (Helm: `gatewayConfig."openshell.gateway.otlp.agent".enabled`) with an endpoint from that table or `[openshell.gateway.otlp]`, and recreate the sandbox; `openshell logs --source sandbox` then shows `OTLP agent trace relay enabled` | | Gateway starts but sandbox create fails | Compute driver cannot reach runtime | Docker/Podman/Kubernetes/VM driver logs | | Docker or Podman sandbox never registers | Wrong gateway endpoint, unavailable host networking, or supervisor startup failure | Gateway logs and supervisor container logs | From c0d61cfd607e011a33c78ad3daa6c57a7263014d Mon Sep 17 00:00:00 2001 From: Eitan Geiger Date: Sun, 22 Nov 2026 14:06:11 +0200 Subject: [PATCH 5/6] feat(supervisor): use meaningful IDs for OTLP resource attributes OTLP metrics emitted by the supervisor now use meaningful IDs so a user could backtrack from a metric to the supervisor that sent it. For dedicated supervisor this is `SupervisorHello.instance_id` while for shared supervisor this is `HostHello.instance_id`. Signed-off-by: Eitan Geiger --- .../openshell-supervisor-process/Cargo.toml | 2 +- .../src/delegated.rs | 5 ++- .../src/backend_setup/tests.rs | 2 + .../src/legacy_startup_regression_tests.rs | 1 + crates/openshell-supervisor/src/lib.rs | 5 +++ crates/openshell-supervisor/src/main.rs | 42 +++++++++++++------ crates/openshell-supervisor/src/metrics.rs | 13 +++--- .../openshell-supervisor/src/shared_host.rs | 9 ++-- docs/observability/gateway-metrics.mdx | 6 +++ docs/observability/traces.mdx | 1 + 10 files changed, 62 insertions(+), 24 deletions(-) diff --git a/crates/openshell-supervisor-process/Cargo.toml b/crates/openshell-supervisor-process/Cargo.toml index 5e6af570f9..1b1dcd5cd9 100644 --- a/crates/openshell-supervisor-process/Cargo.toml +++ b/crates/openshell-supervisor-process/Cargo.toml @@ -31,7 +31,6 @@ tokio-stream = { workspace = true } tonic = { workspace = true, features = ["channel", "tls-native-roots"] } tracing = { workspace = true } tracing-subscriber = { workspace = true } -uuid = { workspace = true } [target.'cfg(unix)'.dependencies] libc = "0.2" @@ -44,6 +43,7 @@ openshell-ocsf = { path = "../openshell-ocsf", features = ["test-support"] } openshell-ocsf-validate = { path = "../openshell-ocsf-validate" } tempfile = "3" tokio = { workspace = true, features = ["test-util"] } +uuid = { workspace = true } [lints] workspace = true diff --git a/crates/openshell-supervisor-process/src/delegated.rs b/crates/openshell-supervisor-process/src/delegated.rs index 4f6edaac11..a88fef109c 100644 --- a/crates/openshell-supervisor-process/src/delegated.rs +++ b/crates/openshell-supervisor-process/src/delegated.rs @@ -82,6 +82,7 @@ impl Drop for BoundaryAccess { #[allow(clippy::too_many_arguments)] pub async fn start_boundary_access( sandbox_id: Option<&str>, + instance_id: String, gateway: Option<&openshell_core::grpc_client::GatewayEndpoint>, ssh_socket_path: Option<&str>, shared_ssh_socket: bool, @@ -96,7 +97,6 @@ pub async fn start_boundary_access( gateway_home: Option>>, app_installations: Option, ) -> Result { - let instance_id = uuid::Uuid::new_v4().to_string(); let terminating = Arc::new(AtomicBool::new(false)); let attachment = agent .attach() @@ -367,6 +367,7 @@ mod tests { ); let access = start_boundary_access( Some("sandbox"), + "registered-supervisor".into(), Some(&gateway), None, false, @@ -383,6 +384,7 @@ mod tests { ) .await .expect("access without SSH is portable"); + assert_eq!(access.instance_id(), "registered-supervisor"); assert!(access.ssh_task.is_none()); assert!(access.session_task.is_some()); assert!( @@ -410,6 +412,7 @@ mod tests { let boundary = Arc::new(AccessBoundary); let result = start_boundary_access( None, + "registered-supervisor".into(), None, Some("health.sock"), false, diff --git a/crates/openshell-supervisor/src/backend_setup/tests.rs b/crates/openshell-supervisor/src/backend_setup/tests.rs index 1239250f0f..dfbb483b94 100644 --- a/crates/openshell-supervisor/src/backend_setup/tests.rs +++ b/crates/openshell-supervisor/src/backend_setup/tests.rs @@ -835,6 +835,7 @@ async fn shared_startup_uses_selected_backend_through_readiness_and_shutdown() { .store(true, Ordering::SeqCst); let startup = |await_main_process_attachment| { let config = crate::SandboxInstanceConfig { + supervisor_instance_id: uuid::Uuid::new_v4().to_string(), app_router: None, command: vec!["test-agent".into(), "test-argument".into()], workdir: Some("/test-workspace".into()), @@ -1053,6 +1054,7 @@ async fn suspend_signal_exits_without_terminating_boundary() { let setup = TestSetup::new(); let startup = || { let config = crate::SandboxInstanceConfig { + supervisor_instance_id: uuid::Uuid::new_v4().to_string(), app_router: None, command: vec!["test-agent".into(), "test-argument".into()], workdir: Some("/test-workspace".into()), diff --git a/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs b/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs index de2532e4b6..3e1d2a81a3 100644 --- a/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs +++ b/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs @@ -287,6 +287,7 @@ async fn config_push_regression_legacy_gateway_never_observes_ready_before_workl probe: probe.clone(), }; let config = SandboxInstanceConfig { + supervisor_instance_id: uuid::Uuid::new_v4().to_string(), app_router: None, command: vec!["true".into()], workdir: None, diff --git a/crates/openshell-supervisor/src/lib.rs b/crates/openshell-supervisor/src/lib.rs index e736528b5a..de7e3a2317 100644 --- a/crates/openshell-supervisor/src/lib.rs +++ b/crates/openshell-supervisor/src/lib.rs @@ -906,6 +906,8 @@ pub fn trace_context_from_environment() -> Option { /// from its [`SandboxInstanceBindings`], so one process can host several /// instances. pub struct SandboxInstanceConfig { + /// Instance ID sent on this sandbox's supervisor control stream. + pub supervisor_instance_id: String, pub app_router: Option, pub command: Vec, pub workdir: Option, @@ -1089,6 +1091,7 @@ pub async fn run_sandbox_instance( controls: SandboxInstanceControls, ) -> Result { let SandboxInstanceConfig { + supervisor_instance_id, app_router, command, workdir, @@ -1764,6 +1767,7 @@ pub async fn run_sandbox_instance( let agent = running.agent(); let boundary_access = openshell_supervisor_process::delegated::start_boundary_access( sandbox_id.as_deref(), + supervisor_instance_id, gateway.as_ref(), ssh_socket_path.as_deref(), shared_ssh_socket, @@ -4768,6 +4772,7 @@ mod tests { agent_otlp_tls: None, }; let config = SandboxInstanceConfig { + supervisor_instance_id: uuid::Uuid::new_v4().to_string(), app_router: None, command: vec!["true".to_string()], workdir: None, diff --git a/crates/openshell-supervisor/src/main.rs b/crates/openshell-supervisor/src/main.rs index e1d6a51fef..83b44f7b23 100644 --- a/crates/openshell-supervisor/src/main.rs +++ b/crates/openshell-supervisor/src/main.rs @@ -515,11 +515,13 @@ fn main() -> Result<()> { .enable_all() .build() .into_diagnostic()?; + let instance_id = uuid::Uuid::new_v4().to_string(); let export_config = |endpoint| openshell_otel::OtlpExportConfig { endpoint, service_name: openshell_otel::ServiceName::Fixed(SERVICE_NAME), service_version: Some(openshell_core::VERSION), resource_attributes: supervisor_resource_attributes( + &instance_id, args.sandbox_id.as_deref(), args.gateway_name.as_deref(), ), @@ -550,6 +552,7 @@ fn main() -> Result<()> { .map(|endpoint| { let assigned = sandbox_assigned.clone(); openshell_supervisor::metrics::start( + &instance_id, endpoint, args.otlp_metrics_protocol, auth.map(SupervisorAuthBundle::metrics_otlp) @@ -657,7 +660,7 @@ fn main() -> Result<()> { }; match args.role { SupervisorRole::IsolationBackend => { - info!(command = ?command, "Starting sandbox supervision"); + info!(instance_id = %instance_id, command = ?command, "Starting sandbox supervision"); let Some(( backend_setup, backend_descriptor, @@ -675,6 +678,7 @@ fn main() -> Result<()> { .transpose()? .map(openshell_supervisor::app_listener::BoundListener::start); let config = openshell_supervisor::SandboxInstanceConfig { + supervisor_instance_id: instance_id, app_router: app_host .as_ref() .map(openshell_supervisor::app_listener::HostHandle::router), @@ -883,20 +887,24 @@ fn target( Ok(openshell_otel::OtlpTarget::new(config)?.with_transport(&transport)) } -/// Resource attributes identifying this supervisor's sandbox and the gateway -/// that launched it. +/// Resource attributes identifying this supervisor, its sandbox, and gateway. fn supervisor_resource_attributes( + instance_id: &str, sandbox_id: Option<&str>, gateway_name: Option<&str>, ) -> Vec { - sandbox_id - .map(|id| opentelemetry::KeyValue::new("openshell.sandbox.id", id.to_string())) - .into_iter() - .chain(openshell_otel::gateway_resource_attributes( - gateway_name, - None, - )) - .collect() + let mut attributes = vec![opentelemetry::KeyValue::new( + "service.instance.id", + instance_id.to_string(), + )]; + attributes.extend( + sandbox_id.map(|id| opentelemetry::KeyValue::new("openshell.sandbox.id", id.to_string())), + ); + attributes.extend(openshell_otel::gateway_resource_attributes( + gateway_name, + None, + )); + attributes } /// Choose the supervisor's exit status for a sandbox run. @@ -1077,7 +1085,7 @@ mod tests { } #[test] - fn telemetry_names_the_sandbox_and_its_gateway() { + fn telemetry_identifies_the_supervisor_sandbox_and_gateway() { let args = Args::try_parse_from([ "openshell-supervisor", "--sandbox-id", @@ -1087,17 +1095,25 @@ mod tests { ]) .expect("parse telemetry identity"); let attributes = supervisor_resource_attributes( + "registered-supervisor", args.sandbox_id.as_deref(), args.gateway_name.as_deref(), ); assert_eq!( attributes, vec![ + opentelemetry::KeyValue::new("service.instance.id", "registered-supervisor"), opentelemetry::KeyValue::new("openshell.sandbox.id", "sb-1"), opentelemetry::KeyValue::new("openshell.gateway.name", "prod-west"), ] ); - assert!(supervisor_resource_attributes(None, None).is_empty()); + assert_eq!( + supervisor_resource_attributes("registered-supervisor", None, None), + vec![opentelemetry::KeyValue::new( + "service.instance.id", + "registered-supervisor", + )] + ); } #[test] diff --git a/crates/openshell-supervisor/src/metrics.rs b/crates/openshell-supervisor/src/metrics.rs index d52f17ae18..acfd0badc5 100644 --- a/crates/openshell-supervisor/src/metrics.rs +++ b/crates/openshell-supervisor/src/metrics.rs @@ -15,6 +15,7 @@ const SERVICE_NAME: &str = "openshell-supervisor"; /// Create the process's metrics provider inside the runtime driving OTLP. pub fn start( + instance_id: &str, endpoint: &str, protocol: OtlpProtocol, credentials: OtlpExportCredentials<'_>, @@ -24,7 +25,7 @@ pub fn start( let mut resource_attributes = openshell_otel::gateway_resource_attributes(gateway_name, None); resource_attributes.push(KeyValue::new( "service.instance.id", - uuid::Uuid::new_v4().to_string(), + instance_id.to_string(), )); let config = OtlpExportConfig { endpoint, @@ -68,7 +69,7 @@ pub fn shutdown(provider: &SdkMeterProvider) { #[cfg(test)] mod tests { use super::*; - use openshell_otel_test_support::OtlpHttpTestServer; + use openshell_otel_test_support::{OtlpHttpTestServer, relay::string_attribute}; use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest; use opentelemetry_proto::tonic::metrics::v1::metric::Data; use prost::Message as _; @@ -79,7 +80,9 @@ mod tests { let path = format!("{}/receiver", collector.endpoint()); let headers = SecretOtlpHeaders::new("x-collector-test=metrics".to_string()); let count = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(2)); + let instance_id = "registered-supervisor"; let provider = start( + instance_id, &path, OtlpProtocol::HttpProtobuf, OtlpExportCredentials { @@ -106,11 +109,9 @@ mod tests { let response = ExportMetricsServiceRequest::decode(received.body).unwrap(); let resource = &response.resource_metrics[0]; let attributes = &resource.resource.as_ref().unwrap().attributes; - assert!(attributes.iter().any(|kv| kv.key == "service.instance.id")); + assert!(attributes.contains(&string_attribute("service.instance.id", instance_id))); assert!( - attributes - .iter() - .any(|kv| kv.key == "openshell.gateway.name") + attributes.contains(&string_attribute("openshell.gateway.name", "test-gateway")) ); let instruments = resource .scope_metrics diff --git a/crates/openshell-supervisor/src/shared_host.rs b/crates/openshell-supervisor/src/shared_host.rs index c2a2b4e384..95d65491a5 100644 --- a/crates/openshell-supervisor/src/shared_host.rs +++ b/crates/openshell-supervisor/src/shared_host.rs @@ -383,7 +383,7 @@ impl SharedHost { } } - fn start_metrics(self: &Arc, configuration: &[u8]) { + fn start_metrics(self: &Arc, instance_id: &str, configuration: &[u8]) { if configuration.is_empty() || self.metrics_provider.get().is_some() { return; } @@ -395,6 +395,7 @@ impl SharedHost { }; let host = Arc::downgrade(self); let result = crate::metrics::start( + instance_id, &config.collector.endpoint, config.collector.protocol, openshell_core::jwt::OtlpExportCredentials { @@ -837,6 +838,7 @@ impl SharedHost { crate::sandbox_instance_host::prepare_private_dir(&trust_dir).map_err(failure)?; let ssh_socket = dir.join("ssh.sock"); let config = crate::SandboxInstanceConfig { + supervisor_instance_id: uuid::Uuid::new_v4().to_string(), app_router: self .app_listener .as_ref() @@ -1493,6 +1495,7 @@ async fn run_stream( .is_ok_and(|sent| sent.is_ok()) } }; + let instance_id = hello.instance_id.clone(); if !send( HostMessage { payload: Some(host_message::Payload::Hello(hello)), @@ -1546,11 +1549,11 @@ async fn run_stream( last_heard = tokio::time::Instant::now(); match payload { Some(host_gateway_message::Payload::Accepted(accepted_message)) => { - host.start_metrics(&accepted_message.supervisor_metrics); + host.start_metrics(&instance_id, &accepted_message.supervisor_metrics); accepted = true; host.gateway_connected.send_replace(true); host.gateway_home.send_replace(Some(accepted_message.peer_endpoint.clone())); - tracing::info!(session = %accepted_message.session_id, "gateway accepted the supervisor host"); + tracing::info!(instance_id = %instance_id, session = %accepted_message.session_id, "gateway accepted the supervisor host"); // A pool gateway detects failed members by silence, // so it asks for more frequent heartbeats. if let Some(interval) = accepted_message diff --git a/docs/observability/gateway-metrics.mdx b/docs/observability/gateway-metrics.mdx index d33a6c5ab0..d6a5f235de 100644 --- a/docs/observability/gateway-metrics.mdx +++ b/docs/observability/gateway-metrics.mdx @@ -21,6 +21,12 @@ and configure your collector to forward the metrics to your backend. `openshell.gateway.name` and `service.instance.id` are OTLP resource attributes for grouping by gateway and supervisor process. +A dedicated supervisor uses its sandbox control-stream registration ID as +`service.instance.id` across metrics, traces, and OTLP OCSF records. A shared +supervisor uses its host registration ID. Search gateway logs for the instance +ID in `supervisor session: accepted` to find the dedicated supervisor's sandbox, +or in `supervisor host attached` to find the shared supervisor's pool member. + | Metric | Type | Labels | Measures | | --- | --- | --- | --- | | `openshell_supervisor_egress_decisions_total` | Counter | `scope`, `outcome`, `inspection_type`, `policy` | Final egress admission decisions. | diff --git a/docs/observability/traces.mdx b/docs/observability/traces.mdx index abe075e27b..d8b610da8e 100644 --- a/docs/observability/traces.mdx +++ b/docs/observability/traces.mdx @@ -55,6 +55,7 @@ Resource attributes identify which process produced a span: |---|---|---| | `service.name` | `openshell-gateway`, `openshell-driver-`, such as `openshell-driver-docker`, or `openshell-supervisor` | Every span | | `service.version` | The OpenShell version | Every span | +| `service.instance.id` | The supervisor's sandbox control-stream registration ID | Dedicated supervisor spans | | `openshell.gateway.name` | The gateway name | Every span | | `openshell.gateway.compute_driver` | The configured compute driver, such as `kubernetes` | Gateway and compute-driver spans | | `openshell.sandbox.id` | The sandbox ID | Supervisor spans | From 234c4fb0f74c375a80959597e34a78944fc48043 Mon Sep 17 00:00:00 2001 From: Eitan Geiger Date: Sun, 22 Nov 2026 22:25:57 +0200 Subject: [PATCH 6/6] fix(observability): align supervisor metrics with gateway OTLP Use one OTLP metrics configuration for the gateway and supervisors and derive supervisor instance IDs from stable sandbox or pool identities. Mark assignment-stream collector settings secret. Remove the policy label, duplicate telemetry fields, and unused exemplar context capture. Signed-off-by: Eitan Geiger --- .../src/proto_json.rs | 4 + crates/openshell-gateway/src/vm.rs | 5 - crates/openshell-server/src/compute/mod.rs | 22 +++- crates/openshell-server/src/config_file.rs | 64 ++------- crates/openshell-server/src/lib.rs | 30 ++--- crates/openshell-server/src/otel_tracing.rs | 46 +++++-- .../src/l7/correlation.rs | 22 +--- .../src/l7/relay.rs | 17 +-- .../src/l7/request_trace.rs | 47 ++----- .../src/l7/websocket.rs | 31 +---- .../src/metrics.rs | 121 ++++-------------- .../openshell-supervisor-network/src/opa.rs | 7 - .../openshell-supervisor-network/src/proxy.rs | 44 +++---- .../src/proxy/egress.rs | 29 +---- .../src/proxy/relay.rs | 9 +- .../src/proxy/tests/request_trace.rs | 3 +- .../openshell-supervisor-process/Cargo.toml | 2 +- .../src/delegated.rs | 5 +- .../src/backend_setup/tests.rs | 2 - .../src/legacy_startup_regression_tests.rs | 1 - crates/openshell-supervisor/src/lib.rs | 5 - crates/openshell-supervisor/src/main.rs | 45 +++---- crates/openshell-supervisor/src/metrics.rs | 68 ++++++++-- .../openshell-supervisor/src/shared_host.rs | 12 +- docs/how-it-works/gateways/configuration.mdx | 53 +++----- docs/observability/gateway-metrics.mdx | 44 +++---- docs/observability/overview.mdx | 12 +- docs/observability/traces.mdx | 1 - proto/supervisor_host.proto | 2 +- skills/debug-openshell-cluster/SKILL.md | 2 +- 30 files changed, 284 insertions(+), 471 deletions(-) diff --git a/crates/openshell-gateway-interceptors/src/proto_json.rs b/crates/openshell-gateway-interceptors/src/proto_json.rs index f34c791adc..aa6d286c6d 100644 --- a/crates/openshell-gateway-interceptors/src/proto_json.rs +++ b/crates/openshell-gateway-interceptors/src/proto_json.rs @@ -399,6 +399,10 @@ mod tests { for (message_name, field_name) in [ ("openshell.datamodel.v1.Provider", "credentials"), ("openshell.compute.v1.DriverSandboxSpec", "sandbox_token"), + ( + "openshell.supervisor.host.v1.HostAccepted", + "supervisor_metrics", + ), ("openshell.v1.IssueSandboxTokenResponse", "token"), ("openshell.v1.RefreshSandboxTokenResponse", "token"), ("openshell.v1.ExtensionServiceCredential", "token"), diff --git a/crates/openshell-gateway/src/vm.rs b/crates/openshell-gateway/src/vm.rs index 0960857f42..ce88f23d7d 100644 --- a/crates/openshell-gateway/src/vm.rs +++ b/crates/openshell-gateway/src/vm.rs @@ -953,7 +953,6 @@ mod tests { traces: Some(OtlpTracesConfig { collector }), ocsf: None, agent: None, - supervisor_metrics: None, }; let mut command = tokio::process::Command::new("openshell-driver-vm"); append_otlp_args(&mut command, Some(&otlp), "production-us-west"); @@ -992,7 +991,6 @@ mod tests { }), ocsf: None, agent: None, - supervisor_metrics: None, }), "production-us-west", ); @@ -1026,7 +1024,6 @@ mod tests { }), ocsf: None, agent: None, - supervisor_metrics: None, }), "production-us-west", ); @@ -1063,7 +1060,6 @@ mod tests { schema_version: Some("2.0".into()), }), agent: None, - supervisor_metrics: None, }), "production-us-west", ); @@ -1102,7 +1098,6 @@ mod tests { OtlpProtocol::HttpProtobuf, ), }), - supervisor_metrics: None, }), "production-us-west", ); diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index 505d493975..26acf32566 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -13972,14 +13972,17 @@ mod tests { traces: secret("authorization=traces"), ocsf: secret("authorization=Bearer%20secret"), agent: secret("x-mlflow-experiment-id=0"), - metrics: None, + metrics: secret("authorization=metrics"), }); runtime.configure_supervisor_otlp_tls(crate::otel_tracing::SupervisorOtlpTls { - materials: vec![openshell_core::jwt::OtlpTlsMaterial { - ca_pem: Some("agent-ca".to_string()), - ..Default::default() - }], + materials: ["agent-ca", "metrics-ca"] + .map(|ca| openshell_core::jwt::OtlpTlsMaterial { + ca_pem: Some(ca.to_string()), + ..Default::default() + }) + .into(), agent: Some(0), + metrics: Some(1), ..Default::default() }); let sandbox = sandbox_record( @@ -14013,11 +14016,13 @@ mod tests { exposed(&bundle.traces_otlp_headers), exposed(&bundle.ocsf_otlp_headers), exposed(&bundle.agent_otlp_headers), + exposed(&bundle.metrics_otlp_headers), ], [ Some("authorization=traces".to_string()), Some("authorization=Bearer%20secret".to_string()), Some("x-mlflow-experiment-id=0".to_string()), + Some("authorization=metrics".to_string()), ] ); assert!(bundle.traces_otlp_tls.is_none() && bundle.ocsf_otlp_tls.is_none()); @@ -14028,6 +14033,13 @@ mod tests { .and_then(|tls| tls.ca_pem.as_deref()), Some("agent-ca") ); + assert_eq!( + bundle + .metrics_otlp() + .tls + .and_then(|tls| tls.ca_pem.as_deref()), + Some("metrics-ca") + ); } #[tokio::test] diff --git a/crates/openshell-server/src/config_file.rs b/crates/openshell-server/src/config_file.rs index 94072a3426..d5fd849e94 100644 --- a/crates/openshell-server/src/config_file.rs +++ b/crates/openshell-server/src/config_file.rs @@ -363,8 +363,7 @@ pub struct MetricsTlsFileConfig { /// /// `endpoint` is the collector for every enabled signal, and on its own /// enables trace export. `[otlp.traces]` overrides the trace endpoint; -/// `[otlp.metrics]` with `enabled = true` exports gateway metrics; -/// `[otlp.supervisor_metrics]` with `enabled = true` exports supervisor metrics; +/// `[otlp.metrics]` with `enabled = true` exports gateway and supervisor metrics; /// `[otlp.ocsf]` with `enabled = true` exports OCSF events as log records; and /// `[otlp.agent]` with `enabled = true` relays workload traces. Each signal /// can use a different endpoint. SDK tuning knobs are deliberately absent — @@ -383,7 +382,7 @@ pub struct OtlpConfig { #[serde(default, skip_serializing_if = "Option::is_none")] pub traces: Option, - /// Gateway metric export, when enabled. + /// Gateway and supervisor metric export, when enabled. #[serde( default, skip_serializing_if = "Option::is_none", @@ -406,14 +405,6 @@ pub struct OtlpConfig { serialize_with = "serialize_enabled" )] pub agent: Option, - - /// Export of supervisor egress metrics, when enabled. - #[serde( - default, - skip_serializing_if = "Option::is_none", - serialize_with = "serialize_enabled" - )] - pub supervisor_metrics: Option, } /// Writes `enabled = true` so that a serialized config parses back to the @@ -474,10 +465,7 @@ impl OtlpConfig { traces: self.traces.as_ref().map(|traces| traces.collector.export()), ocsf: self.ocsf.as_ref().map(|ocsf| ocsf.collector.export()), agent: self.agent.as_ref().map(|agent| agent.collector.export()), - metrics: self - .supervisor_metrics - .as_ref() - .map(OtlpCollectorConfig::export), + metrics: self.metrics.as_ref().map(OtlpCollectorConfig::export), } } } @@ -911,8 +899,6 @@ struct RawOtlpConfig { ocsf: Option, #[serde(default)] agent: Option, - #[serde(default)] - supervisor_metrics: Option, } #[derive(Deserialize)] @@ -1100,19 +1086,7 @@ impl TryFrom for OtlpConfig { }) }) .transpose()?; - let supervisor_metrics = raw - .supervisor_metrics - .filter(|metrics| metrics.enabled) - .map(|metrics| { - raw_collector!(metrics).resolve("otlp.supervisor_metrics", shared.as_ref()) - }) - .transpose()?; - if traces.is_none() - && metrics.is_none() - && ocsf.is_none() - && agent.is_none() - && supervisor_metrics.is_none() - { + if traces.is_none() && metrics.is_none() && ocsf.is_none() && agent.is_none() { return Err("otlp needs an endpoint, or an enabled signal table".to_string()); } let config = Self { @@ -1121,7 +1095,6 @@ impl TryFrom for OtlpConfig { traces, ocsf, agent, - supervisor_metrics, }; let supervisor_tls = config.supervisor_tls_bytes(); if supervisor_tls > MAX_SUPERVISOR_TLS_BYTES { @@ -2219,30 +2192,7 @@ service_name = "openshell-gateway-dev" assert!(otlp.service_name.is_none()); assert_eq!(otlp.ocsf, None); assert!(otlp.metrics.is_none()); - assert_eq!(otlp.supervisor_metrics, None); - } - - #[test] - fn supervisor_metrics_accepts_an_inherited_or_independent_collector() { - let inherited = otlp( - "[openshell.gateway.otlp]\nendpoint = 'https://collector:4318'\n\ - protocol = 'http/protobuf'\n\ - [openshell.gateway.otlp.supervisor_metrics]\nenabled = true\n", - ); - let metrics = inherited.supervisor_otlp().metrics.unwrap(); - assert_eq!(metrics.endpoint, "https://collector:4318"); - assert_eq!(metrics.protocol, OtlpProtocol::HttpProtobuf); - - let independent = otlp( - "[openshell.gateway.otlp.supervisor_metrics]\nenabled = true\n\ - endpoint = 'http://metrics:4317'\n", - ); - assert!(independent.traces.is_none()); - assert!(independent.metrics.is_none()); - assert_eq!( - independent.supervisor_otlp().metrics.unwrap().endpoint, - "http://metrics:4317" - ); + assert!(otlp.supervisor_otlp().metrics.is_none()); } #[test] @@ -2257,6 +2207,7 @@ service_name = "openshell-gateway-dev" let metrics = config.metrics.as_ref().unwrap(); assert_eq!(metrics.endpoint, "http://shared:4318"); assert_eq!(metrics.protocol, OtlpProtocol::HttpProtobuf); + assert_eq!(config.supervisor_otlp().metrics, Some(metrics.export())); assert_eq!( metrics.headers.header_map()["authorization"], "Bearer shared" @@ -2278,6 +2229,7 @@ service_name = "openshell-gateway-dev" [openshell.gateway.otlp.metrics]\n", ); assert!(disabled.metrics.is_none()); + assert!(disabled.supervisor_otlp().metrics.is_none()); let own = otlp( "[openshell.gateway.otlp.metrics]\nenabled = true\n\ @@ -2287,7 +2239,7 @@ service_name = "openshell-gateway-dev" assert_eq!(metrics.endpoint, "http://metrics:4318"); assert_eq!(metrics.protocol, OtlpProtocol::HttpProtobuf); assert!(own.traces.is_none()); - assert!(own.supervisor_metrics.is_none()); + assert_eq!(own.supervisor_otlp().metrics, Some(metrics.export())); let error = toml::from_str::( "[metrics]\nenabled = true\n[traces]\nendpoint = 'http://traces:4317'\n", diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index da1466f974..6dd73e5d27 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -924,37 +924,29 @@ pub(crate) async fn run_server( shutdown_rx.clone(), ) .await?; - compute.configure_supervisor_otlp_headers(supervisor_otlp_headers( - config_file - .as_ref() - .and_then(|file| file.openshell.gateway.otlp.as_ref()), - )); - compute.configure_supervisor_otlp_tls(otel_tracing::supervisor_otlp_tls( - config_file - .as_ref() - .and_then(|file| file.openshell.gateway.otlp.as_ref()), - )); + let otlp = config_file + .as_ref() + .and_then(|file| file.openshell.gateway.otlp.as_ref()); + let supervisor_headers = supervisor_otlp_headers(otlp); + let supervisor_tls = otel_tracing::supervisor_otlp_tls(otlp); if let Some(host) = compute.supervisor_host() - && let Some(otlp) = config_file - .as_ref() - .and_then(|file| file.openshell.gateway.otlp.as_ref()) - && let Some(collector) = otlp.supervisor_metrics.as_ref() + && let Some(collector) = otlp.and_then(|otlp| otlp.metrics.as_ref()) { - let headers = supervisor_otlp_headers(Some(otlp)); - let tls = otel_tracing::supervisor_otlp_tls(Some(otlp)); let metrics = openshell_core::sandbox_env::SharedSupervisorMetrics { collector: collector.export(), gateway_name: config.name.clone(), - headers: headers.metrics, - tls: tls + headers: supervisor_headers.metrics.clone(), + tls: supervisor_tls .metrics - .and_then(|index| tls.materials.get(index).cloned()), + .and_then(|index| supervisor_tls.materials.get(index).cloned()), }; let encoded = serde_json::to_vec(&metrics).map_err(|error| Error::Config { message: format!("could not encode supervisor metrics settings: {error}"), })?; host.set_supervisor_metrics(encoded); } + compute.configure_supervisor_otlp_headers(supervisor_headers); + compute.configure_supervisor_otlp_tls(supervisor_tls); let gateway_interceptors = if let Some(issuer) = extension_jwt_issuer.as_ref() { let mut slots = BTreeMap::new(); for interceptor in &config.gateway_interceptors { diff --git a/crates/openshell-server/src/otel_tracing.rs b/crates/openshell-server/src/otel_tracing.rs index 4b7a5d8eca..6e30d6e84d 100644 --- a/crates/openshell-server/src/otel_tracing.rs +++ b/crates/openshell-server/src/otel_tracing.rs @@ -329,7 +329,8 @@ impl OtlpExport { } /// Collector headers for each supervisor export, delivered in the launch -/// bundle because supervisors do not inherit the gateway's environment. +/// bundle or assignment stream because supervisors do not inherit the +/// gateway's environment. #[derive(Clone, Debug, Default)] pub struct SupervisorOtlpHeaders { pub traces: Option, @@ -350,8 +351,8 @@ impl SupervisorOtlpHeaders { /// The headers each enabled supervisor export sends. /// /// Traces and the agent relay send their collector's configured headers. OCSF -/// export also sends the headers the gateway's own OCSF exporter reads from -/// its environment, which override configured ones. +/// and metrics also use the gateway's environment headers, which override +/// configured ones. pub fn supervisor_otlp_headers(otlp: Option<&OtlpConfig>) -> SupervisorOtlpHeaders { supervisor_otlp_headers_from(otlp, |name| std::env::var(name).ok()) } @@ -409,7 +410,13 @@ fn supervisor_otlp_headers_from( .agent .as_ref() .and_then(|agent| configured(&agent.collector)), - metrics: otlp.supervisor_metrics.as_ref().and_then(configured), + metrics: otlp.metrics.as_ref().and_then(|metrics| { + secret_headers(with_env_headers( + metrics, + "OTEL_EXPORTER_OTLP_METRICS_HEADERS", + &var, + )) + }), } } @@ -458,7 +465,7 @@ pub fn supervisor_otlp_tls(otlp: Option<&OtlpConfig>) -> SupervisorOtlpTls { otlp.traces.as_ref().map(|traces| &traces.collector), otlp.ocsf.as_ref().map(|ocsf| &ocsf.collector), otlp.agent.as_ref().map(|agent| &agent.collector), - otlp.supervisor_metrics.as_ref(), + otlp.metrics.as_ref(), ]; let mut materials = Vec::new(); let mut seen = Vec::new(); @@ -826,7 +833,6 @@ mod tests { }), ocsf: None, agent: None, - supervisor_metrics: None, } } @@ -842,7 +848,7 @@ mod tests { } #[test] - fn supervisors_receive_configured_trace_headers_and_merged_ocsf_headers() { + fn supervisors_receive_configured_and_environment_headers_by_signal() { let env = |vars: &'static [(&'static str, &'static str)]| { move |name: &str| { vars.iter() @@ -863,6 +869,10 @@ mod tests { collector: OtlpCollectorConfig::new("http://mlflow:5000", OtlpProtocol::HttpProtobuf) .with_headers([("x-mlflow-experiment-id", "0")].into()), }); + otlp.metrics = Some( + OtlpCollectorConfig::new("https://metrics:4317", OtlpProtocol::Grpc) + .with_headers([("authorization", "toml"), ("x-tenant", "blue")].into()), + ); let headers = supervisor_otlp_headers_from( Some(&otlp), @@ -872,6 +882,10 @@ mod tests { "authorization=traces%20env", ), ("OTEL_EXPORTER_OTLP_LOGS_HEADERS", "x-extra=logs"), + ( + "OTEL_EXPORTER_OTLP_METRICS_HEADERS", + "authorization=metrics", + ), ("OTEL_EXPORTER_OTLP_HEADERS", "authorization=all"), ]), ); @@ -890,12 +904,20 @@ mod tests { Some("x-mlflow-experiment-id=0"), "the agent lane never reads the environment" ); + assert_eq!( + exposed(headers.metrics).as_deref(), + Some("authorization=metrics,x-tenant=blue"), + ); let generic = supervisor_otlp_headers_from( Some(&otlp), env(&[("OTEL_EXPORTER_OTLP_HEADERS", "authorization=all")]), ); assert_eq!(exposed(generic.ocsf).as_deref(), Some("authorization=all")); + assert_eq!( + exposed(generic.metrics).as_deref(), + Some("authorization=all,x-tenant=blue"), + ); let unconfigured = supervisor_otlp_headers_from( Some(&config()), @@ -903,6 +925,10 @@ mod tests { ("OTEL_EXPORTER_OTLP_TRACES_HEADERS", "authorization=traces"), ("OTEL_EXPORTER_OTLP_HEADERS", "authorization=all"), ("OTEL_EXPORTER_OTLP_LOGS_HEADERS", "authorization=logs"), + ( + "OTEL_EXPORTER_OTLP_METRICS_HEADERS", + "authorization=metrics", + ), ]), ); assert!( @@ -911,6 +937,7 @@ mod tests { ); assert!(unconfigured.ocsf.is_none(), "OCSF export is not enabled"); assert!(unconfigured.agent.is_none()); + assert!(unconfigured.metrics.is_none()); assert!( supervisor_otlp_headers_from(None, env(&[("OTEL_EXPORTER_OTLP_HEADERS", "a=b")])) .traces @@ -990,7 +1017,7 @@ mod tests { OtlpCollectorConfig::new(endpoint, OtlpProtocol::Grpc).with_tls(mutual()) }; let otlp = OtlpConfig { - metrics: None, + metrics: Some(collector("https://metrics:4318")), service_name: None, traces: Some(OtlpTracesConfig { collector: collector("https://shared:4317"), @@ -1002,12 +1029,11 @@ mod tests { agent: Some(AgentOtlpConfig { collector: collector("https://agents:4318"), }), - supervisor_metrics: None, }; let tls = supervisor_otlp_tls(Some(&otlp)); assert_eq!(tls.materials.len(), 1); - assert_eq!([tls.traces, tls.ocsf, tls.agent], [Some(0); 3]); + assert_eq!([tls.traces, tls.ocsf, tls.agent, tls.metrics], [Some(0); 4]); } #[tokio::test] diff --git a/crates/openshell-supervisor-network/src/l7/correlation.rs b/crates/openshell-supervisor-network/src/l7/correlation.rs index 23318faa95..b2a0ff9990 100644 --- a/crates/openshell-supervisor-network/src/l7/correlation.rs +++ b/crates/openshell-supervisor-network/src/l7/correlation.rs @@ -102,19 +102,6 @@ fn enrich_request(event: &mut openshell_ocsf::BaseEventData) { .entry("http_event_kind") .or_insert_with(|| event_kind.into()); fields.insert("request_sequence".into(), sequence.into()); - let finished_inspection = scope - .trace - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .as_ref() - .and_then(RequestTrace::finished_inspection); - if let Some((inspection, result, outcome)) = finished_inspection { - fields.insert("egress_inspection_type".into(), inspection.label().into()); - fields.insert("egress_result".into(), result.label().into()); - if let Some(outcome) = outcome { - fields.insert("egress_outcome".into(), outcome.label().into()); - } - } } } @@ -291,7 +278,7 @@ impl RequestCorrelation { fn build(method: &str, raw_header: &[u8], ctx: &L7EvalContext, request_id: String) -> Self { let mut trace = RequestTrace::new(&request_id, method, &ctx.host, ctx.port, raw_header); - trace.start_inspection(&ctx.policy_name); + trace.start_inspection(); Self::install(RequestScope { request_id, inspected: true, @@ -349,7 +336,7 @@ impl RequestCorrelation { .map_or_else(tracing::Span::none, |trace| trace.stage(stage)) } - pub(crate) fn select_inspector(&self, protocol: crate::l7::L7Protocol, policy: &str) { + pub(crate) fn select_inspector(&self, protocol: crate::l7::L7Protocol) { if let Some(trace) = self .scope .trace @@ -357,10 +344,7 @@ impl RequestCorrelation { .unwrap_or_else(std::sync::PoisonError::into_inner) .as_mut() { - trace.select_inspector( - crate::metrics::InspectionType::from_protocol(protocol), - policy, - ); + trace.select_inspector(crate::metrics::InspectionType::from_protocol(protocol)); } } diff --git a/crates/openshell-supervisor-network/src/l7/relay.rs b/crates/openshell-supervisor-network/src/l7/relay.rs index 7db7b6c7a4..df0f186e6b 100644 --- a/crates/openshell-supervisor-network/src/l7/relay.rs +++ b/crates/openshell-supervisor-network/src/l7/relay.rs @@ -1444,7 +1444,7 @@ where } L7Protocol::Graphql => relay_graphql(config, &engine, client, upstream, ctx).await, L7Protocol::Sql => { - use crate::metrics::{self, InspectionType, Outcome, Policy, Scope}; + use crate::metrics::{self, InspectionType, Outcome, Scope}; if close_if_stale(engine.generation_guard(), ctx) { return Ok(()); @@ -1464,12 +1464,7 @@ where } UninspectableTrafficGate::Unrestricted => Outcome::Allow, }; - metrics::decision( - Scope::Connection, - outcome, - InspectionType::Tcp, - Policy::from(Some(ctx.policy_name.as_str())), - ); + metrics::decision(Scope::Connection, outcome, InspectionType::Tcp); if matches!(outcome, Outcome::Deny) { return Ok(()); } @@ -1609,7 +1604,7 @@ where .map_err(&capture_error)?; return Ok(()); }; - correlation.select_inspector(config.protocol, &ctx.policy_name); + correlation.select_inspector(config.protocol); let observer = EndpointObserver::begin_captured( ctx.endpoint_observation_tx.as_ref(), config, @@ -2596,7 +2591,7 @@ where } }; let correlation = RequestCorrelation::new(&req, ctx); - correlation.select_inspector(config.protocol, &ctx.policy_name); + correlation.select_inspector(config.protocol); let capture_error = |error| correlation.capture_error(error); if !request_authority_matches_endpoint(&req, ctx) { reject_request_authority_mismatch(client, ctx, &req.action, Some(&correlation)) @@ -3157,7 +3152,7 @@ where let req = parsed.request; let jsonrpc_info = parsed.info; let correlation = RequestCorrelation::new(&req, ctx); - correlation.select_inspector(config.protocol, &ctx.policy_name); + correlation.select_inspector(config.protocol); let capture_error = |error| correlation.capture_error(error); let observer = EndpointObserver::begin_captured( ctx.endpoint_observation_tx.as_ref(), @@ -3530,7 +3525,7 @@ where } }; let correlation = RequestCorrelation::new(&req, ctx); - correlation.select_inspector(config.protocol, &ctx.policy_name); + correlation.select_inspector(config.protocol); let capture_error = |error| correlation.capture_error(error); if !request_authority_matches_endpoint(&req, ctx) { diff --git a/crates/openshell-supervisor-network/src/l7/request_trace.rs b/crates/openshell-supervisor-network/src/l7/request_trace.rs index 8d871976ec..8f98e3473e 100644 --- a/crates/openshell-supervisor-network/src/l7/request_trace.rs +++ b/crates/openshell-supervisor-network/src/l7/request_trace.rs @@ -11,7 +11,7 @@ use tracing::Span; use tracing_opentelemetry::OpenTelemetrySpanExt as _; use super::correlation::HttpOutcome; -use crate::metrics::{self, InspectionType, Outcome, Policy, ResultLabel, Scope, Stage, Timer}; +use crate::metrics::{self, InspectionType, Outcome, ResultLabel, Scope, Stage, Timer}; const MAX_TRACEPARENT_BYTES: usize = 256; @@ -21,9 +21,7 @@ pub(super) struct RequestTrace { outcome: &'static str, failure_reason: Option<&'static str>, inspection: Option, - inspection_result: Option<(ResultLabel, Option)>, inspection_type: InspectionType, - policy: String, admission: Outcome, } @@ -73,9 +71,6 @@ impl RequestTrace { server.port = i64::from(port), openshell.request.outcome = tracing::field::Empty, openshell.request.failure_reason = tracing::field::Empty, - openshell.egress.outcome = tracing::field::Empty, - openshell.egress.inspection_type = tracing::field::Empty, - openshell.egress.result = tracing::field::Empty, http.response.status_code = tracing::field::Empty, otel.kind = "server", otel.status_code = tracing::field::Empty, @@ -94,25 +89,20 @@ impl RequestTrace { outcome: "incomplete", failure_reason: None, inspection: None, - inspection_result: None, inspection_type: InspectionType::Http, - policy: String::new(), admission: Outcome::Allow, } } - pub(super) fn start_inspection(&mut self, policy: &str) { - self.policy.push_str(policy); - self.inspection = Some( - self.span - .in_scope(|| Timer::new(Stage::Inspection(Scope::Request, self.inspection_type))), - ); + pub(super) fn start_inspection(&mut self) { + self.inspection = Some(Timer::new(Stage::Inspection( + Scope::Request, + self.inspection_type, + ))); } - pub(super) fn select_inspector(&mut self, inspection_type: InspectionType, policy: &str) { + pub(super) fn select_inspector(&mut self, inspection_type: InspectionType) { self.inspection_type = inspection_type; - self.policy.clear(); - self.policy.push_str(policy); if let Some(timer) = self.inspection.as_mut() { timer.set_stage(Stage::Inspection(Scope::Request, inspection_type)); } @@ -132,13 +122,6 @@ impl RequestTrace { self.inspection.as_mut() } - pub(super) fn finished_inspection( - &self, - ) -> Option<(InspectionType, ResultLabel, Option)> { - let (result, outcome) = self.inspection_result?; - Some((self.inspection_type, result, outcome)) - } - pub(super) fn finish_inspection(&mut self, result: ResultLabel) { let Some(timer) = self.inspection.take() else { return; @@ -148,21 +131,8 @@ impl RequestTrace { ResultLabel::Deny => Some(Outcome::Deny), _ => None, }; - self.inspection_result = Some((result, outcome)); - self.span.record("openshell.egress.result", result.label()); - self.span.record( - "openshell.egress.inspection_type", - self.inspection_type.label(), - ); if let Some(outcome) = outcome { - self.span - .record("openshell.egress.outcome", outcome.label()); - metrics::decision( - Scope::Request, - outcome, - self.inspection_type, - Policy::from(Some(self.policy.as_str())), - ); + metrics::decision(Scope::Request, outcome, self.inspection_type); } timer.finish(result); } @@ -181,7 +151,6 @@ impl RequestTrace { otel.name = stage.name(), otel.status_code = tracing::field::Empty, openshell.request.failure_reason = tracing::field::Empty, - openshell.egress.result = tracing::field::Empty, ) } diff --git a/crates/openshell-supervisor-network/src/l7/websocket.rs b/crates/openshell-supervisor-network/src/l7/websocket.rs index 0c5792bcc9..2c60c249b9 100644 --- a/crates/openshell-supervisor-network/src/l7/websocket.rs +++ b/crates/openshell-supervisor-network/src/l7/websocket.rs @@ -8,7 +8,7 @@ use crate::l7::relay::{L7EvalContext, evaluate_l7_in_scope}; use crate::l7::{EnforcementMode, L7RequestInfo}; -use crate::metrics::{self, InspectionType, Outcome, Policy, ResultLabel, Scope, Stage, Timer}; +use crate::metrics::{self, InspectionType, Outcome, ResultLabel, Scope, Stage, Timer}; use crate::opa::{PolicyGenerationGuard, TunnelPolicyEngine}; use crate::telemetry::egress_emit; use flate2::{Compress, Compression, Decompress, FlushCompress, FlushDecompress, Status}; @@ -1254,7 +1254,7 @@ where | WebSocketTerminationCause::DownstreamDisconnect => (None, ResultLabel::Cancelled), _ => (None, ResultLabel::Error), }; - metrics.finish(options.policy_name, outcome, label); + metrics.finish(outcome, label); } result } @@ -1266,15 +1266,10 @@ struct MessageInspection { } impl MessageInspection { - fn finish(&mut self, policy: &str, outcome: Option, result: ResultLabel) { + fn finish(&mut self, outcome: Option, result: ResultLabel) { if let Some(timer) = self.timer.take() { if let Some(outcome) = outcome { - metrics::decision( - Scope::Message, - outcome, - self.inspection, - Policy::from(Some(policy)), - ); + metrics::decision(Scope::Message, outcome, self.inspection); } timer.finish(result); } @@ -1449,11 +1444,7 @@ where )) })?; apply_mask(&mut payload, mask_key); - metrics.finish( - options.policy_name, - Some(metrics.outcome), - ResultLabel::Success, - ); + metrics.finish(Some(metrics.outcome), ResultLabel::Success); return write_text_frame_guarded( writer, &frame.raw_header, @@ -1485,11 +1476,7 @@ where error, )) })?; - metrics.finish( - options.policy_name, - Some(metrics.outcome), - ResultLabel::Success, - ); + metrics.finish(Some(metrics.outcome), ResultLabel::Success); return write_masked_text_frame_guarded( writer, 0x40, @@ -1501,11 +1488,7 @@ where ) .await; } - metrics.finish( - options.policy_name, - Some(metrics.outcome), - ResultLabel::Success, - ); + metrics.finish(Some(metrics.outcome), ResultLabel::Success); write_masked_text_frame_guarded( writer, 0, diff --git a/crates/openshell-supervisor-network/src/metrics.rs b/crates/openshell-supervisor-network/src/metrics.rs index 4e0f3e20e8..476ea5e611 100644 --- a/crates/openshell-supervisor-network/src/metrics.rs +++ b/crates/openshell-supervisor-network/src/metrics.rs @@ -3,14 +3,13 @@ //! Bounded, process-wide supervisor egress metrics. -use std::collections::HashSet; use std::future::Future; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex, OnceLock}; +use std::sync::{Arc, OnceLock}; use std::time::{Duration, Instant}; +use opentelemetry::KeyValue; use opentelemetry::metrics::{Counter, Histogram, Meter, ObservableGauge}; -use opentelemetry::{Context, KeyValue}; use crate::l7::L7Protocol; @@ -18,9 +17,6 @@ const LATENCY_BUCKETS_SECONDS: [f64; 17] = [ 0.0001, 0.00025, 0.0005, 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 15.0, ]; -const MAX_POLICY_NAMES: usize = 16; -const MAX_POLICY_NAME_BYTES: usize = 128; - static METRICS: OnceLock = OnceLock::new(); /// Installs the process's egress instruments before starting any proxies. @@ -80,7 +76,7 @@ impl InspectionType { } } - pub(crate) fn label(self) -> &'static str { + fn label(self) -> &'static str { match self { Self::Tcp => "tcp", Self::Http => "http", @@ -131,7 +127,7 @@ pub(crate) enum ResultLabel { } impl ResultLabel { - pub(crate) fn label(self) -> &'static str { + fn label(self) -> &'static str { match self { Self::Success => "success", Self::Deny => "deny", @@ -164,25 +160,11 @@ impl Route { } } -pub(crate) enum Policy<'a> { - Named(&'a str), - NoMatch, - Unattributed, -} - -impl<'a> From> for Policy<'a> { - fn from(name: Option<&'a str>) -> Self { - name.filter(|name| !name.is_empty() && *name != "-") - .map_or(Self::Unattributed, Self::Named) - } -} - struct Metrics { decisions: Counter, policy_evaluation: Histogram, request_inspection: Histogram, upstream_connect: Histogram, - policy_names: Mutex>>, connections: Arc<[AtomicU64; InspectionType::ALL.len()]>, _active_connections: ObservableGauge, } @@ -229,50 +211,13 @@ impl Metrics { "openshell_supervisor_upstream_connect_duration_seconds", "Time spent establishing an upstream connection.", ), - policy_names: Mutex::new(HashSet::new()), connections, _active_connections: active_connections, } } - - fn policy_label(&self, policy: Policy<'_>) -> Arc { - let name = match policy { - Policy::NoMatch => return Arc::from("no_match"), - Policy::Unattributed => return Arc::from("unattributed"), - Policy::Named(name) if name.len() > MAX_POLICY_NAME_BYTES => { - return Arc::from("overflow"); - } - Policy::Named(name) => name, - }; - let mut names = self - .policy_names - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let name = if matches!(name, "no_match" | "unattributed" | "overflow") - || name.starts_with("name:") - { - std::borrow::Cow::Owned(format!("name:{name}")) - } else { - std::borrow::Cow::Borrowed(name) - }; - if let Some(existing) = names.get(name.as_ref()) { - return Arc::clone(existing); - } - if names.len() >= MAX_POLICY_NAMES { - return Arc::from("overflow"); - } - let name = Arc::::from(name.as_ref()); - names.insert(Arc::clone(&name)); - name - } } -pub(crate) fn decision( - scope: Scope, - outcome: Outcome, - inspection: InspectionType, - policy: Policy<'_>, -) { +pub(crate) fn decision(scope: Scope, outcome: Outcome, inspection: InspectionType) { if let Some(metrics) = METRICS.get() { metrics.decisions.add( 1, @@ -280,7 +225,6 @@ pub(crate) fn decision( KeyValue::new("scope", scope.label()), KeyValue::new("outcome", outcome.label()), KeyValue::new("inspection_type", inspection.label()), - KeyValue::new("policy", metrics.policy_label(policy)), ], ); } @@ -324,7 +268,6 @@ pub(crate) async fn connect( let label = result .as_ref() .map_or_else(ResultLabel::from_io_error, |_| ResultLabel::Success); - tracing::Span::current().record("openshell.egress.result", label.label()); timer.finish(label); result } @@ -341,7 +284,6 @@ pub(crate) fn evaluate( Ok(false) => ResultLabel::Deny, Err(_) => ResultLabel::Error, }; - tracing::Span::current().record("openshell.egress.result", result.label()); timer.finish(result); decision } @@ -349,7 +291,7 @@ pub(crate) fn evaluate( #[derive(Debug)] pub(crate) struct Timer { stage: Stage, - start: Option<(Instant, Context)>, + start: Option, pause: Option, excluded: Duration, } @@ -358,7 +300,7 @@ impl Timer { pub(crate) fn new(stage: Stage) -> Self { Self { stage, - start: METRICS.get().map(|_| (Instant::now(), Context::current())), + start: METRICS.get().map(|_| Instant::now()), pause: None, excluded: Duration::ZERO, } @@ -385,14 +327,13 @@ impl Timer { } fn record(&mut self, result: ResultLabel) { - let (Some(metrics), Some((started, context))) = (METRICS.get(), self.start.take()) else { + let (Some(metrics), Some(started)) = (METRICS.get(), self.start.take()) else { return; }; let ended = self.pause.unwrap_or_else(Instant::now); let seconds = (ended - started) .saturating_sub(self.excluded) .as_secs_f64(); - let _active_context = context.attach(); let result = KeyValue::new("result", result.label()); match self.stage { Stage::PolicyEvaluation(scope) => { @@ -430,27 +371,6 @@ mod tests { use opentelemetry_sdk::metrics::data::{AggregatedMetrics, MetricData}; use opentelemetry_sdk::metrics::{InMemoryMetricExporter, PeriodicReader, SdkMeterProvider}; - #[test] - fn policy_labels_are_bounded_for_the_process_lifetime() { - let provider = SdkMeterProvider::builder().build(); - let metrics = Metrics::new(&provider.meter("supervisor-metrics-test")); - - assert_eq!(&*metrics.policy_label(Policy::NoMatch), "no_match"); - assert_eq!(&*metrics.policy_label(Policy::Unattributed), "unattributed"); - for policy in ["overflow", "no_match", "unattributed", "name:overflow"] { - assert_eq!( - &*metrics.policy_label(Policy::Named(policy)), - format!("name:{policy}"), - ); - } - for index in 4..MAX_POLICY_NAMES { - let policy = index.to_string(); - assert_eq!(&*metrics.policy_label(Policy::Named(&policy)), policy); - } - assert_eq!(&*metrics.policy_label(Policy::Named("16")), "overflow"); - assert_eq!(&*metrics.policy_label(Policy::Named("4")), "4"); - } - #[tokio::test] async fn histograms_and_decisions_record_without_a_sampled_span() { let exporter = InMemoryMetricExporter::default(); @@ -472,12 +392,14 @@ mod tests { .unwrap_err(); assert_eq!(error.kind(), kind); } - decision( - Scope::Connection, + for outcome in [ + Outcome::Allow, Outcome::Deny, - InspectionType::Unknown, - Policy::Unattributed, - ); + Outcome::Audit, + Outcome::FailOpen, + ] { + decision(Scope::Connection, outcome, InspectionType::Unknown); + } provider.force_flush().unwrap(); let records = exporter.get_finished_metrics().unwrap(); @@ -530,7 +452,18 @@ mod tests { panic!("Decision counter should export a sum"); }; assert!(decisions.is_monotonic()); - assert!(decisions.data_points().any(|point| point.value() > 0)); + for outcome in ["allow", "deny", "audit", "fail_open"] { + let labels = [ + KeyValue::new("scope", "connection"), + KeyValue::new("outcome", outcome), + KeyValue::new("inspection_type", "unknown"), + ]; + assert!(decisions.data_points().any(|point| { + point.value() > 0 + && point.attributes().count() == labels.len() + && point.attributes().all(|label| labels.contains(label)) + })); + } let active_connections = |records: &[opentelemetry_sdk::metrics::data::ResourceMetrics]| { diff --git a/crates/openshell-supervisor-network/src/opa.rs b/crates/openshell-supervisor-network/src/opa.rs index c50ba852b9..d09e7e4fc5 100644 --- a/crates/openshell-supervisor-network/src/opa.rs +++ b/crates/openshell-supervisor-network/src/opa.rs @@ -134,8 +134,6 @@ pub struct PolicyDnsEligibilitySnapshot { #[derive(Debug, Clone)] pub struct EgressAuthorization { pub action: NetworkAction, - /// Whether the policy engine evaluated the request. - pub(crate) policy_evaluated: bool, pub endpoint_configs: Vec, pub matched_endpoints: Vec, pub exact_declared_endpoint_host: bool, @@ -660,7 +658,6 @@ impl OpaEngine { if let Some(reason) = fail_closed_reason { return Ok(EgressAuthorization { action: NetworkAction::Deny { reason }, - policy_evaluated: false, endpoint_configs: Vec::new(), matched_endpoints: Vec::new(), exact_declared_endpoint_host: false, @@ -700,7 +697,6 @@ impl OpaEngine { Ok(EgressAuthorization { action, - policy_evaluated: true, endpoint_configs, matched_endpoints, exact_declared_endpoint_host, @@ -9065,9 +9061,6 @@ network_policies: reason: "candidate policy validation failed: conflicting tls".to_string() } ); - let authorization = engine.authorize_egress(&input).unwrap(); - assert_eq!(authorization.action, action); - assert!(!authorization.policy_evaluated); } #[test] diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index 1d1a8a1dcb..f8bb38bbf5 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -17,7 +17,7 @@ use openshell_sandbox_backend::test_support as rpc_test; use crate::identity::{BinaryIdentityCache, SuppliedIdentityError}; use crate::l7::correlation::{HttpOutcome, RequestStage}; use crate::l7::tls::ProxyTlsState; -use crate::metrics::{ActiveConnection, InspectionType, Outcome, ResultLabel, Scope}; +use crate::metrics::{self, ActiveConnection, InspectionType, Outcome, ResultLabel, Scope}; use crate::opa::{NetworkAction, OpaEngine, PolicyGenerationGuard}; #[cfg(test)] use crate::policy_dns::SocketTrustedResolver; @@ -825,7 +825,7 @@ async fn preauthorize_transparent_open( }); let mut decision = supplied_authorization.decision; if let NetworkAction::Deny { reason } = &decision.action { - decision.record_admission(Scope::Connection, Outcome::Deny, InspectionType::Unknown); + metrics::decision(Scope::Connection, Outcome::Deny, InspectionType::Unknown); let (denial, status_detail) = supplied_authorization.denial.map_or( (TcpOpenDenial::PolicyDenied, "transparent_tcp_policy_denied"), |denial| match denial { @@ -1268,7 +1268,7 @@ async fn handle_transparent_tcp_connection( .map_err(|error| miette::miette!("identity resolution task panicked: {error}"))?; if let NetworkAction::Deny { reason } = &decision.action { - decision.record_admission(Scope::Connection, Outcome::Deny, InspectionType::Tcp); + metrics::decision(Scope::Connection, Outcome::Deny, InspectionType::Tcp); emit_transparent_policy_denial(&decision, workload_addr, &host, port); emit_denial( &denial_tx, @@ -1457,7 +1457,7 @@ async fn handle_transparent_tcp_connection( } )); emit_activity(&activity_tx, false, "transparent_tcp"); - decision.record_admission(Scope::Connection, Outcome::Allow, InspectionType::Tcp); + metrics::decision(Scope::Connection, Outcome::Allow, InspectionType::Tcp); relay::relay_tcp(&mut client, &mut upstream, &generation_guard, &ctx).await } @@ -2414,7 +2414,7 @@ async fn deny_connect_destination( where C: TokioAsyncWrite + Unpin, { - decision.record_admission(Scope::Connection, Outcome::Deny, InspectionType::Unknown); + metrics::decision(Scope::Connection, Outcome::Deny, InspectionType::Unknown); let detail = destination_denial_detail(denial.kind); egress_emit!(build_connect_destination_deny_ocsf_event( denial, peer_addr, host, port, binary, pid, ancestors, cmdline, @@ -2477,7 +2477,7 @@ where correlation.record_rejection(403, HttpOutcome::Denied, None); correlation.emit(event); } else { - decision.record_admission(Scope::Request, Outcome::Deny, InspectionType::Http); + metrics::decision(Scope::Request, Outcome::Deny, InspectionType::Http); crate::telemetry::emit_decision([event], Some(connect_span)); } @@ -2933,7 +2933,7 @@ async fn handle_mediated_connection( // Allowed connections are logged after the L7 config check (below) // so we can distinguish CONNECT (L4-only) from CONNECT_L7 (L7 follows). if matches!(decision.action, NetworkAction::Deny { .. }) { - decision.record_admission(Scope::Connection, Outcome::Deny, InspectionType::Unknown); + metrics::decision(Scope::Connection, Outcome::Deny, InspectionType::Unknown); let event = NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(ActivityId::Open) .action(ActionId::Denied) @@ -3113,7 +3113,7 @@ async fn handle_mediated_connection( if refuse_connect_when_tls_unavailable(&mut client, tls_state.is_some(), effective_tls_skip) .await? { - decision.record_admission(Scope::Connection, Outcome::Deny, InspectionType::Unknown); + metrics::decision(Scope::Connection, Outcome::Deny, InspectionType::Unknown); if let Some(observer) = connect_endpoint_observer.as_ref() { observer.observe(EndpointResult::TlsFailed); } @@ -3228,7 +3228,7 @@ async fn handle_mediated_connection( if effective_tls_skip { match middleware_uninspectable_gate(&opa_engine, &ctx)? { crate::l7::middleware::UninspectableTrafficGate::Deny => { - decision.record_admission(Scope::Connection, Outcome::Deny, InspectionType::Tcp); + metrics::decision(Scope::Connection, Outcome::Deny, InspectionType::Tcp); crate::l7::middleware::emit_middleware_uninspectable(&ctx, "tls-skip tunnel", true); respond( &mut client, @@ -3328,7 +3328,7 @@ async fn handle_mediated_connection( else { return Ok(()); }; - decision.record_admission(Scope::Connection, raw_admission, InspectionType::Tcp); + metrics::decision(Scope::Connection, raw_admission, InspectionType::Tcp); relay::relay_tcp(&mut client, &mut upstream, &generation_guard, &ctx).await?; return Ok(()); } @@ -3487,7 +3487,7 @@ async fn handle_mediated_connection( if let Some(protocol_detail) = unsupported_l7_tunnel_protocol_detail(tunnel_protocol, requirement) { - decision.record_admission(Scope::Connection, Outcome::Deny, InspectionType::Unknown); + metrics::decision(Scope::Connection, Outcome::Deny, InspectionType::Unknown); if requirement == InspectionRequirement::RequiredMiddleware { crate::l7::middleware::emit_middleware_uninspectable(&ctx, protocol_detail, true); } @@ -3553,7 +3553,7 @@ async fn handle_mediated_connection( } else { Outcome::Allow }; - decision.record_admission(Scope::Connection, outcome, InspectionType::Tcp); + metrics::decision(Scope::Connection, outcome, InspectionType::Tcp); relay::relay_tcp(&mut client, &mut upstream, &generation_guard, &ctx).await?; } @@ -4823,8 +4823,8 @@ async fn dial_transparent_upstream( } async fn dial_direct(addrs: &[SocketAddr]) -> std::io::Result { - crate::metrics::connect( - crate::metrics::Route::Direct, + metrics::connect( + metrics::Route::Direct, connect_tcp_nodelay_best_effort(addrs), ) .await @@ -5860,7 +5860,7 @@ async fn handle_forward_proxy_inner( let matched_policy = match &decision.action { NetworkAction::Allow { matched_policy } => matched_policy.clone(), NetworkAction::Deny { reason } => { - decision.record_admission(Scope::Request, Outcome::Deny, InspectionType::Http); + metrics::decision(Scope::Request, Outcome::Deny, InspectionType::Http); crate::telemetry::emit_decision( [build_forward_policy_deny_ocsf_event( workload_addr, @@ -6158,7 +6158,7 @@ async fn handle_forward_proxy_inner( .await?; return Ok(()); }; - correlation.select_inspector(l7_config.config.protocol, &l7_ctx.policy_name); + correlation.select_inspector(l7_config.config.protocol); endpoint_observer = crate::l7::EndpointObserver::begin_captured( l7_ctx.endpoint_observation_tx.as_ref(), &l7_config.config, @@ -6589,7 +6589,7 @@ async fn handle_forward_proxy_inner( } else { egress::resolve_span(&connect_span) }; - correlation.inspection_timer(crate::metrics::Timer::pause); + correlation.inspection_timer(metrics::Timer::pause); let resolved = validate_destination(DestinationRequest { host: &raw_host, port, @@ -6598,7 +6598,7 @@ async fn handle_forward_proxy_inner( }) .instrument(resolve_span.clone()) .await; - correlation.inspection_timer(crate::metrics::Timer::resume); + correlation.inspection_timer(metrics::Timer::resume); if inspected { if resolved.is_err() { egress::mark_error(&resolve_span); @@ -7158,11 +7158,11 @@ async fn handle_forward_proxy_inner( } else { egress::dial_span(&connect_span) }; - correlation.inspection_timer(crate::metrics::Timer::pause); - let dial_result = crate::metrics::connect(crate::metrics::Route::Direct, connector.connect()) + correlation.inspection_timer(metrics::Timer::pause); + let dial_result = metrics::connect(metrics::Route::Direct, connector.connect()) .instrument(dial_span.clone()) .await; - correlation.inspection_timer(crate::metrics::Timer::resume); + correlation.inspection_timer(metrics::Timer::resume); let mut upstream = match dial_result { Ok(s) => { if inspected { @@ -7271,7 +7271,7 @@ async fn handle_forward_proxy_inner( }); let _connection = ActiveConnection::new(inspection); if !inspected { - decision.record_admission(Scope::Request, Outcome::Allow, InspectionType::Http); + metrics::decision(Scope::Request, Outcome::Allow, InspectionType::Http); } let outcome_result = relay_rewritten_forward_request( method, diff --git a/crates/openshell-supervisor-network/src/proxy/egress.rs b/crates/openshell-supervisor-network/src/proxy/egress.rs index 9e8f6c7a23..28ff990956 100644 --- a/crates/openshell-supervisor-network/src/proxy/egress.rs +++ b/crates/openshell-supervisor-network/src/proxy/egress.rs @@ -12,6 +12,7 @@ //! drifting as more adapters are added. use super::destination::DestinationValidationPlan; +use crate::metrics::Outcome; use crate::opa::NetworkAction; use std::path::PathBuf; @@ -44,8 +45,6 @@ pub(super) struct EndpointDecision { pub(super) matched_endpoints: Vec, /// Whether policy matched the requested hostname exactly (not by glob). pub(super) exact_declared_host: bool, - /// Whether this snapshot came from a completed evaluator call. - policy_evaluated: bool, } impl Default for EndpointDecision { @@ -57,7 +56,6 @@ impl Default for EndpointDecision { policy_configs: Vec::new(), matched_endpoints: Vec::new(), exact_declared_host: false, - policy_evaluated: false, } } } @@ -68,7 +66,6 @@ impl EndpointDecision { policy_configs: authorization.endpoint_configs.clone(), matched_endpoints: authorization.matched_endpoints.clone(), exact_declared_host: authorization.exact_declared_endpoint_host, - policy_evaluated: authorization.policy_evaluated, ..Self::default() } } @@ -174,24 +171,6 @@ pub(super) struct EgressDecision { pub(super) cmdline_paths: Vec, } -impl EgressDecision { - pub(super) fn record_admission( - &self, - scope: crate::metrics::Scope, - outcome: crate::metrics::Outcome, - inspection_type: crate::metrics::InspectionType, - ) { - use crate::metrics::Policy; - - let policy = match &self.action { - NetworkAction::Allow { matched_policy } => Policy::from(matched_policy.as_deref()), - NetworkAction::Deny { .. } if self.endpoint.policy_evaluated => Policy::NoMatch, - NetworkAction::Deny { .. } => Policy::Unattributed, - }; - crate::metrics::decision(scope, outcome, inspection_type, policy); - } -} - pub(super) fn connect_span(intent: &EgressIntent) -> tracing::Span { tracing::debug_span!( "supervisor.egress.connect", @@ -209,7 +188,6 @@ pub(super) fn dial_span(parent: &tracing::Span) -> tracing::Span { tracing::debug_span!( parent: parent, "supervisor.egress.dial", - openshell.egress.result = tracing::field::Empty, otel.status_code = tracing::field::Empty, ) } @@ -229,18 +207,17 @@ pub(super) fn traced_authorization( "supervisor.egress.authorize", openshell.policy.decision = tracing::field::Empty, openshell.policy.name = tracing::field::Empty, - openshell.egress.result = tracing::field::Empty, ); let result = span.in_scope(|| authorize(intent)); match &decision(&result).action { NetworkAction::Allow { matched_policy } => { - span.record("openshell.policy.decision", "allow"); + span.record("openshell.policy.decision", Outcome::Allow.label()); if let Some(name) = matched_policy { span.record("openshell.policy.name", name.as_str()); } } NetworkAction::Deny { .. } => { - span.record("openshell.policy.decision", "deny"); + span.record("openshell.policy.decision", Outcome::Deny.label()); } } result diff --git a/crates/openshell-supervisor-network/src/proxy/relay.rs b/crates/openshell-supervisor-network/src/proxy/relay.rs index f91c5b7a53..8d1f428d5b 100644 --- a/crates/openshell-supervisor-network/src/proxy/relay.rs +++ b/crates/openshell-supervisor-network/src/proxy/relay.rs @@ -257,7 +257,7 @@ where C: AsyncRead + AsyncWrite + Unpin + Send, U: AsyncRead + AsyncWrite + Unpin + Send, { - use crate::metrics::{self, ActiveConnection, InspectionType, Outcome, Policy, Scope}; + use crate::metrics::{self, ActiveConnection, InspectionType, Outcome, Scope}; let protocol = match &context.policy { PreparedHttpPolicy::Inspect { configs, .. } if configs.len() == 1 => { @@ -268,12 +268,7 @@ where let inspection = protocol.map_or(InspectionType::Http, InspectionType::from_protocol); let _connection = ActiveConnection::new(inspection); if protocol != Some(crate::l7::L7Protocol::Sql) { - metrics::decision( - Scope::Connection, - Outcome::Allow, - inspection, - Policy::from(Some(context.request.policy_name.as_str())), - ); + metrics::decision(Scope::Connection, Outcome::Allow, inspection); } match context.policy { diff --git a/crates/openshell-supervisor-network/src/proxy/tests/request_trace.rs b/crates/openshell-supervisor-network/src/proxy/tests/request_trace.rs index 6586f396b7..654c348863 100644 --- a/crates/openshell-supervisor-network/src/proxy/tests/request_trace.rs +++ b/crates/openshell-supervisor-network/src/proxy/tests/request_trace.rs @@ -528,8 +528,7 @@ network_policies: } if connect_failed { let failure = &records[1]; - assert_eq!(failure["unmapped"]["egress_result"], "error"); - assert!(failure["unmapped"].get("egress_outcome").is_none()); + assert_eq!(failure["status_id"], StatusId::Failure.as_u8()); } else if !policy_denied && !credential_failure { let forwarded = &records[1]; assert!( diff --git a/crates/openshell-supervisor-process/Cargo.toml b/crates/openshell-supervisor-process/Cargo.toml index 1b1dcd5cd9..5e6af570f9 100644 --- a/crates/openshell-supervisor-process/Cargo.toml +++ b/crates/openshell-supervisor-process/Cargo.toml @@ -31,6 +31,7 @@ tokio-stream = { workspace = true } tonic = { workspace = true, features = ["channel", "tls-native-roots"] } tracing = { workspace = true } tracing-subscriber = { workspace = true } +uuid = { workspace = true } [target.'cfg(unix)'.dependencies] libc = "0.2" @@ -43,7 +44,6 @@ openshell-ocsf = { path = "../openshell-ocsf", features = ["test-support"] } openshell-ocsf-validate = { path = "../openshell-ocsf-validate" } tempfile = "3" tokio = { workspace = true, features = ["test-util"] } -uuid = { workspace = true } [lints] workspace = true diff --git a/crates/openshell-supervisor-process/src/delegated.rs b/crates/openshell-supervisor-process/src/delegated.rs index a88fef109c..4f6edaac11 100644 --- a/crates/openshell-supervisor-process/src/delegated.rs +++ b/crates/openshell-supervisor-process/src/delegated.rs @@ -82,7 +82,6 @@ impl Drop for BoundaryAccess { #[allow(clippy::too_many_arguments)] pub async fn start_boundary_access( sandbox_id: Option<&str>, - instance_id: String, gateway: Option<&openshell_core::grpc_client::GatewayEndpoint>, ssh_socket_path: Option<&str>, shared_ssh_socket: bool, @@ -97,6 +96,7 @@ pub async fn start_boundary_access( gateway_home: Option>>, app_installations: Option, ) -> Result { + let instance_id = uuid::Uuid::new_v4().to_string(); let terminating = Arc::new(AtomicBool::new(false)); let attachment = agent .attach() @@ -367,7 +367,6 @@ mod tests { ); let access = start_boundary_access( Some("sandbox"), - "registered-supervisor".into(), Some(&gateway), None, false, @@ -384,7 +383,6 @@ mod tests { ) .await .expect("access without SSH is portable"); - assert_eq!(access.instance_id(), "registered-supervisor"); assert!(access.ssh_task.is_none()); assert!(access.session_task.is_some()); assert!( @@ -412,7 +410,6 @@ mod tests { let boundary = Arc::new(AccessBoundary); let result = start_boundary_access( None, - "registered-supervisor".into(), None, Some("health.sock"), false, diff --git a/crates/openshell-supervisor/src/backend_setup/tests.rs b/crates/openshell-supervisor/src/backend_setup/tests.rs index dfbb483b94..1239250f0f 100644 --- a/crates/openshell-supervisor/src/backend_setup/tests.rs +++ b/crates/openshell-supervisor/src/backend_setup/tests.rs @@ -835,7 +835,6 @@ async fn shared_startup_uses_selected_backend_through_readiness_and_shutdown() { .store(true, Ordering::SeqCst); let startup = |await_main_process_attachment| { let config = crate::SandboxInstanceConfig { - supervisor_instance_id: uuid::Uuid::new_v4().to_string(), app_router: None, command: vec!["test-agent".into(), "test-argument".into()], workdir: Some("/test-workspace".into()), @@ -1054,7 +1053,6 @@ async fn suspend_signal_exits_without_terminating_boundary() { let setup = TestSetup::new(); let startup = || { let config = crate::SandboxInstanceConfig { - supervisor_instance_id: uuid::Uuid::new_v4().to_string(), app_router: None, command: vec!["test-agent".into(), "test-argument".into()], workdir: Some("/test-workspace".into()), diff --git a/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs b/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs index 3e1d2a81a3..de2532e4b6 100644 --- a/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs +++ b/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs @@ -287,7 +287,6 @@ async fn config_push_regression_legacy_gateway_never_observes_ready_before_workl probe: probe.clone(), }; let config = SandboxInstanceConfig { - supervisor_instance_id: uuid::Uuid::new_v4().to_string(), app_router: None, command: vec!["true".into()], workdir: None, diff --git a/crates/openshell-supervisor/src/lib.rs b/crates/openshell-supervisor/src/lib.rs index de7e3a2317..e736528b5a 100644 --- a/crates/openshell-supervisor/src/lib.rs +++ b/crates/openshell-supervisor/src/lib.rs @@ -906,8 +906,6 @@ pub fn trace_context_from_environment() -> Option { /// from its [`SandboxInstanceBindings`], so one process can host several /// instances. pub struct SandboxInstanceConfig { - /// Instance ID sent on this sandbox's supervisor control stream. - pub supervisor_instance_id: String, pub app_router: Option, pub command: Vec, pub workdir: Option, @@ -1091,7 +1089,6 @@ pub async fn run_sandbox_instance( controls: SandboxInstanceControls, ) -> Result { let SandboxInstanceConfig { - supervisor_instance_id, app_router, command, workdir, @@ -1767,7 +1764,6 @@ pub async fn run_sandbox_instance( let agent = running.agent(); let boundary_access = openshell_supervisor_process::delegated::start_boundary_access( sandbox_id.as_deref(), - supervisor_instance_id, gateway.as_ref(), ssh_socket_path.as_deref(), shared_ssh_socket, @@ -4772,7 +4768,6 @@ mod tests { agent_otlp_tls: None, }; let config = SandboxInstanceConfig { - supervisor_instance_id: uuid::Uuid::new_v4().to_string(), app_router: None, command: vec!["true".to_string()], workdir: None, diff --git a/crates/openshell-supervisor/src/main.rs b/crates/openshell-supervisor/src/main.rs index 83b44f7b23..7174788eef 100644 --- a/crates/openshell-supervisor/src/main.rs +++ b/crates/openshell-supervisor/src/main.rs @@ -515,13 +515,11 @@ fn main() -> Result<()> { .enable_all() .build() .into_diagnostic()?; - let instance_id = uuid::Uuid::new_v4().to_string(); let export_config = |endpoint| openshell_otel::OtlpExportConfig { endpoint, service_name: openshell_otel::ServiceName::Fixed(SERVICE_NAME), service_version: Some(openshell_core::VERSION), resource_attributes: supervisor_resource_attributes( - &instance_id, args.sandbox_id.as_deref(), args.gateway_name.as_deref(), ), @@ -552,12 +550,14 @@ fn main() -> Result<()> { .map(|endpoint| { let assigned = sandbox_assigned.clone(); openshell_supervisor::metrics::start( - &instance_id, endpoint, args.otlp_metrics_protocol, auth.map(SupervisorAuthBundle::metrics_otlp) .unwrap_or_default(), args.gateway_name.as_deref(), + args.sandbox_id + .as_deref() + .map(openshell_supervisor::metrics::SupervisorIdentity::Sandbox), move || u64::from(assigned.load(Ordering::Relaxed)), ) }) @@ -660,7 +660,7 @@ fn main() -> Result<()> { }; match args.role { SupervisorRole::IsolationBackend => { - info!(instance_id = %instance_id, command = ?command, "Starting sandbox supervision"); + info!(command = ?command, "Starting sandbox supervision"); let Some(( backend_setup, backend_descriptor, @@ -678,7 +678,6 @@ fn main() -> Result<()> { .transpose()? .map(openshell_supervisor::app_listener::BoundListener::start); let config = openshell_supervisor::SandboxInstanceConfig { - supervisor_instance_id: instance_id, app_router: app_host .as_ref() .map(openshell_supervisor::app_listener::HostHandle::router), @@ -887,24 +886,20 @@ fn target( Ok(openshell_otel::OtlpTarget::new(config)?.with_transport(&transport)) } -/// Resource attributes identifying this supervisor, its sandbox, and gateway. +/// Resource attributes identifying this supervisor's sandbox and the gateway +/// that launched it. fn supervisor_resource_attributes( - instance_id: &str, sandbox_id: Option<&str>, gateway_name: Option<&str>, ) -> Vec { - let mut attributes = vec![opentelemetry::KeyValue::new( - "service.instance.id", - instance_id.to_string(), - )]; - attributes.extend( - sandbox_id.map(|id| opentelemetry::KeyValue::new("openshell.sandbox.id", id.to_string())), - ); - attributes.extend(openshell_otel::gateway_resource_attributes( - gateway_name, - None, - )); - attributes + sandbox_id + .map(|id| opentelemetry::KeyValue::new("openshell.sandbox.id", id.to_string())) + .into_iter() + .chain(openshell_otel::gateway_resource_attributes( + gateway_name, + None, + )) + .collect() } /// Choose the supervisor's exit status for a sandbox run. @@ -1085,7 +1080,7 @@ mod tests { } #[test] - fn telemetry_identifies_the_supervisor_sandbox_and_gateway() { + fn telemetry_names_the_sandbox_and_its_gateway() { let args = Args::try_parse_from([ "openshell-supervisor", "--sandbox-id", @@ -1095,25 +1090,17 @@ mod tests { ]) .expect("parse telemetry identity"); let attributes = supervisor_resource_attributes( - "registered-supervisor", args.sandbox_id.as_deref(), args.gateway_name.as_deref(), ); assert_eq!( attributes, vec![ - opentelemetry::KeyValue::new("service.instance.id", "registered-supervisor"), opentelemetry::KeyValue::new("openshell.sandbox.id", "sb-1"), opentelemetry::KeyValue::new("openshell.gateway.name", "prod-west"), ] ); - assert_eq!( - supervisor_resource_attributes("registered-supervisor", None, None), - vec![opentelemetry::KeyValue::new( - "service.instance.id", - "registered-supervisor", - )] - ); + assert!(supervisor_resource_attributes(None, None).is_empty()); } #[test] diff --git a/crates/openshell-supervisor/src/metrics.rs b/crates/openshell-supervisor/src/metrics.rs index acfd0badc5..15bc6f640b 100644 --- a/crates/openshell-supervisor/src/metrics.rs +++ b/crates/openshell-supervisor/src/metrics.rs @@ -3,6 +3,7 @@ //! Process-owned supervisor metrics export. +use openshell_core::config::DEFAULT_GATEWAY_NAME; use openshell_core::jwt::{OtlpExportCredentials, OtlpTlsMaterial, SecretOtlpHeaders}; use openshell_core::sandbox_env::OtlpProtocol; use openshell_otel::{ @@ -13,25 +14,53 @@ use opentelemetry::metrics::MeterProvider as _; const SERVICE_NAME: &str = "openshell-supervisor"; +/// The deployment identity of a supervisor, independent of its process. +pub enum SupervisorIdentity<'a> { + Sandbox(&'a str), + PoolMember(&'a str), +} + +fn resource_attributes( + gateway_name: Option<&str>, + identity: Option>, +) -> Vec { + let mut attributes = openshell_otel::gateway_resource_attributes(gateway_name, None); + if let Some(identity) = identity { + let (kind, key, id) = match identity { + SupervisorIdentity::Sandbox(id) => ("sandbox", "openshell.sandbox.id", id), + SupervisorIdentity::PoolMember(id) => { + ("pool", "openshell.supervisor.pool_member.id", id) + } + }; + // Keep the components unambiguous when a configured gateway name contains a colon. + let gateway = gateway_name + .map(str::trim) + .filter(|name| !name.is_empty()) + .unwrap_or(DEFAULT_GATEWAY_NAME) + .replace('%', "%25") + .replace(':', "%3A"); + attributes.extend([ + KeyValue::new("service.instance.id", format!("{kind}:{gateway}:{id}")), + KeyValue::new(key, id.to_string()), + ]); + } + attributes +} + /// Create the process's metrics provider inside the runtime driving OTLP. pub fn start( - instance_id: &str, endpoint: &str, protocol: OtlpProtocol, credentials: OtlpExportCredentials<'_>, gateway_name: Option<&str>, + identity: Option>, sandbox_count: impl Fn() -> u64 + Send + Sync + 'static, ) -> Result { - let mut resource_attributes = openshell_otel::gateway_resource_attributes(gateway_name, None); - resource_attributes.push(KeyValue::new( - "service.instance.id", - instance_id.to_string(), - )); let config = OtlpExportConfig { endpoint, service_name: ServiceName::Fixed(SERVICE_NAME), service_version: Some(openshell_core::VERSION), - resource_attributes, + resource_attributes: resource_attributes(gateway_name, identity), }; let transport = CollectorTransport { protocol: protocol.into(), @@ -74,15 +103,26 @@ mod tests { use opentelemetry_proto::tonic::metrics::v1::metric::Data; use prost::Message as _; + #[test] + fn dedicated_metrics_identify_the_gateway_and_sandbox() { + let attributes = resource_attributes( + Some("test:gateway"), + Some(SupervisorIdentity::Sandbox("sandbox-id")), + ); + assert!(attributes.contains(&KeyValue::new( + "service.instance.id", + "sandbox:test%3Agateway:sandbox-id", + ))); + assert!(attributes.contains(&KeyValue::new("openshell.sandbox.id", "sandbox-id"))); + } + #[tokio::test(flavor = "multi_thread")] async fn pushes_supervisor_gauges_and_resource_to_the_collector() { let mut collector = OtlpHttpTestServer::start().await; let path = format!("{}/receiver", collector.endpoint()); let headers = SecretOtlpHeaders::new("x-collector-test=metrics".to_string()); let count = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(2)); - let instance_id = "registered-supervisor"; let provider = start( - instance_id, &path, OtlpProtocol::HttpProtobuf, OtlpExportCredentials { @@ -90,6 +130,7 @@ mod tests { tls: None, }, Some("test-gateway"), + Some(SupervisorIdentity::PoolMember("member-1")), { let count = count.clone(); move || count.load(std::sync::atomic::Ordering::Relaxed) @@ -109,7 +150,14 @@ mod tests { let response = ExportMetricsServiceRequest::decode(received.body).unwrap(); let resource = &response.resource_metrics[0]; let attributes = &resource.resource.as_ref().unwrap().attributes; - assert!(attributes.contains(&string_attribute("service.instance.id", instance_id))); + assert!(attributes.contains(&string_attribute( + "service.instance.id", + "pool:test-gateway:member-1", + ))); + assert!(attributes.contains(&string_attribute( + "openshell.supervisor.pool_member.id", + "member-1", + ))); assert!( attributes.contains(&string_attribute("openshell.gateway.name", "test-gateway")) ); diff --git a/crates/openshell-supervisor/src/shared_host.rs b/crates/openshell-supervisor/src/shared_host.rs index 95d65491a5..ffe93790a0 100644 --- a/crates/openshell-supervisor/src/shared_host.rs +++ b/crates/openshell-supervisor/src/shared_host.rs @@ -383,7 +383,7 @@ impl SharedHost { } } - fn start_metrics(self: &Arc, instance_id: &str, configuration: &[u8]) { + fn start_metrics(self: &Arc, configuration: &[u8]) { if configuration.is_empty() || self.metrics_provider.get().is_some() { return; } @@ -395,7 +395,6 @@ impl SharedHost { }; let host = Arc::downgrade(self); let result = crate::metrics::start( - instance_id, &config.collector.endpoint, config.collector.protocol, openshell_core::jwt::OtlpExportCredentials { @@ -403,6 +402,9 @@ impl SharedHost { tls: config.tls.as_ref(), }, Some(&config.gateway_name), + Some(crate::metrics::SupervisorIdentity::PoolMember( + &self.pool.member_id, + )), move || host.upgrade().map_or(0, |host| host.assigned_sandboxes()), ); match result { @@ -838,7 +840,6 @@ impl SharedHost { crate::sandbox_instance_host::prepare_private_dir(&trust_dir).map_err(failure)?; let ssh_socket = dir.join("ssh.sock"); let config = crate::SandboxInstanceConfig { - supervisor_instance_id: uuid::Uuid::new_v4().to_string(), app_router: self .app_listener .as_ref() @@ -1495,7 +1496,6 @@ async fn run_stream( .is_ok_and(|sent| sent.is_ok()) } }; - let instance_id = hello.instance_id.clone(); if !send( HostMessage { payload: Some(host_message::Payload::Hello(hello)), @@ -1549,11 +1549,11 @@ async fn run_stream( last_heard = tokio::time::Instant::now(); match payload { Some(host_gateway_message::Payload::Accepted(accepted_message)) => { - host.start_metrics(&instance_id, &accepted_message.supervisor_metrics); + host.start_metrics(&accepted_message.supervisor_metrics); accepted = true; host.gateway_connected.send_replace(true); host.gateway_home.send_replace(Some(accepted_message.peer_endpoint.clone())); - tracing::info!(instance_id = %instance_id, session = %accepted_message.session_id, "gateway accepted the supervisor host"); + tracing::info!(session = %accepted_message.session_id, "gateway accepted the supervisor host"); // A pool gateway detects failed members by silence, // so it asks for more frequent heartbeats. if let Some(interval) = accepted_message diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index f126e32351..35184e2064 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -818,11 +818,13 @@ Each enabled signal needs an endpoint, either in its own table or from `endpoint `protocol` selects the transport to a collector: `grpc`, the default, or `http/protobuf`. With `http/protobuf`, the endpoint is a base URL and each signal is posted to its path under it, `/v1/traces`, `/v1/logs`, or `/v1/metrics`, as with `OTEL_EXPORTER_OTLP_ENDPOINT`. HTTP/JSON is not supported. Point a `grpc` endpoint at a collector's gRPC receiver, conventionally port `4317`, and an `http/protobuf` endpoint at its HTTP receiver, conventionally port `4318`. A URI alone cannot distinguish the two, so a mismatched endpoint is accepted at startup and then fails on export. Sandbox supervisors and standalone compute drivers must come from the same release as the gateway to use `http/protobuf`: an older supervisor exports over gRPC, and an older driver rejects the protocol setting. -`headers` sets request headers sent with every export to a collector, as gRPC metadata or HTTP headers, such as an authorization token or a backend's routing header. Each name must be a valid HTTP header name set once, ignoring case; names the exporters set themselves, such as `content-type`, `host`, and `grpc-*`, and binary gRPC names ending in `-bin` are rejected. Each value must be non-empty printable ASCII; spaces are allowed. The gateway's exporters also read their signal's `OTEL_EXPORTER_OTLP_TRACES_HEADERS`, `OTEL_EXPORTER_OTLP_LOGS_HEADERS`, or `OTEL_EXPORTER_OTLP_METRICS_HEADERS`, or else `OTEL_EXPORTER_OTLP_HEADERS`, and a header set there replaces a configured header of the same name. In-process compute drivers and the VM driver send the gateway's trace headers, including those from the environment, with their own spans. A standalone compute driver sends only the headers in its own `OTEL_EXPORTER_OTLP_*HEADERS` variables. Supervisors send their trace collector's `headers` with their own spans, and the gateway's OCSF headers, including those from the environment, with their OCSF records. Trace headers from the gateway's environment do not reach supervisors, so set `headers` or `headers_file` on the trace collector when supervisor spans need them. The agent trace relay sends only its collector's `headers`, never ones from the environment, so its credentials can only be set with `headers` or `headers_file`. A changed header takes effect when the gateway restarts, and reaches a running sandbox only after that sandbox restarts. +`headers` sets request headers sent with every export to a collector, as gRPC metadata or HTTP headers, such as an authorization token or a backend's routing header. Each name must be a valid HTTP header name set once, ignoring case; names the exporters set themselves, such as `content-type`, `host`, and `grpc-*`, and binary gRPC names ending in `-bin` are rejected. Each value must be non-empty printable ASCII; spaces are allowed. The gateway's exporters also read their signal's `OTEL_EXPORTER_OTLP_TRACES_HEADERS`, `OTEL_EXPORTER_OTLP_LOGS_HEADERS`, or `OTEL_EXPORTER_OTLP_METRICS_HEADERS`, or else `OTEL_EXPORTER_OTLP_HEADERS`, and a header set there replaces a configured header of the same name. In-process compute drivers and the VM driver send the gateway's trace headers, including those from the environment, with their own spans. A standalone compute driver sends only the headers in its own `OTEL_EXPORTER_OTLP_*HEADERS` variables. + +Supervisors send the gateway's OCSF and metrics headers, including environment overrides, with their own OCSF records and metrics. For supervisor traces and the agent trace relay, set `headers` or `headers_file` on the corresponding collector. Header changes take effect when the gateway restarts and reach supervisors when they next start. Put credentials in `headers_file` rather than `headers`. It reads a collector's headers from a file instead, such as a mounted Kubernetes Secret, so credentials stay out of the configuration file. The file holds one `name=value` header per line. Blank lines are skipped, and whitespace around each name and value is trimmed. The headers are validated like `headers`, the file must be UTF-8 and at most 64 KiB, and setting both `headers` and `headers_file` in one table is a configuration error. A relative path uses the gateway's working directory. The gateway reads the file at startup and fails to start if it is missing or invalid, so a changed file takes effect as a changed header does. -Supervisors receive the gateway's headers but export to the endpoints their compute driver gives them. An external compute driver takes those endpoints from its own flags, so give it the same endpoints as the gateway, or supervisors send the gateway's credentials to a different collector. Supervisors and external compute drivers from an earlier release than the gateway reject launch credentials that carry trace or agent relay headers, so when the trace or agent collector sets `headers` or `headers_file`, upgrade them with or before the gateway. A gateway rolled back to an earlier release cannot read the stored launch credentials of sandboxes created with those headers, so delete and recreate those sandboxes after a rollback. +Dedicated supervisors receive the gateway's headers but export to the endpoints their compute driver gives them. An external compute driver takes those endpoints from its own flags, so give it the same endpoints as the gateway to send the gateway's credentials to the intended collector. Upgrade dedicated supervisors and external compute drivers with or before the gateway when enabling authenticated trace, metrics, or agent relay export. Earlier releases can reject launch credentials containing the new collector settings. If you roll back to such a release, delete and recreate the sandboxes created with those settings. Headers travel in cleartext unless the endpoint uses `https://`, so use TLS when they carry credentials over an untrusted network. @@ -927,11 +929,10 @@ In-process compute drivers read their backend-specific settings from `[openshell ### OTLP Metrics -Set `enabled = true` in `[openshell.gateway.otlp.metrics]` to push gateway -metrics over OTLP. It defaults to `false` and uses the table's collector -settings, or inherits the shared endpoint, protocol, headers, and TLS settings -from `[openshell.gateway.otlp]` when its own `endpoint` is omitted. This works -even when `[openshell.gateway.otlp.traces]` selects a different collector. +Set `enabled = true` in `[openshell.gateway.otlp.metrics]` to push gateway and +supervisor metrics over OTLP. It defaults to `false`. Both use the table's +collector settings, or inherit the shared endpoint, protocol, headers, and TLS +settings from `[openshell.gateway.otlp]` when the metrics table omits `endpoint`. ```toml [openshell.gateway.otlp.metrics] @@ -939,15 +940,18 @@ enabled = true # endpoint = "https://metrics-collector:4317" # optional override ``` -Metric export works with or without the Prometheus listener. Metric names and -labels are preserved: for example, `openshell_server_grpc_requests_total` -keeps that name, and `openshell_server_grpc_request_duration_seconds` is one -OTLP histogram with that name, not separate `_bucket`, `_sum`, or `_count` -metric names. Prometheus summary quantiles are not exported. Metrics carry the -gateway's trace resource attributes and a `service.instance.id` that distinguishes -gateway processes. Set it through `OTEL_RESOURCE_ATTRIBUTES` to override the -generated process identity. Supervisors and workloads do not export metrics -through this setting. +If you already enable gateway metrics over OTLP, this setting now also enables +supervisor export. Make the collector reachable from the gateway and its +supervisors. See [Supervisor Metrics](/observability/gateway-metrics#supervisor-metrics) +for the egress metrics catalog. + +Metric export works with or without the Prometheus listener. Gateway metric +names and labels are preserved. The OTLP export sends +`openshell_server_grpc_request_duration_seconds` as a single histogram and +omits Prometheus summary quantiles. Gateway metrics carry the gateway's trace +resource attributes and a `service.instance.id` that distinguishes gateway +processes. Set it through `OTEL_RESOURCE_ATTRIBUTES` to override the generated +gateway process identity. For Helm, set `gatewayConfig."openshell.gateway.otlp.metrics".enabled: true`. @@ -981,23 +985,6 @@ A collector can accept a batch while rejecting some of its records, an OTLP part Metrics include `openshell_ocsf_otlp_queued_total`, `openshell_ocsf_otlp_exported_total`, `openshell_ocsf_otlp_dropped_total` (with a `reason` label of `queue_capacity`, `queue_bytes`, `oversized`, `export_failed`, `serialization`, or `closed`), `openshell_ocsf_otlp_export_errors_total`, and `openshell_ocsf_otlp_retries_total`. -### Supervisor Metrics Export - -Enable supervisor egress metrics in `gateway.toml`. - -```toml -[openshell.gateway.otlp.supervisor_metrics] -enabled = true -endpoint = "https://otel-collector.observability.svc:4317" -``` - -Omit `endpoint` to inherit the full `[openshell.gateway.otlp]` collector -configuration. With its own endpoint, this table accepts the same protocol, -header, and TLS settings as the base collector table. The collector must be -reachable from supervisor processes. In Helm, put the table under -`gatewayConfig`. See [Supervisor Metrics](/observability/gateway-metrics#supervisor-metrics) -for the catalog. - ### 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: diff --git a/docs/observability/gateway-metrics.mdx b/docs/observability/gateway-metrics.mdx index d6a5f235de..53ef488f39 100644 --- a/docs/observability/gateway-metrics.mdx +++ b/docs/observability/gateway-metrics.mdx @@ -12,54 +12,48 @@ The gateway exports Prometheus metrics for API requests, database readiness, gateway interceptors, the OCSF log file, and multi-replica capacity. Use them to alert on saturation, to follow rollouts, and to choose autoscaling signals. -Supervisors push egress metrics to an OTLP collector. - ## Supervisor Metrics -Enable [supervisor metrics export](/how-it-works/gateways/configuration#supervisor-metrics-export) +Supervisors push egress metrics to the same OTLP collector as the gateway. +Enable [OTLP metrics export](/how-it-works/gateways/configuration#otlp-metrics) and configure your collector to forward the metrics to your backend. -`openshell.gateway.name` and `service.instance.id` are OTLP resource attributes -for grouping by gateway and supervisor process. -A dedicated supervisor uses its sandbox control-stream registration ID as -`service.instance.id` across metrics, traces, and OTLP OCSF records. A shared -supervisor uses its host registration ID. Search gateway logs for the instance -ID in `supervisor session: accepted` to find the dedicated supervisor's sandbox, -or in `supervisor host attached` to find the shared supervisor's pool member. +Supervisor metrics carry the gateway installation name in +`openshell.gateway.name`. The `service.instance.id` combines the gateway name +with the sandbox ID for dedicated supervisors or the pool member ID for shared +supervisors. A restart preserves the ID when those inputs stay the same. + +Dedicated metrics carry the sandbox ID in `openshell.sandbox.id`. Shared metrics +carry the member ID in `openshell.supervisor.pool_member.id`. Helm uses the +supervisor Pod name as the member ID. A replacement Pod gets a new member ID. | Metric | Type | Labels | Measures | | --- | --- | --- | --- | -| `openshell_supervisor_egress_decisions_total` | Counter | `scope`, `outcome`, `inspection_type`, `policy` | Final egress admission decisions. | +| `openshell_supervisor_egress_decisions_total` | Counter | `scope`, `outcome`, `inspection_type` | Final egress admission decisions. | | `openshell_supervisor_policy_evaluation_duration_seconds` | Histogram | `scope`, `result` | Policy evaluation, including input construction and engine lock wait. | | `openshell_supervisor_request_inspection_duration_seconds` | Histogram | `scope`, `inspection_type`, `result` | Inspection of a request or message before forwarding. | | `openshell_supervisor_upstream_connect_duration_seconds` | Histogram | `route`, `result` | New upstream connections, including address fallback and proxy negotiation. | | `openshell_supervisor_connections_active` | Gauge | `inspection_type` | Live proxied connections. | | `openshell_supervisor_sandboxes_active` | Gauge | | Sandbox assignments held by this supervisor. | -Decision scopes are `connection`, `request`, and `message`. Outcomes are -`allow`, `deny`, `audit`, and `fail_open`. All histograms use the results -`success`, `deny`, `error`, `timeout`, and `cancelled`, with explicit duration -buckets from 0.1 milliseconds to 15 seconds. Upstream routes are `direct` and -`proxy`. Inspection types are `tcp`, `http`, `rest`, `graphql`, `json-rpc`, -`mcp`, `websocket`, and `unknown`. +Decision scopes are `connection`, `request`, and `message`. Admission outcomes +are `allow`, `deny`, `audit`, and `fail_open`, as in policy and middleware +records. All histograms use the results `success`, `deny`, `error`, `timeout`, +and `cancelled`, with explicit duration buckets from 0.1 milliseconds to 15 +seconds. Upstream routes are `direct` and `proxy`. Inspection types are `tcp`, +`http`, `rest`, `graphql`, `json-rpc`, `mcp`, `websocket`, and `unknown`. A decision records one outcome. A denial takes precedence over `fail_open`, which takes precedence over `audit`. CONNECT allows are counted when the tunnel is admitted to relay, after any required TLS handshake. The OCSF CONNECT allow records the earlier `200 Connection Established` response. -A supervisor retains the first 16 distinct attributed policy names of up to -128 bytes for its lifetime. `no_match` means evaluation matched no configured -policy. `unattributed` means the decision has no available policy name. -Additional or longer names use `overflow`. A policy name that collides -with a reserved value is prefixed with `name:`. - -In Prometheus, these queries show decisions by outcome and policy and the 95th +In Prometheus, these queries show decision rates by scope and outcome and the 95th percentile for upstream connects. Adjust the names if your collector renames the metrics. ```promql -sum by (outcome, policy) (rate(openshell_supervisor_egress_decisions_total[5m])) +sum by (scope, outcome) (rate(openshell_supervisor_egress_decisions_total[5m])) ``` ```promql diff --git a/docs/observability/overview.mdx b/docs/observability/overview.mdx index a5a6d701de..ae837dec41 100644 --- a/docs/observability/overview.mdx +++ b/docs/observability/overview.mdx @@ -15,7 +15,7 @@ OpenShell produces three kinds of observability signals: traces, metrics, and OC | Traces | Gateway, compute drivers, sandbox supervisors | OTLP collector | | Agent traces | Agents, relayed by sandbox supervisors | OTLP collector | | Gateway metrics | Gateway | Prometheus scrape, optional OTLP push | -| Supervisor egress metrics | Sandbox supervisors | OTLP collector | +| Supervisor egress metrics | Sandbox supervisors | Optional OTLP push | | OCSF events, shorthand | Gateway, sandbox supervisors | Gateway console, `openshell logs`, supervisor log file | | OCSF events, JSONL | Gateway, sandbox supervisors | Local file | | OCSF events, OTLP | Gateway, sandbox supervisors | OTLP collector | @@ -24,17 +24,17 @@ The examples on this page are `gateway.toml` tables. In the Helm chart, set each ## OTLP Collectors -Configure OTLP export in `gateway.toml`. The gateway exports its own signals and passes each collector's settings to the compute drivers and sandbox supervisors it starts. Supervisors export their own signals and relay the agent's traces directly, so each collector must be reachable from sandboxes as well as from the gateway. +Configure OTLP export in `gateway.toml`. The gateway exports its own signals and passes each collector's settings to the compute drivers and sandbox supervisors. Supervisors export their own signals and relay agent traces. Each collector must be reachable from every process that exports to it. ![OpenShell OTLP collectors. The gateway and its compute drivers export spans to the trace collector, and the gateway exports its OCSF events to the OCSF collector. The gateway gives each sandbox supervisor its collector settings with the launch credentials. The supervisor exports its own spans and OCSF events to the same collectors. The network-isolated agent sends OTLP/HTTP to the supervisor's agent trace relay, which tags the spans with the sandbox ID and forwards them to the agent trace collector.](../images/openshell-otlp-collectors.svg) -`[openshell.gateway.otlp]` sets one collector for every signal. `[openshell.gateway.otlp.traces]`, `[openshell.gateway.otlp.ocsf]`, and `[openshell.gateway.otlp.agent]` can each send their signal to a different collector instead, such as a SIEM for OCSF events or an MLflow tracking server for agent traces. Each collector has its own transport settings: +`[openshell.gateway.otlp]` sets a default collector. The `traces`, `metrics`, `ocsf`, and `agent` tables can each select a collector for their signal. Each collector has its own transport settings: - OTLP over gRPC, the default, or HTTP/protobuf. - Request headers, such as an authorization token, set inline or read from a file. - TLS, verified against the system trust roots or a CA file, with an optional client certificate. -Supervisors receive collector headers and TLS material with their launch credentials, never through the sandbox environment. The agent reaches the relay through the sandbox's mediated channel, so it needs no egress rule and never sees the agent trace collector's address or credentials. +Supervisors receive collector headers and TLS material in their launch credentials or on the authenticated assignment stream. The agent reaches the relay through the sandbox's mediated channel, so it needs no egress rule and never sees the agent trace collector's address or credentials. The gateway ignores the `OTEL_*` variables that would choose which signals are exported or where they go, and honors those that tune export, such as sampling. For every setting, refer to [OTLP Export](/how-it-works/gateways/configuration#otlp-export) and [Tuning](/how-it-works/gateways/configuration#tuning). @@ -69,8 +69,8 @@ While the relay is on, every workload process gets `OTEL_EXPORTER_OTLP_ENDPOINT` The gateway serves Prometheus metrics for API requests, readiness, gateway interceptors, OCSF output, and multi-replica capacity, on a listener separate from its API. Use them to alert on saturation and to choose autoscaling signals. -To push these metrics to an OTLP collector independently of the scrape -listener, refer to [OTLP Metrics](/how-it-works/gateways/configuration#otlp-metrics). +To push gateway and supervisor metrics to the same OTLP collector, enable +[OTLP Metrics](/how-it-works/gateways/configuration#otlp-metrics). To enable the listener, set `metrics_bind_address` in `gateway.toml`: diff --git a/docs/observability/traces.mdx b/docs/observability/traces.mdx index d8b610da8e..abe075e27b 100644 --- a/docs/observability/traces.mdx +++ b/docs/observability/traces.mdx @@ -55,7 +55,6 @@ Resource attributes identify which process produced a span: |---|---|---| | `service.name` | `openshell-gateway`, `openshell-driver-`, such as `openshell-driver-docker`, or `openshell-supervisor` | Every span | | `service.version` | The OpenShell version | Every span | -| `service.instance.id` | The supervisor's sandbox control-stream registration ID | Dedicated supervisor spans | | `openshell.gateway.name` | The gateway name | Every span | | `openshell.gateway.compute_driver` | The configured compute driver, such as `kubernetes` | Gateway and compute-driver spans | | `openshell.sandbox.id` | The sandbox ID | Supervisor spans | diff --git a/proto/supervisor_host.proto b/proto/supervisor_host.proto index 55bfeb0c3a..5643ff3638 100644 --- a/proto/supervisor_host.proto +++ b/proto/supervisor_host.proto @@ -97,7 +97,7 @@ message HostAccepted { // Optional JSON-encoded OTLP configuration for the host's own metrics. // Includes collector credentials and is sent only over this authenticated // supervisor stream. - bytes supervisor_metrics = 4; + bytes supervisor_metrics = 4 [(openshell.options.v1.secret) = true]; } // Another gateway replica should serve the host, which dials it at once. The diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index 9c2506bd0a..46095406a2 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -1646,7 +1646,7 @@ credential failures. | Collector receives no OCSF log records, or `openshell.ocsf.gap` records | `[openshell.gateway.otlp.ocsf]` missing or without `enabled = true`, an unreachable endpoint or one that does not speak the table's `protocol`, or export failures and queue pressure | Check `[openshell.gateway.otlp.ocsf]` for `enabled = true` and the endpoint it resolves to, the gateway's `OTLP exporting enabled` startup log for `ocsf_endpoint` and `ocsf_protocol`, export warnings, and `openshell_ocsf_otlp_*` metrics. See the published [gateway configuration reference](https://docs.nvidia.com/openshell/latest/how-it-works/gateways/configuration). | | Gateway OCSF JSONL stops growing, has gaps, or is rejected by a SIEM | File errors, queue pressure, or shipper falling behind retention | Inspect gateway warnings and `openshell_ocsf_log_*` metrics; check `[openshell.gateway.ocsf_log]`, directory permissions, free space, per-replica paths, and shipper rotation checkpoints. See the published [gateway configuration reference](https://docs.nvidia.com/openshell/latest/how-it-works/gateways/configuration). | | `BatchSpanProcessor.ExportError` repeatedly reports connection refused on `127.0.0.1:4317` | The local gateway started with `OPENSHELL_DEV_OTLP_ENDPOINT` set but no collector is listening, for example because `helm:k3s:forward` stopped | Start the collector forwarding again, or restart the gateway task without `OPENSHELL_DEV_OTLP_ENDPOINT`; inspect the generated `gateway.toml` for `[openshell.gateway.otlp]` | -| Collector receives no supervisor metrics | Supervisor metrics export is off, or the collector cannot receive OTLP from the supervisor | Check `enabled = true` in `[openshell.gateway.otlp.supervisor_metrics]`, the resolved collector endpoint and protocol, and the supervisor's OTLP export warnings. See the published [gateway configuration reference](https://docs.nvidia.com/openshell/latest/how-it-works/gateways/configuration). | +| Collector receives no supervisor metrics | OTLP metrics export is off, or the metrics collector is unreachable from the supervisor | Check `enabled = true` in `[openshell.gateway.otlp.metrics]`, reachability to the resolved collector from the supervisor, and the supervisor's OTLP export warnings. See [OTLP metrics](https://docs.nvidia.com/openshell/latest/how-it-works/gateways/configuration#otlp-metrics). | | Sandbox log shows `OTLP agent trace relay inactive: not enabled by the gateway` at startup, then `agent OTLP export attempted but the agent trace relay is not enabled` when the agent exports | The gateway does not enable `[openshell.gateway.otlp.agent]`, so the supervisor refuses the workload's OTLP relay address | Set `enabled = true` in `[openshell.gateway.otlp.agent]` (Helm: `gatewayConfig."openshell.gateway.otlp.agent".enabled`) with an endpoint from that table or `[openshell.gateway.otlp]`, and recreate the sandbox; `openshell logs --source sandbox` then shows `OTLP agent trace relay enabled` | | Gateway starts but sandbox create fails | Compute driver cannot reach runtime | Docker/Podman/Kubernetes/VM driver logs | | Docker or Podman sandbox never registers | Wrong gateway endpoint, unavailable host networking, or supervisor startup failure | Gateway logs and supervisor container logs |