Skip to main content

rig_otel/
aws.rs

1//! Export to Amazon CloudWatch's OTLP endpoints, signed with AWS SigV4.
2//!
3//! CloudWatch takes OTLP over HTTP at `https://xray.REGION.amazonaws.com/v1/traces`
4//! and `https://monitoring.REGION.amazonaws.com/v1/metrics`, each request
5//! signed with SigV4 for its service (`xray`, `monitoring`). The credentials
6//! come from the standard AWS chain: the IAM role of an AgentCore runtime, an
7//! ECS task, an EC2 instance or a Lambda function, or a local profile.
8//! Traces need CloudWatch Transaction Search enabled on the account.
9
10use std::time::{Duration, SystemTime};
11
12use aws_credential_types::provider::{ProvideCredentials, SharedCredentialsProvider};
13use aws_sigv4::http_request::{SignableBody, SignableRequest, SigningSettings, sign};
14use aws_sigv4::sign::v4;
15use bytes::Bytes;
16use opentelemetry_http::{HttpClient, HttpError, Request, Response};
17use opentelemetry_otlp::{WithExportConfig, WithHttpConfig};
18
19use crate::{InitError, TelemetryBuilder};
20
21/// Why the CloudWatch exporters could not be set up.
22#[derive(Debug, thiserror::Error)]
23#[non_exhaustive]
24pub enum AwsError {
25    /// No region in the environment or the profile.
26    #[error("no AWS region: set AWS_REGION or a profile region")]
27    NoRegion,
28    /// No credential provider in the environment.
29    #[error("no AWS credentials provider")]
30    NoCredentials,
31    /// The tokio runtime the exporters sign requests on is missing.
32    #[error("set up CloudWatch export from inside a tokio runtime")]
33    NoRuntime,
34    /// The HTTP client for the endpoints could not be built. The cause is
35    /// logged with `tracing` at the failure.
36    #[error("could not build the HTTP client for CloudWatch")]
37    HttpClient,
38}
39
40/// The OTel spec default for OTLP exporter timeouts.
41const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
42/// Bounds the TCP and TLS connect, so a black-holed host fails fast.
43const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
44
45/// The export timeout for one signal, as the plain OTLP exporters read it:
46/// `signal_var` (`OTEL_EXPORTER_OTLP_TRACES_TIMEOUT` or
47/// `OTEL_EXPORTER_OTLP_METRICS_TIMEOUT`), then `OTEL_EXPORTER_OTLP_TIMEOUT`,
48/// in milliseconds. Zero and unparsable values are ignored; then 10 s.
49fn export_timeout(signal_var: &str) -> Duration {
50    export_timeout_from(signal_var, |var| std::env::var(var).ok())
51}
52
53fn export_timeout_from(signal_var: &str, lookup: impl Fn(&str) -> Option<String>) -> Duration {
54    [signal_var, "OTEL_EXPORTER_OTLP_TIMEOUT"]
55        .into_iter()
56        .find_map(|var| lookup(var)?.trim().parse::<u64>().ok().filter(|ms| *ms > 0))
57        .map_or(DEFAULT_TIMEOUT, Duration::from_millis)
58}
59
60/// An OTLP HTTP client that signs each request with SigV4 for the service
61/// its host names (`xray.…` → `xray`).
62#[derive(Debug, Clone)]
63struct SigV4Client {
64    http: reqwest::Client,
65    credentials: SharedCredentialsProvider,
66    region: String,
67    runtime: tokio::runtime::Handle,
68}
69
70impl SigV4Client {
71    async fn sign_and_send(&self, request: Request<Bytes>) -> Result<Response<Bytes>, HttpError> {
72        let (parts, body) = request.into_parts();
73        let service = parts
74            .uri
75            .host()
76            .and_then(|host| host.split('.').next())
77            .unwrap_or("xray")
78            .to_owned();
79        let credentials = self.credentials.provide_credentials().await?;
80        let identity = credentials.into();
81        let params = v4::SigningParams::builder()
82            .identity(&identity)
83            .region(&self.region)
84            .name(&service)
85            .time(SystemTime::now())
86            .settings(SigningSettings::default())
87            .build()?
88            .into();
89        let uri = parts.uri.to_string();
90        let headers: Vec<(&str, &str)> = parts
91            .headers
92            .iter()
93            .filter_map(|(name, value)| Some((name.as_str(), value.to_str().ok()?)))
94            .collect();
95        let signable = SignableRequest::new(
96            parts.method.as_str(),
97            &uri,
98            headers.into_iter(),
99            SignableBody::Bytes(&body),
100        )?;
101        let (instructions, _signature) = sign(signable, &params)?.into_parts();
102        let mut signed = http::Request::from_parts(parts, body);
103        instructions.apply_to_request_http1x(&mut signed);
104
105        let response = self.http.execute(signed.try_into()?).await?;
106        let mut builder = http::Response::builder().status(response.status());
107        for (name, value) in response.headers() {
108            builder = builder.header(name, value);
109        }
110        Ok(builder.body(response.bytes().await?)?)
111    }
112}
113
114#[async_trait::async_trait]
115impl HttpClient for SigV4Client {
116    async fn send_bytes(&self, request: Request<Bytes>) -> Result<Response<Bytes>, HttpError> {
117        // The batch exporters call this from their own threads, outside any
118        // tokio runtime, and the AWS credential providers need one.
119        if tokio::runtime::Handle::try_current().is_ok() {
120            self.sign_and_send(request).await
121        } else {
122            self.runtime.block_on(self.sign_and_send(request))
123        }
124    }
125}
126
127impl TelemetryBuilder {
128    /// Export to Amazon CloudWatch's OTLP endpoints in the configured region,
129    /// signed with SigV4 from the standard AWS credential chain. Call it from
130    /// inside a tokio runtime.
131    ///
132    /// For AgentCore Observability, also set `OTEL_RESOURCE_ATTRIBUTES` to
133    /// `service.name=…,aws.log.group.names=/aws/bedrock-agentcore/runtimes/RUNTIME_ID`,
134    /// as AWS documents.
135    pub async fn aws_cloudwatch(self) -> Result<Self, InitError> {
136        let runtime = tokio::runtime::Handle::try_current()
137            .map_err(|_| InitError::Aws(AwsError::NoRuntime))?;
138        let config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
139        let region = config
140            .region()
141            .ok_or(InitError::Aws(AwsError::NoRegion))?
142            .to_string();
143        let credentials = config
144            .credentials_provider()
145            .ok_or(InitError::Aws(AwsError::NoCredentials))?;
146        let spans_url = format!("https://xray.{region}.amazonaws.com/v1/traces");
147        let metrics_url = format!("https://monitoring.{region}.amazonaws.com/v1/metrics");
148        self.cloudwatch_exporters(
149            runtime,
150            region,
151            credentials,
152            (
153                spans_url,
154                export_timeout("OTEL_EXPORTER_OTLP_TRACES_TIMEOUT"),
155            ),
156            (
157                metrics_url,
158                export_timeout("OTEL_EXPORTER_OTLP_METRICS_TIMEOUT"),
159            ),
160        )
161    }
162
163    fn cloudwatch_exporters(
164        self,
165        runtime: tokio::runtime::Handle,
166        region: String,
167        credentials: SharedCredentialsProvider,
168        spans: (String, Duration),
169        metrics: (String, Duration),
170    ) -> Result<Self, InitError> {
171        let client = |timeout: Duration| -> Result<SigV4Client, InitError> {
172            let http = reqwest::Client::builder()
173                .connect_timeout(CONNECT_TIMEOUT)
174                .timeout(timeout)
175                .build()
176                .map_err(|error| {
177                    tracing::error!(%error, "building the CloudWatch HTTP client failed");
178                    InitError::Aws(AwsError::HttpClient)
179                })?;
180            Ok(SigV4Client {
181                http,
182                credentials: credentials.clone(),
183                region: region.clone(),
184                runtime: runtime.clone(),
185            })
186        };
187        let spans_exporter = opentelemetry_otlp::SpanExporter::builder()
188            .with_http()
189            .with_http_client(client(spans.1)?)
190            .with_protocol(opentelemetry_otlp::Protocol::HttpBinary)
191            .with_endpoint(spans.0)
192            .build()
193            .map_err(InitError::SpanExporter)?;
194        let metrics_exporter = opentelemetry_otlp::MetricExporter::builder()
195            .with_http()
196            .with_http_client(client(metrics.1)?)
197            .with_protocol(opentelemetry_otlp::Protocol::HttpBinary)
198            .with_endpoint(metrics.0)
199            .build()
200            .map_err(InitError::MetricExporter)?;
201        Ok(self
202            .span_exporter(spans_exporter)
203            .metric_exporter(metrics_exporter))
204    }
205}
206
207#[cfg(test)]
208mod tests {
209    use std::time::{Duration, Instant};
210
211    use aws_credential_types::Credentials;
212    use aws_credential_types::provider::SharedCredentialsProvider;
213    use tokio::net::TcpListener;
214
215    use super::{DEFAULT_TIMEOUT, TelemetryBuilder, export_timeout_from};
216
217    /// As `tests/integration`: a global default, so exporter-thread warnings
218    /// do not depend on which test ran first.
219    fn pin_global_default() {
220        static PIN: std::sync::Once = std::sync::Once::new();
221        PIN.call_once(|| {
222            let _ = tracing::subscriber::set_global_default(
223                tracing::subscriber::NoSubscriber::default(),
224            );
225        });
226    }
227    use crate::Telemetry;
228
229    fn env(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<String> {
230        move |var| {
231            pairs
232                .iter()
233                .find(|(name, _)| *name == var)
234                .map(|(_, value)| (*value).to_owned())
235        }
236    }
237
238    #[test]
239    fn the_signal_variable_beats_the_general_one() {
240        let lookup = env(&[
241            ("OTEL_EXPORTER_OTLP_TRACES_TIMEOUT", "1500"),
242            ("OTEL_EXPORTER_OTLP_TIMEOUT", "3000"),
243        ]);
244        assert_eq!(
245            export_timeout_from("OTEL_EXPORTER_OTLP_TRACES_TIMEOUT", &lookup),
246            Duration::from_millis(1500)
247        );
248        assert_eq!(
249            export_timeout_from("OTEL_EXPORTER_OTLP_METRICS_TIMEOUT", &lookup),
250            Duration::from_millis(3000)
251        );
252    }
253
254    #[test]
255    fn zero_and_junk_fall_through_to_the_general_variable_then_the_default() {
256        let lookup = env(&[
257            ("OTEL_EXPORTER_OTLP_TRACES_TIMEOUT", "0"),
258            ("OTEL_EXPORTER_OTLP_TIMEOUT", "0"),
259        ]);
260        assert_eq!(
261            export_timeout_from("OTEL_EXPORTER_OTLP_TRACES_TIMEOUT", &lookup),
262            DEFAULT_TIMEOUT
263        );
264        let lookup = env(&[
265            ("OTEL_EXPORTER_OTLP_TRACES_TIMEOUT", "0"),
266            ("OTEL_EXPORTER_OTLP_TIMEOUT", "2000"),
267        ]);
268        assert_eq!(
269            export_timeout_from("OTEL_EXPORTER_OTLP_TRACES_TIMEOUT", &lookup),
270            Duration::from_millis(2000)
271        );
272        let lookup = env(&[("OTEL_EXPORTER_OTLP_TRACES_TIMEOUT", "soon")]);
273        assert_eq!(
274            export_timeout_from("OTEL_EXPORTER_OTLP_TRACES_TIMEOUT", &lookup),
275            DEFAULT_TIMEOUT
276        );
277        assert_eq!(
278            export_timeout_from("OTEL_EXPORTER_OTLP_TRACES_TIMEOUT", env(&[])),
279            DEFAULT_TIMEOUT
280        );
281    }
282
283    /// Exporting to a server that accepts and never answers fails within the
284    /// timeout, and flush and shutdown return.
285    #[tokio::test(flavor = "multi_thread")]
286    async fn a_hung_cloudwatch_endpoint_fails_the_export_within_its_timeout() {
287        pin_global_default();
288        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
289        let base = format!("http://{}", listener.local_addr().unwrap());
290        let accept = tokio::spawn(async move {
291            let mut held = Vec::new();
292            while let Ok((socket, _)) = listener.accept().await {
293                held.push(socket);
294            }
295        });
296
297        let credentials = Credentials::new("AKIDEXAMPLE", "dummy-secret", None, None, "test");
298        let timeout = Duration::from_millis(300);
299        let url = |path: &str| format!("{base}{path}");
300        let (telemetry, subscriber): (Telemetry, _) = TelemetryBuilder::default()
301            .service_name("rig-otel-test")
302            .cloudwatch_exporters(
303                tokio::runtime::Handle::current(),
304                "us-east-1".to_owned(),
305                SharedCredentialsProvider::new(credentials),
306                (url("/v1/traces"), timeout),
307                (url("/v1/metrics"), timeout),
308            )
309            .unwrap()
310            .logs(false)
311            .build()
312            .unwrap();
313        let guard = tracing::subscriber::set_default(subscriber);
314        tracing::info_span!("hung export").in_scope(|| ());
315        drop(guard);
316
317        let outer = Duration::from_secs(10);
318        let (telemetry, flushed, flush_took) = tokio::time::timeout(
319            outer,
320            tokio::task::spawn_blocking(move || {
321                let started = Instant::now();
322                let flushed = telemetry.force_flush();
323                (telemetry, flushed, started.elapsed())
324            }),
325        )
326        .await
327        .expect("flush did not return within 10 s")
328        .unwrap();
329        assert!(flushed.is_err(), "flush against a hung endpoint must fail");
330        assert!(
331            flush_took < Duration::from_secs(2),
332            "flush took {flush_took:?}"
333        );
334
335        let shutdown_took = tokio::time::timeout(
336            outer,
337            tokio::task::spawn_blocking(move || {
338                let started = Instant::now();
339                drop(telemetry);
340                started.elapsed()
341            }),
342        )
343        .await
344        .expect("shutdown did not return within 10 s")
345        .unwrap();
346        assert!(
347            shutdown_took < Duration::from_secs(2),
348            "shutdown took {shutdown_took:?}"
349        );
350        accept.abort();
351    }
352}