Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support http/json protocol #1585

Merged
merged 40 commits into from
Apr 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
1482d5c
Add http-json feature flag
ramgdev Feb 27, 2024
576a56d
prototype json serialization
ramgdev Feb 27, 2024
d13ab4b
fix default protocol
ramgdev Feb 27, 2024
ed4fc03
fix typo
ramgdev Feb 27, 2024
587c341
use default protocol for HttpConfig
ramgdev Feb 28, 2024
d460bda
Update opentelemetry-otlp/src/exporter/http/trace.rs
ramgdev Feb 28, 2024
da76734
address review comments
ramgdev Feb 29, 2024
aa74b9c
run pre-commit script
ramgdev Feb 29, 2024
efa8588
fix dependency
ramgdev Feb 29, 2024
e47a80f
Merge branch 'main' into otel-json
ramgdev Mar 3, 2024
04593ec
Update mod.rs
ramgdev Mar 3, 2024
277df67
unit test default endpoint
ramgdev Mar 3, 2024
5d5e06e
test default protocol
ramgdev Mar 4, 2024
359babe
Merge branch 'main' into otel-json
ramgdev Mar 12, 2024
8c9577f
Merge branch 'main' into otel-json
ramgdev Mar 12, 2024
f175980
Merge branch 'main' into otel-json
ramgdev Mar 15, 2024
f93058c
enable http-json for all signals
ramgdev Mar 18, 2024
46f92c4
Merge branch 'main' into otel-json
ramgdev Mar 18, 2024
0f1a805
fix lint
ramgdev Mar 18, 2024
6ebea63
Merge branch 'main' into otel-json
ramgdev Mar 19, 2024
e50ac0e
run precommit
ramgdev Mar 19, 2024
049e96a
Merge branch 'main' into otel-json
ramgdev Mar 20, 2024
d64bda0
Merge branch 'main' into otel-json
ramgdev Mar 24, 2024
ad8322b
add unit test
ramgdev Mar 25, 2024
e457a85
Merge branch 'main' into otel-json
ramgdev Mar 25, 2024
5222f8d
Merge branch 'main' into otel-json
ramgdev Mar 25, 2024
25b0857
Merge branch 'main' into otel-json
ramgdev Mar 29, 2024
63fb044
update changelog
ramgdev Mar 29, 2024
bcde320
Merge branch 'main' into otel-json
ramgdev Mar 29, 2024
f9abf24
address code review
ramgdev Mar 29, 2024
250fab4
remove duplicate line
ramgdev Mar 29, 2024
67552f8
Update opentelemetry-otlp/src/exporter/http/metrics.rs
ramgdev Apr 1, 2024
765ab99
Merge branch 'main' into otel-json
ramgdev Apr 5, 2024
67d6875
Merge branch 'main' into otel-json
ramgdev Apr 15, 2024
680b191
Merge branch 'main' into otel-json
lalitb Apr 16, 2024
c6d1817
Merge branch 'main' into otel-json
ramgdev Apr 20, 2024
4ed5158
move build_body to otlphttpclient
ramgdev Apr 20, 2024
ebc3cc3
allow builder to accept protocol
ramgdev Apr 20, 2024
86a89d5
Merge branch 'main' into otel-json
ramgdev Apr 21, 2024
aa2cd05
Merge branch 'main' into otel-json
TommyCpp Apr 22, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions opentelemetry-otlp/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@

### Added

