Skip to content

Commit

Permalink
fix(deps): update opentelemetry (#54)
Browse files Browse the repository at this point in the history
* fix(deps): update opentelemetry

* Fix compilation errors

* Update semantic convention

* Run cargo update

* Update tokio in dev-dependencies

* Use CARGO_PKG_NAME as a tracer name

* Add semconv module for easier consts management

---------

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Leonid Beschastny <[email protected]>
  • Loading branch information
renovate[bot] and lbeschastny authored Oct 7, 2024
1 parent 669e473 commit 7842267
Show file tree
Hide file tree
Showing 9 changed files with 396 additions and 484 deletions.
752 changes: 330 additions & 422 deletions Cargo.lock

Large diffs are not rendered by default.

26 changes: 12 additions & 14 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,18 @@ description = "Open Telemetry fox Axum and Tracing"

[dependencies]
http = "1.1.0"
opentelemetry = { version = "0.23", default-features = false, features = [
opentelemetry = { version = "0.25", default-features = false, features = [
"trace",
] }
tracing-opentelemetry = "0.24"
opentelemetry-http = { version = "0.12", features = ["hyper", "tokio"] }
opentelemetry-otlp = { version = "0.16", features = ["http-proto"] }
opentelemetry-zipkin = { version = "0.21", features = [], optional = true }
opentelemetry_sdk = { version = "0.23", default-features = false, features = [
tracing-opentelemetry = "0.26"
opentelemetry-http = { version = "0.25", features = ["hyper"] }
opentelemetry-otlp = { version = "0.25", features = ["http-proto"] }
opentelemetry-zipkin = { version = "0.25", features = [], optional = true }
opentelemetry_sdk = { version = "0.25", default-features = false, features = [
"rt-tokio",
] }
opentelemetry-semantic-conventions = "0.15"
tracing-opentelemetry-instrumentation-sdk = { version = "0.19", features = ["http"] }
opentelemetry-semantic-conventions = "0.25"
tracing-opentelemetry-instrumentation-sdk = { version = "0.21", features = ["http"] }
tracing = { version = "0.1.40", default-features = false }
tracing-subscriber = { version = "0.3.18", default-features = false, features = [
"env-filter",
Expand All @@ -34,27 +34,25 @@ tower = { version = "0.4", optional = true }
axum = { version = "0.7.5", optional = true }
pin-project-lite = { version = "0.2", optional = true }
futures-util = { version = "0.3", default-features = false, features = [], optional = true }
hyper = { version = "0.14", default-features = false, features = ["http1", "client"] }
hyper-v1 = { package = "hyper", version = "1.3", default-features = false, features = ["http1", "client"], optional = true }
hyper = { package = "hyper", version = "1.3", default-features = false, features = ["http1", "client"] }
http-body-util = { version = "0.1.1", optional = true }
aws-types = { version = "1", optional = true }
lambda_runtime = { version = "0", optional = true }
paste = { version = "1.0.14", optional = true }
opentelemetry-resource-detectors = "0.2.0"
hyper-util = "0.1.9"

[dev-dependencies]
assert2 = "0.3"
rstest = "0.22"
tokio = "1.35.1"
tokio = "1.38"

[features]
full = ["aws-full", "test"]
default = ["zipkin"]
zipkin = ["dep:opentelemetry-zipkin"]
future = ["dep:pin-project-lite"]
test = ["axum", "dep:serde", "dep:serde_json", "dep:opentelemetry_api", "dep:rand"]
test = ["axum", "dep:serde", "dep:serde_json", "dep:opentelemetry_api", "dep:rand", "dep:http-body-util"]
axum = ["dep:axum", "dep:tower", "dep:futures-util", "dep:pin-project-lite"]
hyper-v1 = ["dep:hyper-v1", "dep:http-body-util"]
aws-span = ["dep:aws-types", "dep:paste"]
aws-instrumentation = ["future"]
aws-lambda = ["dep:tower", "dep:lambda_runtime", "future"]
Expand Down
35 changes: 16 additions & 19 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// which is licensed under CC0 1.0 Universal
// https://github.com/davidB/tracing-opentelemetry-instrumentation-sdk/blob/d3609ac2cc699d3a24fbf89754053cc8e938e3bf/LICENSE

use opentelemetry_resource_detectors::OsResourceDetector;
use opentelemetry_sdk::{
resource::{EnvResourceDetector, ResourceDetector},
Resource,
Expand All @@ -12,21 +11,20 @@ use tracing::level_filters::LevelFilter;
use tracing_subscriber::fmt::format::FmtSpan;
use tracing_subscriber::layer::SubscriberExt;

pub use opentelemetry::{Array, Context, Key, KeyValue, StringValue, Value};
use opentelemetry::trace::TracerProvider as _;
pub use opentelemetry::{global, Array, Context, Key, KeyValue, StringValue, Value};
pub use opentelemetry_sdk::trace::TracerProvider;
pub use opentelemetry_semantic_conventions::{resource, trace as semconv};
pub use tracing_opentelemetry::OpenTelemetrySpanExt;
pub use tracing_opentelemetry::{OpenTelemetryLayer, OpenTelemetrySpanExt};

pub mod http;
pub mod middleware;
pub mod otlp;
pub mod propagation;

pub mod http;
pub mod semconv;

#[cfg(feature = "axum")]
pub use tracing_opentelemetry_instrumentation_sdk;

pub mod otlp;

#[cfg(feature = "test")]
pub mod test;

Expand Down Expand Up @@ -69,7 +67,6 @@ impl DetectResource {
fallback_service_name: self.fallback_service_name,
fallback_service_version: self.fallback_service_version,
}),
Box::new(OsResourceDetector),
Box::new(EnvResourceDetector::new()),
],
);
Expand All @@ -96,12 +93,12 @@ impl ResourceDetector for ServiceInfoDetector {
.or_else(|| util::env_var("SERVICE_NAME"))
.or_else(|| util::env_var("APP_NAME"))
.or_else(|| Some(self.fallback_service_name.to_string()))
.map(|v| KeyValue::new(resource::SERVICE_NAME, v));
.map(|v| KeyValue::new(semconv::SERVICE_NAME, v));
let service_version = util::env_var("OTEL_SERVICE_VERSION")
.or_else(|| util::env_var("SERVICE_VERSION"))
.or_else(|| util::env_var("APP_VERSION"))
.or_else(|| Some(self.fallback_service_version.to_string()))
.map(|v| KeyValue::new(resource::SERVICE_VERSION, v));
.map(|v| KeyValue::new(semconv::SERVICE_VERSION, v));
Resource::new(vec![service_name, service_version].into_iter().flatten())
}
}
Expand Down Expand Up @@ -137,16 +134,16 @@ pub fn init_tracing_with_fallbacks(

let otel_rsrc =
DetectResource::new(fallback_service_name, fallback_service_version).build();
let otel_tracer =
otlp::init_tracer(otel_rsrc, otlp::identity).expect("setup of Tracer");

let tracer_provider = otel_tracer.provider().unwrap();
let tracer_provider =
otlp::init_tracer(otel_rsrc, otlp::identity).expect("TracerProvider setup");

opentelemetry::global::set_text_map_propagator(
propagation::TextMapSplitPropagator::from_env().expect("setup of Propagation"),
global::set_tracer_provider(tracer_provider.clone());
global::set_text_map_propagator(
propagation::TextMapSplitPropagator::from_env().expect("TextMapPropagator setup"),
);

let otel_layer = tracing_opentelemetry::layer().with_tracer(otel_tracer);
let otel_layer =
OpenTelemetryLayer::new(tracer_provider.tracer(env!("CARGO_PKG_NAME")));
let subscriber = tracing_subscriber::registry()
.with(Into::<filter::TracingFilter>::into(log_level))
.with(fmt_layer!())
Expand All @@ -169,7 +166,7 @@ macro_rules! init_tracing {

#[inline]
pub fn shutdown_signal() {
std::thread::spawn(opentelemetry::global::shutdown_tracer_provider)
std::thread::spawn(global::shutdown_tracer_provider)
.join()
.unwrap();
}
12 changes: 9 additions & 3 deletions src/middleware/aws/operations/dynamodb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@ impl<'a> AwsSpanBuilder<'a> {
table_names.into_iter().map(|item| item.into()).collect();
let mut attributes = vec![
KeyValue::new(semconv::DB_SYSTEM, "dynamodb"),
KeyValue::new(semconv::DB_OPERATION, method.clone()),
KeyValue::new(semconv::DB_OPERATION_NAME, method.clone()),
KeyValue::new(semconv::legacy::DB_OPERATION, method.clone()),
];
match table_names.len() {
0 => {}
1 => {
attributes.extend([
KeyValue::new(semconv::DB_NAME, table_names[0].clone()),
KeyValue::new(semconv::DB_NAMESPACE, table_names[0].clone()),
KeyValue::new(semconv::legacy::DB_NAME, table_names[0].clone()),
Key::new(semconv::AWS_DYNAMODB_TABLE_NAMES).array(table_names),
]);
}
Expand Down Expand Up @@ -64,11 +66,15 @@ macro_rules! dynamodb_table_arn_operation {
($op: ident) => {
impl DynamodbSpanBuilder {
pub fn $op<'a>(table_arn: impl Into<StringValue>) -> AwsSpanBuilder<'a> {
let table_arn = table_arn.into();
AwsSpanBuilder::dynamodb(
stringify_camel!($op),
std::iter::empty::<StringValue>(),
)
.attribute(KeyValue::new(semconv::DB_NAME, table_arn.into()))
.attributes(vec![
KeyValue::new(semconv::DB_NAMESPACE, table_arn.clone()),
KeyValue::new(semconv::legacy::DB_NAME, table_arn),
])
}
}
};
Expand Down
6 changes: 5 additions & 1 deletion src/middleware/aws/operations/firehose.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ impl<'a> AwsSpanBuilder<'a> {
) -> Self {
let mut attributes = vec![
KeyValue::new(semconv::MESSAGING_SYSTEM, "aws_firehose"),
KeyValue::new(semconv::MESSAGING_OPERATION, operation_kind.as_str()),
KeyValue::new(semconv::MESSAGING_OPERATION_TYPE, operation_kind.as_str()),
KeyValue::new(
semconv::legacy::MESSAGING_OPERATION,
operation_kind.as_str(),
),
];
if let Some(stream_name) = stream_name {
attributes.push(KeyValue::new(
Expand Down
6 changes: 5 additions & 1 deletion src/middleware/aws/operations/sns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ impl<'a> AwsSpanBuilder<'a> {
) -> Self {
let mut attributes = vec![
KeyValue::new(semconv::MESSAGING_SYSTEM, "aws_sns"),
KeyValue::new(semconv::MESSAGING_OPERATION, operation_kind.as_str()),
KeyValue::new(semconv::MESSAGING_OPERATION_TYPE, operation_kind.as_str()),
KeyValue::new(
semconv::legacy::MESSAGING_OPERATION,
operation_kind.as_str(),
),
];
if let Some(topic_arn) = topic_arn {
attributes.push(KeyValue::new(
Expand Down
12 changes: 8 additions & 4 deletions src/otlp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@

use std::{collections::HashMap, str::FromStr};

use hyper_util::{client::legacy::Client, rt::TokioExecutor};
use opentelemetry::trace::TraceError;
use opentelemetry_http::hyper::HyperClient;
use opentelemetry_otlp::{ExportConfig, Protocol, SpanExporterBuilder};
use opentelemetry_sdk::{
trace::{Sampler, Tracer},
trace::{Sampler, TracerProvider},
Resource,
};
use std::time::Duration;
Expand All @@ -24,7 +25,10 @@ pub fn identity(
}

// see https://opentelemetry.io/docs/reference/specification/protocol/exporter/
pub fn init_tracer<F>(resource: Resource, transform: F) -> Result<Tracer, TraceError>
pub fn init_tracer<F>(
resource: Resource,
transform: F,
) -> Result<TracerProvider, TraceError>
where
F: FnOnce(
opentelemetry_otlp::OtlpTracePipeline<SpanExporterBuilder>,
Expand All @@ -43,7 +47,7 @@ where
Protocol::HttpBinary => opentelemetry_otlp::new_exporter()
.http()
.with_http_client(HyperClient::new_with_timeout(
hyper::Client::new(),
Client::builder(TokioExecutor::new()).build_http(),
export_config.timeout,
))
.with_headers(read_headers_from_env())
Expand All @@ -60,7 +64,7 @@ where
.tracing()
.with_exporter(exporter)
.with_trace_config(
opentelemetry_sdk::trace::config()
opentelemetry_sdk::trace::Config::default()
.with_resource(resource)
.with_sampler(read_sampler_from_env()),
);
Expand Down
8 changes: 8 additions & 0 deletions src/semconv.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
pub use opentelemetry_semantic_conventions::attribute::*;

#[allow(deprecated)]
pub mod legacy {
pub const DB_NAME: &str = super::DB_NAME;
pub const DB_OPERATION: &str = super::DB_OPERATION;
pub const MESSAGING_OPERATION: &str = super::MESSAGING_OPERATION;
}
23 changes: 3 additions & 20 deletions src/test/mod.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,12 @@
pub mod jaegar;

#[cfg(feature = "hyper-v1")]
use http_body_util::BodyExt;
#[cfg(not(feature = "hyper-v1"))]
use hyper::{body::Bytes, header::HeaderValue, HeaderMap, Result};
#[cfg(feature = "hyper-v1")]
use hyper_v1::{header::HeaderValue, HeaderMap, Result};
use hyper::{header::HeaderValue, HeaderMap, Result};

pub use opentelemetry_api::trace::{SpanId, TraceId};
use rand::Rng;

#[cfg(feature = "hyper-v1")]
type Response = hyper_v1::Response<hyper_v1::body::Incoming>;
#[cfg(not(feature = "hyper-v1"))]
type Response = hyper::Response<hyper::Body>;
type Response = hyper::Response<hyper::body::Incoming>;

#[derive(Debug)]
pub struct TracedResponse {
Expand All @@ -31,17 +24,7 @@ impl TracedResponse {
}
}

#[cfg(not(feature = "hyper-v1"))]
pub async fn get_bytes(&mut self) -> Result<Bytes> {
hyper::body::to_bytes(self.body_mut()).await
}

#[cfg(not(feature = "hyper-v1"))]
pub async fn into_bytes(self) -> Result<Bytes> {
hyper::body::to_bytes(self.resp).await
}

#[cfg(all(feature = "axum", feature = "hyper-v1"))]
#[cfg(feature = "axum")]
pub async fn into_axum_bytes(self) -> Result<axum::body::Bytes> {
Ok(self.resp.into_body().collect().await?.to_bytes())
}
Expand Down

0 comments on commit 7842267

Please sign in to comment.