#![allow(unexpected_cfgs)]
use std::collections::HashMap;
use opentelemetry_otlp::{SpanExporter, WithExportConfig, WithHttpConfig, WithTonicConfig};
use super::{Compression, Protocol, TracingConfig};
use crate::core::{Error, Result, TlsConfig};
pub fn otlp_exporter(config: &TracingConfig) -> Result<SpanExporter> {
let built = match config.protocol {
Protocol::HttpProtobuf => {
let mut b = SpanExporter::builder()
.with_http()
.with_timeout(config.batch.export_timeout)
.with_headers(
config
.headers
.clone()
.into_iter()
.collect::<HashMap<_, _>>(),
);
if let Some(endpoint) = &config.endpoint {
b = b.with_endpoint(http_traces_endpoint(endpoint));
}
if let Some(tls) = config.tls.as_ref().filter(|t| **t != TlsConfig::default()) {
let client = crate::core::transport::apply_tls(reqwest::Client::builder(), tls)?
.timeout(config.batch.export_timeout)
.build()
.map_err(|e| {
Error::config("cannot build the OTLP HTTP client").with_source(e)
})?;
b = b.with_http_client(client);
}
if config.compression == Compression::Gzip {
b = b.with_compression(opentelemetry_otlp::Compression::Gzip);
}
b.build()
}
Protocol::Grpc => {
use opentelemetry_otlp::tonic_types::metadata::MetadataMap;
let mut headers = http::HeaderMap::new();
for (k, v) in &config.headers {
let name = http::header::HeaderName::from_bytes(k.as_bytes())
.map_err(|_| Error::config(format!("invalid tracing header name {k:?}")))?;
let value = http::header::HeaderValue::from_str(v).map_err(|_| {
Error::config(format!("invalid value for tracing header {k:?}"))
})?;
headers.insert(name, value);
}
let metadata = MetadataMap::from_headers(headers);
let mut b = SpanExporter::builder()
.with_tonic()
.with_timeout(config.batch.export_timeout)
.with_metadata(metadata);
if let Some(endpoint) = &config.endpoint {
b = b.with_endpoint(endpoint.clone());
}
if let Some(tls) = config.tls.as_ref().filter(|t| **t != TlsConfig::default()) {
b = grpc_tls(b, config.endpoint.as_deref(), tls)?;
}
if config.compression == Compression::Gzip {
b = b.with_compression(opentelemetry_otlp::Compression::Gzip);
}
b.build()
}
Protocol::Native => {
return Err(Error::config(
"tracing protocol \"native\" needs the service package's exporter",
))
}
};
built.map_err(|e| Error::config(format!("cannot build the OTLP exporter: {e}")))
}
pub fn http_traces_endpoint(endpoint: &str) -> String {
match url::Url::parse(endpoint) {
Ok(url) if url.query().is_none() => {
let base = endpoint.trim_end_matches('/');
if url.path().trim_matches('/').is_empty() {
format!("{base}/v1/traces")
} else {
base.to_string()
}
}
_ => endpoint.to_string(),
}
}
fn is_https(endpoint: &str) -> bool {
endpoint
.get(..8)
.is_some_and(|p| p.eq_ignore_ascii_case("https://"))
}
pub type OtlpGrpcExporterBuilder =
opentelemetry_otlp::SpanExporterBuilder<opentelemetry_otlp::TonicExporterBuilderSet>;
pub fn apply_grpc_tls(
builder: OtlpGrpcExporterBuilder,
endpoint: Option<&str>,
tls: &TlsConfig,
) -> Result<OtlpGrpcExporterBuilder> {
grpc_tls(builder, endpoint, tls)
}
#[cfg(feature = "otlp-tls")]
fn grpc_tls(
b: OtlpGrpcExporterBuilder,
endpoint: Option<&str>,
tls: &TlsConfig,
) -> Result<OtlpGrpcExporterBuilder> {
use opentelemetry_otlp::tonic_types::transport::{Certificate, ClientTlsConfig, Identity};
if tls.insecure_skip_verify && endpoint.is_some_and(is_https) {
return Err(Error::config(
"tracing: insecure_skip_verify is not supported for grpc; use http/protobuf",
));
}
let read = |path: &std::path::Path, what: &str| {
std::fs::read(path).map_err(|e| {
Error::config(format!("{what} file {} cannot be read", path.display())).with_source(e)
})
};
let mut cfg = ClientTlsConfig::new().with_enabled_roots();
let mut ca = Vec::new();
if let Some(path) = &tls.ca_cert_path {
ca.extend(read(path, "CA certificate")?);
ca.push(b'\n');
}
if let Some(pem) = &tls.ca_cert_pem {
ca.extend_from_slice(pem.as_bytes());
}
if !ca.is_empty() {
cfg = cfg.ca_certificate(Certificate::from_pem(ca));
}
if let (Some(cert), Some(key)) = (&tls.client_cert_path, &tls.client_key_path) {
cfg = cfg.identity(Identity::from_pem(
read(cert, "client certificate")?,
read(key, "client key")?,
));
}
Ok(b.with_tls_config(cfg))
}
#[cfg(not(feature = "otlp-tls"))]
fn grpc_tls(
b: OtlpGrpcExporterBuilder,
endpoint: Option<&str>,
tls: &TlsConfig,
) -> Result<OtlpGrpcExporterBuilder> {
let _ = tls;
if !endpoint.is_some_and(is_https) {
return Ok(b); }
Err(Error::config(
"tracing: TLS settings for grpc need the crate feature \"otlp-tls\"; use http/protobuf",
))
}