- Aded `http/json` support for all signals ([#1585])

[#1585]: https://github.com/open-telemetry/opentelemetry-rust/pull/1585

- Added `DeltaTemporalitySelector` ([#1568])
- Add `webkpi-roots` features to `reqwest` and `tonic` backends

Expand Down
5 changes: 4 additions & 1 deletion opentelemetry-otlp/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ reqwest = { workspace = true, optional = true }
http = { workspace = true, optional = true }
serde = { workspace = true, features = ["derive"], optional = true }
thiserror = { workspace = true }
serde_json = { workspace = true, optional = true }

[dev-dependencies]
tokio-stream = { workspace = true, features = ["net"] }
Expand All @@ -58,7 +59,7 @@ metrics = ["opentelemetry/metrics", "opentelemetry_sdk/metrics", "opentelemetry-
logs = ["opentelemetry/logs", "opentelemetry_sdk/logs", "opentelemetry-proto/logs"]

# add ons
serialize = ["serde"]
serialize = ["serde", "serde_json"]

default = ["grpc-tonic", "trace"]

Expand All @@ -71,6 +72,8 @@ tls-webkpi-roots = ["tls", "tonic/tls-webpki-roots"]

# http binary
http-proto = ["prost", "opentelemetry-http", "opentelemetry-proto/gen-tonic-messages", "http", "trace", "metrics"]
# http json
http-json = ["serde_json", "prost", "opentelemetry-http", "opentelemetry-proto/gen-tonic-messages", "opentelemetry-proto/with-serde", "http", "trace", "metrics"]
ramgdev marked this conversation as resolved.
Show resolved Hide resolved
reqwest-blocking-client = ["reqwest/blocking", "opentelemetry-http/reqwest"]
reqwest-client = ["reqwest", "opentelemetry-http/reqwest"]
reqwest-rustls = ["reqwest", "opentelemetry-http/reqwest-rustls"]
Expand Down
2 changes: 1 addition & 1 deletion opentelemetry-otlp/examples/basic-otlp-http/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ publish = false
once_cell = { workspace = true }
opentelemetry = { path = "../../../opentelemetry" }
opentelemetry_sdk = { path = "../../../opentelemetry-sdk", features = ["rt-tokio", "metrics", "logs"] }
opentelemetry-otlp = { path = "../..", features = ["http-proto", "reqwest-client", "logs"] }
opentelemetry-otlp = { path = "../..", features = ["http-proto", "http-json", "reqwest-client", "logs"] }
opentelemetry-appender-tracing = { path = "../../../opentelemetry-appender-tracing", default-features = false}
opentelemetry-semantic-conventions = { path = "../../../opentelemetry-semantic-conventions" }

Expand Down
23 changes: 1 addition & 22 deletions opentelemetry-otlp/src/exporter/http/logs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ impl LogExporter for OtlpHttpClient {
_ => Err(LogError::Other("exporter is already shut down".into())),
})?;

let (body, content_type) = build_body(batch)?;
let (body, content_type) = self.build_logs_export_body(batch)?;
let mut request = http::Request::builder()
.method(Method::POST)
.uri(&self.collector_endpoint)
Expand Down Expand Up @@ -51,24 +51,3 @@ impl LogExporter for OtlpHttpClient {
let _ = self.client.lock().map(|mut c| c.take());
}
}

#[cfg(feature = "http-proto")]
fn build_body(logs: Vec<LogData>) -> LogResult<(Vec<u8>, &'static str)> {
use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest;
use prost::Message;

let req = ExportLogsServiceRequest {
resource_logs: logs.into_iter().map(Into::into).collect(),
};
let mut buf = vec![];
req.encode(&mut buf).map_err(crate::Error::from)?;

Ok((buf, "application/x-protobuf"))
}

#[cfg(not(feature = "http-proto"))]
fn build_body(logs: Vec<LogData>) -> LogResult<(Vec<u8>, &'static str)> {
Err(LogsError::Other(
"No http protocol configured. Enable one via `http-proto`".into(),
))
}
21 changes: 1 addition & 20 deletions opentelemetry-otlp/src/exporter/http/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ impl MetricsClient for OtlpHttpClient {
_ => Err(MetricsError::Other("exporter is already shut down".into())),
})?;

let (body, content_type) = build_body(metrics)?;
let (body, content_type) = self.build_metrics_export_body(metrics)?;
let mut request = http::Request::builder()
.method(Method::POST)
.uri(&self.collector_endpoint)
Expand All @@ -47,22 +47,3 @@ impl MetricsClient for OtlpHttpClient {
Ok(())
}
}

#[cfg(feature = "http-proto")]
fn build_body(metrics: &mut ResourceMetrics) -> Result<(Vec<u8>, &'static str)> {
use prost::Message;

let req: opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest =
(&*metrics).into();
let mut buf = vec![];
req.encode(&mut buf).map_err(crate::Error::from)?;

Ok((buf, "application/x-protobuf"))
}

#[cfg(not(feature = "http-proto"))]
fn build_body(metrics: &mut ResourceMetrics) -> Result<(Vec<u8>, &'static str)> {
Err(MetricsError::Other(
"No http protocol configured. Enable one via `http-proto`".into(),
))
}
90 changes: 85 additions & 5 deletions opentelemetry-otlp/src/exporter/http/mod.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
use super::{default_headers, default_protocol, parse_header_string};
use crate::{
ExportConfig, Protocol, OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_HEADERS,
OTEL_EXPORTER_OTLP_TIMEOUT,
};
use http::{HeaderName, HeaderValue, Uri};
use opentelemetry_http::HttpClient;
#[cfg(feature = "logs")]
use opentelemetry_sdk::export::logs::LogData;
#[cfg(feature = "trace")]
use opentelemetry_sdk::export::trace::SpanData;
#[cfg(feature = "metrics")]
use opentelemetry_sdk::metrics::data::ResourceMetrics;
use prost::Message;
use std::collections::HashMap;
use std::env;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use super::{default_headers, parse_header_string};

#[cfg(feature = "metrics")]
mod metrics;

Expand All @@ -22,7 +28,7 @@ mod logs;
mod trace;

/// Configuration of the http transport
#[cfg(feature = "http-proto")]
#[cfg(any(feature = "http-proto", feature = "http-json"))]
#[derive(Debug)]
#[cfg_attr(
all(
Expand Down Expand Up @@ -98,7 +104,7 @@ impl Default for HttpExporterBuilder {
fn default() -> Self {
HttpExporterBuilder {
exporter_config: ExportConfig {
protocol: Protocol::HttpBinary,
protocol: default_protocol(),
..ExportConfig::default()
},
http_config: HttpConfig {
Expand All @@ -110,6 +116,12 @@ impl Default for HttpExporterBuilder {
}

impl HttpExporterBuilder {
/// Specify the OTLP protocol to be used by the exporter
pub fn with_protocol(mut self, protocol: Protocol) -> Self {
self.exporter_config.protocol = protocol;
self
}

/// Assign client implementation
pub fn with_http_client<T: HttpClient + 'static>(mut self, client: T) -> Self {
self.http_config.client = Some(Arc::new(client));
Expand Down Expand Up @@ -181,7 +193,13 @@ impl HttpExporterBuilder {
add_header_from_string(&input, &mut headers);
}

Ok(OtlpHttpClient::new(http_client, endpoint, headers, timeout))
Ok(OtlpHttpClient::new(
http_client,
endpoint,
headers,
self.exporter_config.protocol,
timeout,
))
}

/// Create a log exporter with the current configuration
Expand Down Expand Up @@ -254,6 +272,7 @@ struct OtlpHttpClient {
client: Mutex<Option<Arc<dyn HttpClient>>>,
collector_endpoint: Uri,
headers: HashMap<HeaderName, HeaderValue>,
protocol: Protocol,
_timeout: Duration,
}

Expand All @@ -263,15 +282,76 @@ impl OtlpHttpClient {
client: Arc<dyn HttpClient>,
collector_endpoint: Uri,
headers: HashMap<HeaderName, HeaderValue>,
protocol: Protocol,
timeout: Duration,
) -> Self {
OtlpHttpClient {
client: Mutex::new(Some(client)),
collector_endpoint,
headers,
protocol,
_timeout: timeout,
}
}

#[cfg(feature = "trace")]
fn build_trace_export_body(
&self,
spans: Vec<SpanData>,
) -> opentelemetry::trace::TraceResult<(Vec<u8>, &'static str)> {
use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest;

let req = ExportTraceServiceRequest {
resource_spans: spans.into_iter().map(Into::into).collect(),
};
match self.protocol {
#[cfg(feature = "http-json")]
Protocol::HttpJson => match serde_json::to_string_pretty(&req) {
Ok(json) => Ok((json.into(), "application/json")),
Err(e) => Err(opentelemetry::trace::TraceError::from(e.to_string())),
},
_ => Ok((req.encode_to_vec(), "application/x-protobuf")),
}
}

#[cfg(feature = "logs")]
fn build_logs_export_body(
&self,
logs: Vec<LogData>,
) -> opentelemetry::logs::LogResult<(Vec<u8>, &'static str)> {
use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest;

let req = ExportLogsServiceRequest {
resource_logs: logs.into_iter().map(Into::into).collect(),
};
match self.protocol {
#[cfg(feature = "http-json")]
Protocol::HttpJson => match serde_json::to_string_pretty(&req) {
Ok(json) => Ok((json.into(), "application/json")),
Err(e) => Err(opentelemetry::logs::LogError::from(e.to_string())),
},
_ => Ok((req.encode_to_vec(), "application/x-protobuf")),
}
}

#[cfg(feature = "metrics")]
fn build_metrics_export_body(
&self,
metrics: &mut ResourceMetrics,
) -> opentelemetry::metrics::Result<(Vec<u8>, &'static str)> {
use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest;

let req: ExportMetricsServiceRequest = (&*metrics).into();

match self.protocol {
#[cfg(feature = "http-json")]
Protocol::HttpJson => match serde_json::to_string_pretty(&req) {
Ok(json) => Ok((json.into(), "application/json")),
Err(e) => Err(opentelemetry::metrics::MetricsError::Other(e.to_string())),
},
_ => Ok((req.encode_to_vec(), "application/x-protobuf")),
}
}
}

fn build_endpoint_uri(endpoint: &str, path: &str) -> Result<Uri, crate::Error> {
Expand Down
25 changes: 2 additions & 23 deletions opentelemetry-otlp/src/exporter/http/trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::sync::Arc;

use futures_core::future::BoxFuture;
use http::{header::CONTENT_TYPE, Method};
use opentelemetry::trace::{TraceError, TraceResult};
use opentelemetry::trace::TraceError;
use opentelemetry_sdk::export::trace::{ExportResult, SpanData, SpanExporter};

use super::OtlpHttpClient;
Expand All @@ -21,7 +21,7 @@ impl SpanExporter for OtlpHttpClient {
Err(err) => return Box::pin(std::future::ready(Err(err))),
};

let (body, content_type) = match build_body(batch) {
let (body, content_type) = match self.build_trace_export_body(batch) {
Ok(body) => body,
Err(e) => return Box::pin(std::future::ready(Err(e))),
};
Expand Down Expand Up @@ -67,24 +67,3 @@ impl SpanExporter for OtlpHttpClient {
let _ = self.client.lock().map(|mut c| c.take());
}
}

#[cfg(feature = "http-proto")]
fn build_body(spans: Vec<SpanData>) -> TraceResult<(Vec<u8>, &'static str)> {
use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest;
use prost::Message;

let req = ExportTraceServiceRequest {
resource_spans: spans.into_iter().map(Into::into).collect(),
};
let mut buf = vec![];
req.encode(&mut buf).map_err(crate::Error::from)?;

Ok((buf, "application/x-protobuf"))
}

#[cfg(not(feature = "http-proto"))]
fn build_body(spans: Vec<SpanData>) -> TraceResult<(Vec<u8>, &'static str)> {
Err(TraceError::Other(
"No http protocol configured. Enable one via `http-proto`".into(),
))
}
Loading
Loading