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-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 1f64a329a2..ce88f23d7d 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 [ 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-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 32641d0937..bd0d41323d 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -13993,13 +13993,17 @@ mod tests { traces: secret("authorization=traces"), ocsf: secret("authorization=Bearer%20secret"), agent: secret("x-mlflow-experiment-id=0"), + 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( @@ -14033,11 +14037,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()); @@ -14048,6 +14054,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 68e3207ba5..391ff876c4 100644 --- a/crates/openshell-server/src/config_file.rs +++ b/crates/openshell-server/src/config_file.rs @@ -416,7 +416,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.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 — @@ -435,7 +435,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", @@ -518,6 +518,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.metrics.as_ref().map(OtlpCollectorConfig::export), } } } @@ -884,7 +885,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, @@ -928,7 +929,7 @@ pub struct AgentOtlpConfig { #[serde(deny_unknown_fields)] struct RawOtlpConfig { #[serde(default)] - metrics: Option, + metrics: Option, #[serde(default)] endpoint: Option, #[serde(default)] @@ -950,33 +951,12 @@ struct RawOtlpConfig { #[serde(default)] ocsf: Option, #[serde(default)] - agent: Option, + 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, - #[serde(default)] - ca_file: Option, - #[serde(default)] - cert_file: Option, - #[serde(default)] - key_file: Option, -} - -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct RawOtlpMetrics { +struct RawEnabledOtlp { #[serde(default)] enabled: bool, #[serde(default)] @@ -2296,6 +2276,7 @@ service_name = "openshell-gateway-dev" assert!(otlp.service_name.is_none()); assert_eq!(otlp.ocsf, None); assert!(otlp.metrics.is_none()); + assert!(otlp.supervisor_otlp().metrics.is_none()); } #[test] @@ -2310,6 +2291,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" @@ -2331,6 +2313,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\ @@ -2340,6 +2323,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_eq!(own.supervisor_otlp().metrics, Some(metrics.export())); let error = toml::from_str::( "[metrics]\nenabled = true\n[traces]\nendpoint = 'http://traces:4317'\n", @@ -2477,6 +2461,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 799c46e397..34ffd1babb 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -952,16 +952,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(collector) = otlp.and_then(|otlp| otlp.metrics.as_ref()) + { + let metrics = openshell_core::sandbox_env::SharedSupervisorMetrics { + collector: collector.export(), + gateway_name: config.name.clone(), + headers: supervisor_headers.metrics.clone(), + tls: supervisor_tls + .metrics + .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 301c052d98..6e30d6e84d 100644 --- a/crates/openshell-server/src/otel_tracing.rs +++ b/crates/openshell-server/src/otel_tracing.rs @@ -329,12 +329,14 @@ 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, pub ocsf: Option, pub agent: Option, + pub metrics: Option, } impl SupervisorOtlpHeaders { @@ -342,14 +344,15 @@ 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); } } /// 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()) } @@ -407,6 +410,13 @@ fn supervisor_otlp_headers_from( .agent .as_ref() .and_then(|agent| configured(&agent.collector)), + metrics: otlp.metrics.as_ref().and_then(|metrics| { + secret_headers(with_env_headers( + metrics, + "OTEL_EXPORTER_OTLP_METRICS_HEADERS", + &var, + )) + }), } } @@ -419,6 +429,7 @@ pub struct SupervisorOtlpTls { pub traces: Option, pub ocsf: Option, pub agent: Option, + pub metrics: Option, } impl SupervisorOtlpTls { @@ -427,6 +438,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 +465,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.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 +484,7 @@ pub fn supervisor_otlp_tls(otlp: Option<&OtlpConfig>) -> SupervisorOtlpTls { traces, ocsf, agent, + metrics, } } @@ -834,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() @@ -855,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), @@ -864,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"), ]), ); @@ -882,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()), @@ -895,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!( @@ -903,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 @@ -982,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"), @@ -998,7 +1033,7 @@ mod tests { 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-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 69ad6ded82..3e70bb431f 100644 --- a/crates/openshell-supervisor-control/src/controller.rs +++ b/crates/openshell-supervisor-control/src/controller.rs @@ -354,6 +354,7 @@ struct Inner { observed: Mutex, /// This replica's peer endpoint, sent in every `HostAccepted`. peer_endpoint: Mutex, + supervisor_metrics: Mutex>, /// Size limits of the pool and each member. limits: Mutex, /// Live gateway replicas serving the pool, which scale its capacity. @@ -409,6 +410,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()), limits: Mutex::new(PoolLimits::default()), gateway_replicas: AtomicUsize::new(1), }), @@ -448,6 +450,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) { @@ -899,6 +906,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(), @@ -907,6 +915,7 @@ impl SupervisorHostController { nanos: 0, }), peer_endpoint, + supervisor_metrics, })), })) .await diff --git a/crates/openshell-supervisor-network/src/l7/correlation.rs b/crates/openshell-supervisor-network/src/l7/correlation.rs index 1d4cfe36fa..b2a0ff9990 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; @@ -137,6 +143,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 +161,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 +277,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(); Self::install(RequestScope { request_id, inspected: true, @@ -295,6 +316,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 +336,47 @@ impl RequestCorrelation { .map_or_else(tracing::Span::none, |trace| trace.stage(stage)) } + pub(crate) fn select_inspector(&self, protocol: crate::l7::L7Protocol) { + 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)); + } + } + + 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 +493,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 9349886d72..cca7823397 100644 --- a/crates/openshell-supervisor-network/src/l7/relay.rs +++ b/crates/openshell-supervisor-network/src/l7/relay.rs @@ -1551,6 +1551,8 @@ where } L7Protocol::Graphql => relay_graphql(config, &engine, client, upstream, ctx).await, L7Protocol::Sql => { + use crate::metrics::{self, InspectionType, Outcome, Scope}; + if close_if_stale(engine.generation_guard(), ctx) { return Ok(()); } @@ -1558,15 +1560,20 @@ 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); + if matches!(outcome, Outcome::Deny) { + return Ok(()); } // SQL provider is Phase 3 — fall through to passthrough with warning { @@ -1705,6 +1712,7 @@ where .map_err(&capture_error)?; return Ok(()); }; + correlation.select_inspector(config.protocol); let observer = EndpointObserver::begin_captured( ctx.endpoint_observation_tx.as_ref(), config, @@ -1912,12 +1920,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()); @@ -2692,6 +2700,7 @@ where } }; let correlation = RequestCorrelation::new(&req, ctx); + 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)) @@ -2784,11 +2793,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. @@ -3252,6 +3265,7 @@ where let req = parsed.request; let jsonrpc_info = parsed.info; let correlation = RequestCorrelation::new(&req, ctx); + correlation.select_inspector(config.protocol); let capture_error = |error| correlation.capture_error(error); let observer = EndpointObserver::begin_captured( ctx.endpoint_observation_tx.as_ref(), @@ -3350,12 +3364,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 { @@ -3625,6 +3639,7 @@ where } }; let correlation = RequestCorrelation::new(&req, ctx); + correlation.select_inspector(config.protocol); let capture_error = |error| correlation.capture_error(error); if !request_authority_matches_endpoint(&req, ctx) { @@ -3728,12 +3743,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 { @@ -4425,6 +4440,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!( @@ -4433,7 +4457,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..8f98e3473e 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, ResultLabel, Scope, Stage, Timer}; const MAX_TRACEPARENT_BYTES: usize = 256; @@ -19,6 +20,9 @@ pub(super) struct RequestTrace { span: Span, outcome: &'static str, failure_reason: Option<&'static str>, + inspection: Option, + inspection_type: InspectionType, + admission: Outcome, } #[derive(Debug, Clone, Copy)] @@ -84,9 +88,55 @@ impl RequestTrace { span, outcome: "incomplete", failure_reason: None, + inspection: None, + inspection_type: InspectionType::Http, + admission: Outcome::Allow, } } + 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) { + self.inspection_type = inspection_type; + 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 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, + }; + if let Some(outcome) = outcome { + metrics::decision(Scope::Request, outcome, self.inspection_type); + } + timer.finish(result); + } + pub(super) fn span(&self) -> Span { self.span.clone() } @@ -110,6 +160,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 +190,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 30b34c2638..11dd59cdd5 100644 --- a/crates/openshell-supervisor-network/src/l7/rest.rs +++ b/crates/openshell-supervisor-network/src/l7/rest.rs @@ -1022,6 +1022,7 @@ where observer, correlation, request_span: None, + started_forwarding: false, track_request_span: live_body.is_none(), transport_failed: false, read_eof: false, @@ -1652,6 +1653,7 @@ struct ObservedUpstream<'a, U> { read_eof: bool, correlation: Option<&'a RequestCorrelation>, request_span: Option, + started_forwarding: bool, track_request_span: bool, } @@ -1704,6 +1706,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 @@ -7288,6 +7296,7 @@ mod tests { observer: Some(&observer), correlation: None, request_span: None, + started_forwarding: false, track_request_span: true, transport_failed: false, read_eof: false, diff --git a/crates/openshell-supervisor-network/src/l7/websocket.rs b/crates/openshell-supervisor-network/src/l7/websocket.rs index ba39c99961..2c60c249b9 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, 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,84 @@ 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(outcome, label); + } + result +} + +struct MessageInspection { + timer: Option, + inspection: InspectionType, + outcome: Outcome, +} + +impl MessageInspection { + 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); + } + 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 +1337,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 +1381,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 +1444,7 @@ where )) })?; apply_mask(&mut payload, mask_key); + metrics.finish(Some(metrics.outcome), ResultLabel::Success); return write_text_frame_guarded( writer, &frame.raw_header, @@ -1376,6 +1476,7 @@ where error, )) })?; + metrics.finish(Some(metrics.outcome), ResultLabel::Success); return write_masked_text_frame_guarded( writer, 0x40, @@ -1387,6 +1488,7 @@ where ) .await; } + metrics.finish(Some(metrics.outcome), ResultLabel::Success); write_masked_text_frame_guarded( writer, 0, @@ -1422,7 +1524,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 +1536,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 +1559,7 @@ fn inspect_websocket_text_message( miette!("websocket text message denied by policy"), )); } - Ok(()) + Ok(decision) } fn inspect_graphql_websocket_message( @@ -1465,7 +1568,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 +1587,7 @@ fn inspect_graphql_websocket_message( &format!("GraphQL WebSocket control message {message_type}"), None, ); - Ok(()) + Ok(Outcome::Allow) } GraphqlWebSocketMessage::Operation { message_type, @@ -1505,22 +1608,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 +1636,7 @@ fn inspect_graphql_websocket_message( miette!("websocket GraphQL message denied by policy"), )); } - Ok(()) + Ok(decision) } } } 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..476ea5e611 --- /dev/null +++ b/crates/openshell-supervisor-network/src/metrics.rs @@ -0,0 +1,498 @@ +// 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::future::Future; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, OnceLock}; +use std::time::{Duration, Instant}; + +use opentelemetry::KeyValue; +use opentelemetry::metrics::{Counter, Histogram, Meter, ObservableGauge}; + +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, +]; +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, + Request, + Message, +} + +impl Scope { + fn label(self) -> &'static str { + match self { + Self::Connection => "connection", + Self::Request => "request", + Self::Message => "message", + } + } +} + +#[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. + } + } + + 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, + Audit, + FailOpen, +} + +impl Outcome { + pub(crate) fn label(self) -> &'static str { + 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)] +pub(crate) enum ResultLabel { + Success, + Deny, + Error, + Timeout, + Cancelled, +} + +impl ResultLabel { + 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", + } + } +} + +struct Metrics { + decisions: Counter, + policy_evaluation: Histogram, + request_inspection: Histogram, + upstream_connect: Histogram, + 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.", + ), + 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.", + ), + connections, + _active_connections: active_connections, + } + } +} + +pub(crate) fn decision(scope: Scope, outcome: Outcome, inspection: InspectionType) { + 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()), + ], + ); + } +} + +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), + Inspection(Scope, InspectionType), + 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); + 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, + }; + timer.finish(result); + decision +} + +#[derive(Debug)] +pub(crate) struct Timer { + stage: Stage, + start: Option, + pause: Option, + excluded: Duration, +} + +impl Timer { + pub(crate) fn new(stage: Stage) -> Self { + Self { + stage, + start: METRICS.get().map(|_| Instant::now()), + pause: None, + excluded: Duration::ZERO, + } + } + + pub(crate) fn finish(mut self, result: ResultLabel) { + 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)) = (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 result = KeyValue::new("result", result.label()); + match self.stage { + Stage::PolicyEvaluation(scope) => { + metrics + .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 + .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}; + + #[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); + 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, + std::io::ErrorKind::TimedOut, + ] { + let error = connect(Route::Proxy, async { Err::<(), _>(kind.into()) }) + .await + .unwrap_err(); + assert_eq!(error.kind(), kind); + } + for outcome in [ + Outcome::Allow, + Outcome::Deny, + Outcome::Audit, + Outcome::FailOpen, + ] { + decision(Scope::Connection, outcome, InspectionType::Unknown); + } + 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_request_inspection_duration_seconds", + "success", + ), + ( + "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()); + 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]| { + 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 4607e9ad38..477d099e81 100644 --- a/crates/openshell-supervisor-network/src/opa.rs +++ b/crates/openshell-supervisor-network/src/opa.rs @@ -630,6 +630,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(); diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index e497ac5df9..20455b19bc 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::{self, ActiveConnection, InspectionType, Outcome, ResultLabel, 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 { + 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 { @@ -1270,6 +1272,7 @@ async fn handle_transparent_tcp_connection( .map_err(|error| miette::miette!("identity resolution task panicked: {error}"))?; if let NetworkAction::Deny { reason } = &decision.action { + metrics::decision(Scope::Connection, Outcome::Deny, InspectionType::Tcp); emit_transparent_policy_denial(&decision, workload_addr, &host, port); emit_denial( &denial_tx, @@ -1458,6 +1461,7 @@ async fn handle_transparent_tcp_connection( } )); emit_activity(&activity_tx, false, "transparent_tcp"); + metrics::decision(Scope::Connection, Outcome::Allow, InspectionType::Tcp); relay::relay_tcp(&mut client, &mut upstream, &generation_guard, &ctx).await } @@ -2394,6 +2398,7 @@ async fn deny_connect_destination( where C: TokioAsyncWrite + Unpin, { + 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, actor, @@ -2454,6 +2459,7 @@ where correlation.record_rejection(403, HttpOutcome::Denied, None); correlation.emit(event); } else { + metrics::decision(Scope::Request, Outcome::Deny, InspectionType::Http); crate::telemetry::emit_decision([event], Some(connect_span)); } @@ -2884,6 +2890,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 { .. }) { + metrics::decision(Scope::Connection, Outcome::Deny, InspectionType::Unknown); let event = NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(ActivityId::Open) .action(ActionId::Denied) @@ -3056,6 +3063,7 @@ async fn handle_mediated_connection( if refuse_connect_when_tls_unavailable(&mut client, tls_state.is_some(), effective_tls_skip) .await? { + metrics::decision(Scope::Connection, Outcome::Deny, InspectionType::Unknown); if let Some(observer) = connect_endpoint_observer.as_ref() { observer.observe(EndpointResult::TlsFailed); } @@ -3160,9 +3168,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 => { + metrics::decision(Scope::Connection, Outcome::Deny, InspectionType::Tcp); crate::l7::middleware::emit_middleware_uninspectable(&ctx, "tls-skip tunnel", true); respond( &mut client, @@ -3177,6 +3187,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", @@ -3258,6 +3269,7 @@ async fn handle_mediated_connection( else { return Ok(()); }; + metrics::decision(Scope::Connection, raw_admission, InspectionType::Tcp); relay::relay_tcp(&mut client, &mut upstream, &generation_guard, &ctx).await?; return Ok(()); } @@ -3413,6 +3425,7 @@ async fn handle_mediated_connection( if let Some(protocol_detail) = unsupported_l7_tunnel_protocol_detail(tunnel_protocol, requirement) { + metrics::decision(Scope::Connection, Outcome::Deny, InspectionType::Unknown); if requirement == InspectionRequirement::RequiredMiddleware { crate::l7::middleware::emit_middleware_uninspectable(&ctx, protocol_detail, true); } @@ -3468,6 +3481,14 @@ async fn handle_mediated_connection( else { return Ok(()); }; + let outcome = if middleware_gate + == crate::l7::middleware::UninspectableTrafficGate::BypassWithFinding + { + Outcome::FailOpen + } else { + Outcome::Allow + }; + metrics::decision(Scope::Connection, outcome, InspectionType::Tcp); relay::relay_tcp(&mut client, &mut upstream, &generation_guard, &ctx).await?; } @@ -4691,33 +4712,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. @@ -4733,21 +4751,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 { + metrics::connect( + 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 @@ -5756,6 +5783,7 @@ async fn handle_forward_proxy_inner( let matched_policy = match &decision.action { NetworkAction::Allow { matched_policy } => matched_policy.clone(), NetworkAction::Deny { reason } => { + metrics::decision(Scope::Request, Outcome::Deny, InspectionType::Http); crate::telemetry::emit_decision( [build_forward_policy_deny_ocsf_event( workload_addr, @@ -6050,6 +6078,7 @@ async fn handle_forward_proxy_inner( .await?; return Ok(()); }; + correlation.select_inspector(l7_config.config.protocol); endpoint_observer = crate::l7::EndpointObserver::begin_captured( l7_ctx.endpoint_observation_tx.as_ref(), &l7_config.config, @@ -6323,12 +6352,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 { @@ -6471,6 +6500,7 @@ async fn handle_forward_proxy_inner( } else { egress::resolve_span(&connect_span) }; + correlation.inspection_timer(metrics::Timer::pause); let resolved = validate_destination(DestinationRequest { host: &raw_host, port, @@ -6479,6 +6509,7 @@ async fn handle_forward_proxy_inner( }) .instrument(resolve_span.clone()) .await; + correlation.inspection_timer(metrics::Timer::resume); if inspected { if resolved.is_err() { egress::mark_error(&resolve_span); @@ -7036,7 +7067,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(metrics::Timer::pause); + let dial_result = metrics::connect(metrics::Route::Direct, connector.connect()) + .instrument(dial_span.clone()) + .await; + correlation.inspection_timer(metrics::Timer::resume); let mut upstream = match dial_result { Ok(s) => { if inspected { @@ -7047,6 +7082,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", @@ -7134,6 +7170,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 { + metrics::decision(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/egress.rs b/crates/openshell-supervisor-network/src/proxy/egress.rs index c12cd1ae9b..853b562607 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 openshell_isolation_interface::contract::ProcessInstance; use openshell_ocsf::Process; @@ -282,13 +283,13 @@ pub(super) fn traced_authorization( 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 b982702186..6aa874b30b 100644 --- a/crates/openshell-supervisor-network/src/proxy/relay.rs +++ b/crates/openshell-supervisor-network/src/proxy/relay.rs @@ -257,6 +257,20 @@ where C: AsyncRead + AsyncWrite + Unpin + Send, U: AsyncRead + AsyncWrite + Unpin + Send, { + use crate::metrics::{self, ActiveConnection, InspectionType, Outcome, 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); + } + match context.policy { PreparedHttpPolicy::Inspect { configs, evaluator } if configs.len() == 1 => { let generation_guard = evaluator.generation_guard().clone(); @@ -348,6 +362,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/proxy/tests/request_trace.rs b/crates/openshell-supervisor-network/src/proxy/tests/request_trace.rs index 597a5bc932..ee3c17b76f 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, } @@ -332,8 +333,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 @@ -442,6 +450,7 @@ network_policies: result }, async { + let Some(listener) = &listener else { return }; if policy_denied || credential_failure { assert!( tokio::time::timeout( @@ -482,12 +491,12 @@ network_policies: .unwrap(); result.unwrap(); let spans = capture.spans(); - let upstream_failure = matches!(outcome, Outcome::UpstreamClosed); + let upstream_closed = matches!(outcome, Outcome::UpstreamClosed); let expected = if policy_denied { 403 } else if credential_failure { 500 - } else if upstream_failure { + } else if connect_failed || upstream_closed { 502 } else { 200 @@ -496,7 +505,7 @@ network_policies: let records = capture.events.json_events(); let expected_records = if policy_denied || credential_failure { 1 - } else if upstream_failure { + } else if upstream_closed { 3 } else { 2 @@ -507,7 +516,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"] @@ -519,7 +531,7 @@ network_policies: assert!(record.get("status_id").is_none()); assert!(record.get("status_detail").is_none()); for (index, control) in records.iter().enumerate() { - if upstream_failure && index == 1 { + if upstream_closed && index == 1 { assert_eq!(control["status_detail"], "upstream_http_transport_failure"); assert_eq!(control["status_id"], 2); assert_eq!(control["http_request"]["http_method"], "GET"); @@ -530,7 +542,10 @@ network_policies: assert!(control.get("http_response").is_none()); } } - if !policy_denied && !credential_failure { + if connect_failed { + let failure = &records[1]; + assert_eq!(failure["status_id"], StatusId::Failure.as_u8()); + } else if !policy_denied && !credential_failure { let forwarded = records.last().unwrap(); assert!( forwarded["message"] @@ -544,7 +559,7 @@ network_policies: } let receipt = record["metadata"]["correlation_uid"].as_str().unwrap(); assert!(uuid::Uuid::parse_str(receipt).is_ok()); - if upstream_failure { + if upstream_closed { assert_eq!(records[1]["unmapped"]["request_id"], receipt); assert!(response.contains("Connection: close\r\n")); } @@ -653,7 +668,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" ); @@ -699,6 +716,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] { 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}"); } diff --git a/crates/openshell-supervisor/src/backend_setup/tests.rs b/crates/openshell-supervisor/src/backend_setup/tests.rs index 36c8060633..a4a41f3766 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 e3af1d51bf..2ee3082c9d 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 fe1cbec6d9..8a9f1de251 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; @@ -4758,10 +4759,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 1ef3c343a8..c8e5bc755a 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}; @@ -180,6 +180,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, @@ -546,6 +554,31 @@ 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(), + args.sandbox_id + .as_deref() + .map(openshell_supervisor::metrics::SupervisorIdentity::Sandbox), + 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); @@ -605,6 +638,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() { @@ -749,6 +785,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?); } @@ -1238,10 +1278,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/metrics.rs b/crates/openshell-supervisor/src/metrics.rs new file mode 100644 index 0000000000..15bc6f640b --- /dev/null +++ b/crates/openshell-supervisor/src/metrics.rs @@ -0,0 +1,195 @@ +// 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::config::DEFAULT_GATEWAY_NAME; +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"; + +/// 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( + endpoint: &str, + protocol: OtlpProtocol, + credentials: OtlpExportCredentials<'_>, + gateway_name: Option<&str>, + identity: Option>, + sandbox_count: impl Fn() -> u64 + Send + Sync + 'static, +) -> Result { + let config = OtlpExportConfig { + endpoint, + service_name: ServiceName::Fixed(SERVICE_NAME), + service_version: Some(openshell_core::VERSION), + resource_attributes: resource_attributes(gateway_name, identity), + }; + 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, relay::string_attribute}; + use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest; + 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 provider = start( + &path, + OtlpProtocol::HttpProtobuf, + OtlpExportCredentials { + headers: Some(&headers), + tls: None, + }, + Some("test-gateway"), + Some(SupervisorIdentity::PoolMember("member-1")), + { + 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.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")) + ); + 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 f8be6d1439..32beb4a468 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; @@ -191,6 +191,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, /// This member's cap, which also sizes its stream's message bounds. @@ -308,6 +309,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, limits: config.limits, stop_routes: Mutex::new(std::collections::BTreeSet::new()), @@ -370,6 +372,53 @@ 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), + Some(crate::metrics::SupervisorIdentity::PoolMember( + &self.pool.member_id, + )), + 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. @@ -1501,6 +1550,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())); @@ -1756,6 +1806,7 @@ mod tests { limits: test_limits(), }) .unwrap(); + assert_eq!(host.assigned_sandboxes(), 0); let routes = [ "rt-kept-0123456789", "rt-released-012345", @@ -1792,6 +1843,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. @@ -2141,6 +2193,7 @@ mod tests { nanos: 0, }), peer_endpoint: peer_endpoint.to_string(), + supervisor_metrics: Vec::new(), }, )) } diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index 57c4da5c0b..00bfe327fa 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -961,11 +961,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. @@ -1070,11 +1072,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] @@ -1082,15 +1083,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`. diff --git a/docs/observability/gateway-metrics.mdx b/docs/observability/gateway-metrics.mdx index 5f24a9e192..53ef488f39 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. +## Supervisor Metrics + +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. + +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` | 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`. 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. + +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 (scope, outcome) (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..ae837dec41 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 | 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 | @@ -23,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). @@ -68,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/proto/supervisor_host.proto b/proto/supervisor_host.proto index 3195837eff..5643ff3638 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 [(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 2b101ad1e3..c5e0f18ab8 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -1678,6 +1678,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 | 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 |