saluki_components/common/otlp/
proxy.rs1use std::sync::{
8 atomic::{AtomicBool, Ordering},
9 Arc,
10};
11use std::time::Duration;
12
13use axum::extract::Request;
14use axum::response::{IntoResponse as _, Response};
15use axum::routing::{any, MethodRouter};
16use http::header::{self, HeaderMap, HeaderValue};
17use http::uri::Uri;
18use http::Version;
19use metrics::Counter;
20use rustls::RootCertStore;
21use saluki_error::{generic_error, ErrorContext as _, GenericError};
22use saluki_io::net::client::http::{HttpClient, HttpProtocol};
23use saluki_metrics::MetricsBuilder;
24use tonic::Status;
25use tracing::{debug, info, warn};
26
27use super::Signal;
28use crate::common::proxy::{strip_hop_by_hop_headers, upstream_uri, Destination, ForwardError, UpstreamClient};
29
30const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
32
33#[derive(Clone, Debug, Eq, PartialEq)]
35pub struct OtlpProxyDestinations {
36 pub grpc: Option<Destination>,
40
41 pub http: Option<Destination>,
45}
46
47pub(crate) struct OtlpProxy {
49 grpc: Option<Arc<Upstream>>,
50 http: Option<Arc<Upstream>>,
51 metrics_builder: MetricsBuilder,
52}
53
54impl OtlpProxy {
55 pub(crate) fn new(
61 destinations: &OtlpProxyDestinations, metrics_builder: MetricsBuilder,
62 ) -> Result<Self, GenericError> {
63 Self::with_connect_timeout(destinations, metrics_builder, CONNECT_TIMEOUT)
64 }
65
66 fn with_connect_timeout(
67 destinations: &OtlpProxyDestinations, metrics_builder: MetricsBuilder, connect_timeout: Duration,
68 ) -> Result<Self, GenericError> {
69 let upstream = |protocol, destination: &Option<Destination>| {
70 destination
71 .as_ref()
72 .map(|destination| Upstream::new(protocol, destination, connect_timeout).map(Arc::new))
73 .transpose()
74 };
75 Ok(Self {
76 grpc: upstream(Protocol::Grpc, &destinations.grpc)?,
77 http: upstream(Protocol::Http, &destinations.http)?,
78 metrics_builder,
79 })
80 }
81
82 pub(crate) fn grpc_service(&self, signal: Signal) -> Result<MethodRouter, GenericError> {
88 let upstream = self.grpc.as_ref().ok_or_else(|| {
89 generic_error!("An OTLP signal is proxied over gRPC, but the OTLP proxy has no gRPC destination.")
90 })?;
91 Ok(SignalProxy::new(Arc::clone(upstream), signal, &self.metrics_builder).into_service())
92 }
93
94 pub(crate) fn http_service(&self, signal: Signal) -> Result<MethodRouter, GenericError> {
100 let upstream = self.http.as_ref().ok_or_else(|| {
101 generic_error!("An OTLP signal is proxied over HTTP, but the OTLP proxy has no HTTP destination.")
102 })?;
103 Ok(SignalProxy::new(Arc::clone(upstream), signal, &self.metrics_builder).into_service())
104 }
105}
106
107#[derive(Clone, Copy, Debug, Eq, PartialEq)]
109enum Protocol {
110 Grpc,
111 Http,
112}
113
114impl Protocol {
115 const fn as_str(self) -> &'static str {
116 match self {
117 Self::Grpc => "grpc",
118 Self::Http => "http",
119 }
120 }
121
122 fn error_response(self, error: ForwardError) -> Response {
124 match (self, error) {
125 (Self::Grpc, ForwardError::Unreachable) => {
127 Status::unavailable("The upstream OTLP receiver is unreachable.").into_http()
128 }
129 (Self::Grpc, _) => Status::internal("The request couldn't be forwarded.").into_http(),
130 (Self::Http, error) => error.into_response(),
131 }
132 }
133}
134
135struct Upstream {
137 protocol: Protocol,
138 client: UpstreamClient,
139
140 base_uri: Uri,
143
144 destination: Destination,
145
146 unreachable: AtomicBool,
148}
149
150impl Upstream {
151 fn new(protocol: Protocol, destination: &Destination, connect_timeout: Duration) -> Result<Self, GenericError> {
152 let builder = HttpClient::builder()
153 .with_tls_config(|builder| builder.with_root_cert_store(RootCertStore::empty()))
155 .with_http_protocol(match protocol {
156 Protocol::Grpc => HttpProtocol::Http2,
157 Protocol::Http => HttpProtocol::Http1,
158 })
159 .with_connect_timeout(connect_timeout)
160 .without_request_timeout()
162 .with_hyper_config(|builder| {
165 builder.retry_canceled_requests(true);
166 });
167
168 let base_uri = destination
169 .base_uri()
170 .with_error_context(|| format!("Invalid OTLP proxy destination {destination:?}."))?;
171 let builder = destination.configure_client(builder);
172
173 Ok(Self {
174 protocol,
175 client: UpstreamClient::new(builder.build()?),
176 base_uri,
177 destination: destination.clone(),
178 unreachable: AtomicBool::new(false),
179 })
180 }
181
182 async fn forward(&self, signal: Signal, request: Request) -> Result<Response, ForwardError> {
188 let (mut parts, body) = request.into_parts();
189
190 parts.uri = match upstream_uri(&self.base_uri, parts.uri.path_and_query()) {
191 Ok(uri) => uri,
192 Err(e) => {
193 debug!(error = %e, signal = signal.as_str(), "Failed to build the upstream URI of an OTLP request.");
194 return Err(ForwardError::InvalidUri);
195 }
196 };
197
198 let keep_te = self.protocol == Protocol::Grpc && accepts_trailers(&parts.headers);
200 strip_hop_by_hop_headers(&mut parts.headers);
201 if keep_te {
202 parts.headers.insert(header::TE, HeaderValue::from_static("trailers"));
203 }
204 parts.headers.remove(header::HOST);
206 parts.version = match self.protocol {
208 Protocol::Grpc => Version::HTTP_2,
209 Protocol::Http => Version::HTTP_11,
210 };
211
212 match self.client.send(http::Request::from_parts(parts, body)).await {
213 Ok(response) => {
214 if self.unreachable.swap(false, Ordering::Relaxed) {
215 info!(
216 destination = ?self.destination,
217 protocol = self.protocol.as_str(),
218 "The upstream OTLP receiver is reachable again."
219 );
220 }
221 Ok(response)
222 }
223 Err(e) => {
224 if self.unreachable.swap(true, Ordering::Relaxed) {
225 debug!(
226 error = %e,
227 destination = ?self.destination,
228 protocol = self.protocol.as_str(),
229 signal = signal.as_str(),
230 "Failed to forward an OTLP request to the upstream receiver."
231 );
232 } else {
233 warn!(
234 error = %e,
235 destination = ?self.destination,
236 protocol = self.protocol.as_str(),
237 signal = signal.as_str(),
238 "Failed to forward an OTLP request to the upstream receiver. Proxied requests fail until it is reachable again."
239 );
240 }
241 Err(ForwardError::Unreachable)
242 }
243 }
244 }
245}
246
247fn accepts_trailers(headers: &HeaderMap) -> bool {
249 headers
250 .get_all(header::TE)
251 .iter()
252 .filter_map(|value| value.to_str().ok())
253 .flat_map(|value| value.split(','))
254 .any(|coding| coding.trim().eq_ignore_ascii_case("trailers"))
255}
256
257#[derive(Clone)]
259struct SignalProxy {
260 upstream: Arc<Upstream>,
261 signal: Signal,
262
263 requests_relayed: Counter,
265
266 requests_failed: Counter,
268}
269
270impl SignalProxy {
271 fn new(upstream: Arc<Upstream>, signal: Signal, metrics_builder: &MetricsBuilder) -> Self {
272 let tags = [("signal", signal.as_str()), ("protocol", upstream.protocol.as_str())];
273 Self {
274 requests_relayed: metrics_builder.register_counter_with_tags("component_requests_relayed_total", tags),
275 requests_failed: metrics_builder.register_counter_with_tags("component_requests_failed_total", tags),
276 upstream,
277 signal,
278 }
279 }
280
281 fn into_service(self) -> MethodRouter {
282 any(move |request: Request| {
283 let proxy = self.clone();
284 async move { proxy.forward(request).await }
285 })
286 }
287
288 async fn forward(&self, request: Request) -> Response {
289 match self.upstream.forward(self.signal, request).await {
290 Ok(response) => {
291 self.requests_relayed.increment(1);
292 response
293 }
294 Err(error) => {
295 self.requests_failed.increment(1);
296 self.upstream.protocol.error_response(error)
297 }
298 }
299 }
300}
301
302#[cfg(test)]
303mod tests;