-
Notifications
You must be signed in to change notification settings - Fork 272
/
mod.rs
3451 lines (3194 loc) · 139 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Telemetry plugin.
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use ::tracing::info_span;
use ::tracing::Span;
use axum::headers::HeaderName;
use config_new::cache::CacheInstruments;
use config_new::instruments::InstrumentsConfig;
use config_new::instruments::StaticInstrument;
use config_new::Selectors;
use dashmap::DashMap;
use futures::future::ready;
use futures::future::BoxFuture;
use futures::stream::once;
use futures::StreamExt;
use http::header;
use http::HeaderMap;
use http::HeaderValue;
use http::StatusCode;
use metrics::apollo::studio::SingleLimitsStats;
use metrics::local_type_stats::LocalTypeStatRecorder;
use multimap::MultiMap;
use once_cell::sync::OnceCell;
use opentelemetry::global::GlobalTracerProvider;
use opentelemetry::metrics::MetricsError;
use opentelemetry::propagation::text_map_propagator::FieldIter;
use opentelemetry::propagation::Extractor;
use opentelemetry::propagation::Injector;
use opentelemetry::propagation::TextMapPropagator;
use opentelemetry::sdk::propagation::TextMapCompositePropagator;
use opentelemetry::sdk::trace::Builder;
use opentelemetry::trace::SpanContext;
use opentelemetry::trace::SpanId;
use opentelemetry::trace::TraceContextExt;
use opentelemetry::trace::TraceFlags;
use opentelemetry::trace::TraceState;
use opentelemetry::trace::TracerProvider;
use opentelemetry::Key;
use opentelemetry::KeyValue;
use opentelemetry_api::trace::TraceId;
use opentelemetry_semantic_conventions::trace::HTTP_REQUEST_METHOD;
use parking_lot::Mutex;
use parking_lot::RwLock;
use rand::Rng;
use serde_json_bytes::json;
use serde_json_bytes::ByteString;
use serde_json_bytes::Map;
use serde_json_bytes::Value;
use tokio::runtime::Handle;
use tower::BoxError;
use tower::ServiceBuilder;
use tower::ServiceExt;
use uuid::Uuid;
use self::apollo::ForwardValues;
use self::apollo::LicensedOperationCountByType;
use self::apollo::OperationSubType;
use self::apollo::SingleReport;
use self::apollo_exporter::proto;
use self::apollo_exporter::Sender;
use self::config::Conf;
use self::config::TraceIdFormat;
use self::config_new::events::RouterEvents;
use self::config_new::events::SubgraphEvents;
use self::config_new::events::SupergraphEvents;
use self::config_new::instruments::Instrumented;
use self::config_new::instruments::RouterInstruments;
use self::config_new::instruments::SubgraphInstruments;
use self::config_new::spans::Spans;
use self::metrics::apollo::studio::SingleTypeStat;
use self::metrics::AttributesForwardConf;
use self::reload::reload_fmt;
pub(crate) use self::span_factory::SpanMode;
use self::tracing::apollo_telemetry::APOLLO_PRIVATE_DURATION_NS;
use self::tracing::apollo_telemetry::CLIENT_NAME_KEY;
use self::tracing::apollo_telemetry::CLIENT_VERSION_KEY;
use crate::apollo_studio_interop::ExtendedReferenceStats;
use crate::apollo_studio_interop::ReferencedEnums;
use crate::apollo_studio_interop::UsageReporting;
use crate::context::CONTAINS_GRAPHQL_ERROR;
use crate::context::OPERATION_KIND;
use crate::context::OPERATION_NAME;
use crate::graphql::ResponseVisitor;
use crate::layers::instrument::InstrumentLayer;
use crate::layers::ServiceBuilderExt;
use crate::metrics::aggregation::MeterProviderType;
use crate::metrics::filter::FilterMeterProvider;
use crate::metrics::meter_provider;
use crate::plugin::PluginInit;
use crate::plugin::PluginPrivate;
use crate::plugins::telemetry::apollo::ForwardHeaders;
use crate::plugins::telemetry::apollo_exporter::proto::reports::trace::node::Id::ResponseName;
use crate::plugins::telemetry::apollo_exporter::proto::reports::StatsContext;
use crate::plugins::telemetry::config::AttributeValue;
use crate::plugins::telemetry::config::MetricsCommon;
use crate::plugins::telemetry::config::TracingCommon;
use crate::plugins::telemetry::config_new::cost::add_cost_attributes;
use crate::plugins::telemetry::config_new::graphql::GraphQLInstruments;
use crate::plugins::telemetry::config_new::instruments::SupergraphInstruments;
use crate::plugins::telemetry::config_new::trace_id;
use crate::plugins::telemetry::config_new::DatadogId;
use crate::plugins::telemetry::consts::EXECUTION_SPAN_NAME;
use crate::plugins::telemetry::consts::OTEL_NAME;
use crate::plugins::telemetry::consts::OTEL_STATUS_CODE;
use crate::plugins::telemetry::consts::OTEL_STATUS_CODE_ERROR;
use crate::plugins::telemetry::consts::OTEL_STATUS_CODE_OK;
use crate::plugins::telemetry::consts::REQUEST_SPAN_NAME;
use crate::plugins::telemetry::consts::ROUTER_SPAN_NAME;
use crate::plugins::telemetry::dynamic_attribute::SpanDynAttribute;
use crate::plugins::telemetry::fmt_layer::create_fmt_layer;
use crate::plugins::telemetry::metrics::apollo::histogram::ListLengthHistogram;
use crate::plugins::telemetry::metrics::apollo::studio::LocalTypeStat;
use crate::plugins::telemetry::metrics::apollo::studio::SingleContextualizedStats;
use crate::plugins::telemetry::metrics::apollo::studio::SinglePathErrorStats;
use crate::plugins::telemetry::metrics::apollo::studio::SingleQueryLatencyStats;
use crate::plugins::telemetry::metrics::apollo::studio::SingleStats;
use crate::plugins::telemetry::metrics::apollo::studio::SingleStatsReport;
use crate::plugins::telemetry::metrics::prometheus::commit_prometheus;
use crate::plugins::telemetry::metrics::MetricsBuilder;
use crate::plugins::telemetry::metrics::MetricsConfigurator;
use crate::plugins::telemetry::otel::OpenTelemetrySpanExt;
use crate::plugins::telemetry::reload::metrics_layer;
use crate::plugins::telemetry::reload::OPENTELEMETRY_TRACER_HANDLE;
use crate::plugins::telemetry::tracing::apollo_telemetry::decode_ftv1_trace;
use crate::plugins::telemetry::tracing::apollo_telemetry::APOLLO_PRIVATE_OPERATION_SIGNATURE;
use crate::plugins::telemetry::tracing::TracingConfigurator;
use crate::query_planner::OperationKind;
use crate::register_private_plugin;
use crate::router_factory::Endpoint;
use crate::services::execution;
use crate::services::router;
use crate::services::subgraph;
use crate::services::subgraph::Request;
use crate::services::subgraph::Response;
use crate::services::supergraph;
use crate::services::ExecutionRequest;
use crate::services::SubgraphRequest;
use crate::services::SubgraphResponse;
use crate::services::SupergraphRequest;
use crate::services::SupergraphResponse;
use crate::spec::operation_limits::OperationLimits;
use crate::Context;
use crate::ListenAddr;
pub(crate) mod apollo;
pub(crate) mod apollo_exporter;
pub(crate) mod apollo_otlp_exporter;
pub(crate) mod config;
pub(crate) mod config_new;
pub(crate) mod consts;
pub(crate) mod dynamic_attribute;
mod endpoint;
mod fmt_layer;
pub(crate) mod formatters;
mod logging;
pub(crate) mod metrics;
/// Opentelemetry utils
pub(crate) mod otel;
mod otlp;
pub(crate) mod reload;
mod resource;
mod span_factory;
pub(crate) mod tracing;
pub(crate) mod utils;
// Tracing consts
pub(crate) const CLIENT_NAME: &str = "apollo_telemetry::client_name";
const CLIENT_VERSION: &str = "apollo_telemetry::client_version";
const SUBGRAPH_FTV1: &str = "apollo_telemetry::subgraph_ftv1";
pub(crate) const STUDIO_EXCLUDE: &str = "apollo_telemetry::studio::exclude";
pub(crate) const LOGGING_DISPLAY_HEADERS: &str = "apollo_telemetry::logging::display_headers";
pub(crate) const LOGGING_DISPLAY_BODY: &str = "apollo_telemetry::logging::display_body";
pub(crate) const SUPERGRAPH_SCHEMA_ID_CONTEXT_KEY: &str = "apollo::supergraph_schema_id";
const GLOBAL_TRACER_NAME: &str = "apollo-router";
const DEFAULT_EXPOSE_TRACE_ID_HEADER: &str = "apollo-trace-id";
static DEFAULT_EXPOSE_TRACE_ID_HEADER_NAME: HeaderName =
HeaderName::from_static(DEFAULT_EXPOSE_TRACE_ID_HEADER);
static FTV1_HEADER_NAME: HeaderName = HeaderName::from_static("apollo-federation-include-trace");
static FTV1_HEADER_VALUE: HeaderValue = HeaderValue::from_static("ftv1");
pub(crate) const APOLLO_PRIVATE_QUERY_ALIASES: Key =
Key::from_static_str("apollo_private.query.aliases");
pub(crate) const APOLLO_PRIVATE_QUERY_DEPTH: Key =
Key::from_static_str("apollo_private.query.depth");
pub(crate) const APOLLO_PRIVATE_QUERY_HEIGHT: Key =
Key::from_static_str("apollo_private.query.height");
pub(crate) const APOLLO_PRIVATE_QUERY_ROOT_FIELDS: Key =
Key::from_static_str("apollo_private.query.root_fields");
#[doc(hidden)] // Only public for integration tests
pub(crate) struct Telemetry {
pub(crate) config: Arc<config::Conf>,
supergraph_schema_id: Arc<String>,
custom_endpoints: MultiMap<ListenAddr, Endpoint>,
apollo_metrics_sender: apollo_exporter::Sender,
field_level_instrumentation_ratio: f64,
pub(crate) graphql_custom_instruments: RwLock<Arc<HashMap<String, StaticInstrument>>>,
router_custom_instruments: RwLock<Arc<HashMap<String, StaticInstrument>>>,
supergraph_custom_instruments: RwLock<Arc<HashMap<String, StaticInstrument>>>,
subgraph_custom_instruments: RwLock<Arc<HashMap<String, StaticInstrument>>>,
cache_custom_instruments: RwLock<Arc<HashMap<String, StaticInstrument>>>,
activation: Mutex<TelemetryActivation>,
}
struct TelemetryActivation {
tracer_provider: Option<opentelemetry::sdk::trace::TracerProvider>,
// We have to have separate meter providers for prometheus metrics so that they don't get zapped on router reload.
public_meter_provider: Option<FilterMeterProvider>,
public_prometheus_meter_provider: Option<FilterMeterProvider>,
private_meter_provider: Option<FilterMeterProvider>,
is_active: bool,
}
fn setup_tracing<T: TracingConfigurator>(
mut builder: Builder,
configurator: &T,
tracing_config: &TracingCommon,
spans_config: &Spans,
) -> Result<Builder, BoxError> {
if configurator.enabled() {
builder = configurator.apply(builder, tracing_config, spans_config)?;
}
Ok(builder)
}
fn setup_metrics_exporter<T: MetricsConfigurator>(
mut builder: MetricsBuilder,
configurator: &T,
metrics_common: &MetricsCommon,
) -> Result<MetricsBuilder, BoxError> {
if configurator.enabled() {
builder = configurator.apply(builder, metrics_common)?;
}
Ok(builder)
}
impl Drop for Telemetry {
fn drop(&mut self) {
let mut activation = self.activation.lock();
let metrics_providers: [Option<FilterMeterProvider>; 3] = [
activation.private_meter_provider.take(),
activation.public_meter_provider.take(),
activation.public_prometheus_meter_provider.take(),
];
let tracer_provider = activation.tracer_provider.take();
drop(activation);
TelemetryActivation::checked_meter_shutdown(metrics_providers);
if let Some(tracer_provider) = tracer_provider {
Self::checked_tracer_shutdown(tracer_provider);
}
}
}
struct BuiltinInstruments {
graphql_custom_instruments: Arc<HashMap<String, StaticInstrument>>,
router_custom_instruments: Arc<HashMap<String, StaticInstrument>>,
supergraph_custom_instruments: Arc<HashMap<String, StaticInstrument>>,
subgraph_custom_instruments: Arc<HashMap<String, StaticInstrument>>,
cache_custom_instruments: Arc<HashMap<String, StaticInstrument>>,
}
fn create_builtin_instruments(config: &InstrumentsConfig) -> BuiltinInstruments {
BuiltinInstruments {
graphql_custom_instruments: Arc::new(config.new_builtin_graphql_instruments()),
router_custom_instruments: Arc::new(config.new_builtin_router_instruments()),
supergraph_custom_instruments: Arc::new(config.new_builtin_supergraph_instruments()),
subgraph_custom_instruments: Arc::new(config.new_builtin_subgraph_instruments()),
cache_custom_instruments: Arc::new(config.new_builtin_cache_instruments()),
}
}
#[async_trait::async_trait]
impl PluginPrivate for Telemetry {
type Config = config::Conf;
async fn new(init: PluginInit<Self::Config>) -> Result<Self, BoxError> {
opentelemetry::global::set_error_handler(handle_error)
.expect("otel error handler lock poisoned, fatal");
let mut config = init.config;
config.instrumentation.spans.update_defaults();
config.instrumentation.instruments.update_defaults();
config.exporters.logging.validate()?;
if let Err(err) = config.instrumentation.validate() {
::tracing::warn!("Potential configuration error for 'instrumentation': {err}, please check the documentation on https://www.apollographql.com/docs/router/configuration/telemetry/instrumentation/events");
}
let field_level_instrumentation_ratio =
config.calculate_field_level_instrumentation_ratio()?;
let metrics_builder = Self::create_metrics_builder(&config)?;
let tracer_provider = Self::create_tracer_provider(&config)?;
if config.instrumentation.spans.mode == SpanMode::Deprecated {
::tracing::warn!("telemetry.instrumentation.spans.mode is currently set to 'deprecated', either explicitly or via defaulting. Set telemetry.instrumentation.spans.mode explicitly in your router.yaml to 'spec_compliant' for log and span attributes that follow OpenTelemetry semantic conventions. This option will be defaulted to 'spec_compliant' in a future release and eventually removed altogether");
}
let BuiltinInstruments {
graphql_custom_instruments,
router_custom_instruments,
supergraph_custom_instruments,
subgraph_custom_instruments,
cache_custom_instruments,
} = create_builtin_instruments(&config.instrumentation.instruments);
Ok(Telemetry {
custom_endpoints: metrics_builder.custom_endpoints,
apollo_metrics_sender: metrics_builder.apollo_metrics_sender,
supergraph_schema_id: init.supergraph_schema_id,
field_level_instrumentation_ratio,
activation: Mutex::new(TelemetryActivation {
tracer_provider: Some(tracer_provider),
public_meter_provider: Some(FilterMeterProvider::public(
metrics_builder.public_meter_provider_builder.build(),
)),
private_meter_provider: Some(FilterMeterProvider::private(
metrics_builder.apollo_meter_provider_builder.build(),
)),
public_prometheus_meter_provider: metrics_builder
.prometheus_meter_provider
.map(FilterMeterProvider::public),
is_active: false,
}),
graphql_custom_instruments: RwLock::new(graphql_custom_instruments),
router_custom_instruments: RwLock::new(router_custom_instruments),
supergraph_custom_instruments: RwLock::new(supergraph_custom_instruments),
subgraph_custom_instruments: RwLock::new(subgraph_custom_instruments),
cache_custom_instruments: RwLock::new(cache_custom_instruments),
config: Arc::new(config),
})
}
fn router_service(&self, service: router::BoxService) -> router::BoxService {
let config = self.config.clone();
let supergraph_schema_id = self.supergraph_schema_id.clone();
let config_later = self.config.clone();
let config_request = self.config.clone();
let span_mode = config.instrumentation.spans.mode;
let use_legacy_request_span =
matches!(config.instrumentation.spans.mode, SpanMode::Deprecated);
let field_level_instrumentation_ratio = self.field_level_instrumentation_ratio;
let metrics_sender = self.apollo_metrics_sender.clone();
let static_router_instruments = self.router_custom_instruments.read().clone();
ServiceBuilder::new()
.map_response(move |response: router::Response| {
// The current span *should* be the request span as we are outside the instrument block.
let span = Span::current();
if let Some(span_name) = span.metadata().map(|metadata| metadata.name()) {
if (use_legacy_request_span && span_name == REQUEST_SPAN_NAME)
|| (!use_legacy_request_span && span_name == ROUTER_SPAN_NAME)
{
//https://opentelemetry.io/docs/specs/otel/trace/semantic_conventions/instrumentation/graphql/
let operation_kind = response.context.get::<_, String>(OPERATION_KIND);
let operation_name = response.context.get::<_, String>(OPERATION_NAME);
if let Ok(Some(operation_kind)) = &operation_kind {
span.record("graphql.operation.type", operation_kind);
}
if let Ok(Some(operation_name)) = &operation_name {
span.record("graphql.operation.name", operation_name);
}
match (&operation_kind, &operation_name) {
(Ok(Some(kind)), Ok(Some(name))) => span.set_span_dyn_attribute(
OTEL_NAME.into(),
format!("{kind} {name}").into(),
),
(Ok(Some(kind)), _) => {
span.set_span_dyn_attribute(OTEL_NAME.into(), kind.clone().into())
}
_ => span.set_span_dyn_attribute(
OTEL_NAME.into(),
"GraphQL Operation".into(),
),
};
}
}
response
})
.option_layer(use_legacy_request_span.then(move || {
InstrumentLayer::new(move |request: &router::Request| {
span_mode.create_router(&request.router_request)
})
}))
.map_future_with_request_data(
move |request: &router::Request| {
let _ = request.context.insert(
SUPERGRAPH_SCHEMA_ID_CONTEXT_KEY,
supergraph_schema_id.clone(),
);
if !use_legacy_request_span {
let span = Span::current();
span.set_span_dyn_attribute(
HTTP_REQUEST_METHOD,
request.router_request.method().to_string().into(),
);
}
let client_name = request
.router_request
.headers()
.get(&config_request.apollo.client_name_header)
.and_then(|h| h.to_str().ok());
let client_version = request
.router_request
.headers()
.get(&config_request.apollo.client_version_header)
.and_then(|h| h.to_str().ok());
if let Some(name) = client_name {
let _ = request.context.insert(CLIENT_NAME, name.to_owned());
}
if let Some(version) = client_version {
let _ = request.context.insert(CLIENT_VERSION, version.to_owned());
}
let mut custom_attributes = config_request
.instrumentation
.spans
.router
.attributes
.on_request(request);
custom_attributes.extend([
KeyValue::new(CLIENT_NAME_KEY, client_name.unwrap_or("").to_string()),
KeyValue::new(CLIENT_VERSION_KEY, client_version.unwrap_or("").to_string()),
KeyValue::new(
Key::from_static_str("apollo_private.http.request_headers"),
filter_headers(
request.router_request.headers(),
&config_request.apollo.send_headers,
),
),
]);
let custom_instruments: RouterInstruments = config_request
.instrumentation
.instruments
.new_router_instruments(static_router_instruments.clone());
custom_instruments.on_request(request);
let custom_events: RouterEvents =
config_request.instrumentation.events.new_router_events();
custom_events.on_request(request);
(
custom_attributes,
custom_instruments,
custom_events,
request.context.clone(),
)
},
move |(custom_attributes, custom_instruments, custom_events, ctx): (
Vec<KeyValue>,
RouterInstruments,
RouterEvents,
Context,
),
fut| {
let start = Instant::now();
let config = config_later.clone();
let sender = metrics_sender.clone();
Self::plugin_metrics(&config);
async move {
let span = Span::current();
span.set_span_dyn_attributes(custom_attributes);
let response: Result<router::Response, BoxError> = fut.await;
span.record(
APOLLO_PRIVATE_DURATION_NS,
start.elapsed().as_nanos() as i64,
);
let expose_trace_id = &config.exporters.tracing.response_trace_id;
if let Ok(response) = &response {
span.set_span_dyn_attributes(
config
.instrumentation
.spans
.router
.attributes
.on_response(response),
);
custom_instruments.on_response(response);
custom_events.on_response(response);
if expose_trace_id.enabled {
let header_name = expose_trace_id
.header_name
.as_ref()
.unwrap_or(&DEFAULT_EXPOSE_TRACE_ID_HEADER_NAME);
let mut headers: HashMap<String, Vec<String>> =
HashMap::with_capacity(1);
if let Some(value) = response.response.headers().get(header_name) {
headers.insert(
header_name.to_string(),
vec![value.to_str().unwrap_or_default().to_string()],
);
let response_headers =
serde_json::to_string(&headers).unwrap_or_default();
span.record(
"apollo_private.http.response_headers",
&response_headers,
);
}
}
if response.context.extensions().with_lock(|lock| {
lock.get::<Arc<UsageReporting>>()
.map(|u| {
u.stats_report_key == "## GraphQLValidationFailure\n"
|| u.stats_report_key == "## GraphQLParseFailure\n"
|| u.stats_report_key
== "## GraphQLUnknownOperationName\n"
})
.unwrap_or(false)
}) {
Self::update_apollo_metrics(
&response.context,
field_level_instrumentation_ratio,
sender,
true,
start.elapsed(),
// the query is invalid, we did not parse the operation kind
OperationKind::Query,
None,
Default::default(),
);
}
if response.response.status() >= StatusCode::BAD_REQUEST {
span.record(OTEL_STATUS_CODE, OTEL_STATUS_CODE_ERROR);
} else {
span.record(OTEL_STATUS_CODE, OTEL_STATUS_CODE_OK);
}
} else if let Err(err) = &response {
span.record(OTEL_STATUS_CODE, OTEL_STATUS_CODE_ERROR);
span.set_span_dyn_attributes(
config
.instrumentation
.spans
.router
.attributes
.on_error(err, &ctx),
);
custom_instruments.on_error(err, &ctx);
custom_events.on_error(err, &ctx);
}
response
}
},
)
.service(service)
.boxed()
}
fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService {
let metrics_sender = self.apollo_metrics_sender.clone();
let span_mode = self.config.instrumentation.spans.mode;
let config = self.config.clone();
let config_instrument = self.config.clone();
let config_map_res_first = config.clone();
let config_map_res = config.clone();
let field_level_instrumentation_ratio = self.field_level_instrumentation_ratio;
let static_supergraph_instruments = self.supergraph_custom_instruments.read().clone();
let static_graphql_instruments = self.graphql_custom_instruments.read().clone();
ServiceBuilder::new()
.instrument(move |supergraph_req: &SupergraphRequest| span_mode.create_supergraph(
&config_instrument.apollo,
supergraph_req,
field_level_instrumentation_ratio,
))
.map_response(move |mut resp: SupergraphResponse| {
let config = config_map_res_first.clone();
if let Some(usage_reporting) = resp.context.extensions().with_lock(|lock| lock.get::<Arc<UsageReporting>>().cloned()) {
// Record the operation signature on the router span
Span::current().record(
APOLLO_PRIVATE_OPERATION_SIGNATURE.as_str(),
usage_reporting.stats_report_key.as_str(),
);
}
// To expose trace_id or not
let expose_trace_id_header = config.exporters.tracing.response_trace_id.enabled.then(|| {
config.exporters.tracing.response_trace_id
.header_name
.clone()
.unwrap_or_else(|| DEFAULT_EXPOSE_TRACE_ID_HEADER_NAME.clone())
});
// Append the trace ID with the right format, based on the config
let format_id = |trace_id: TraceId| {
let id = match config.exporters.tracing.response_trace_id.format {
TraceIdFormat::Hexadecimal | TraceIdFormat::OpenTelemetry => format!("{:032x}", trace_id),
TraceIdFormat::Decimal => format!("{}", u128::from_be_bytes(trace_id.to_bytes())),
TraceIdFormat::Datadog => trace_id.to_datadog(),
TraceIdFormat::Uuid => Uuid::from_bytes(trace_id.to_bytes()).to_string(),
};
HeaderValue::from_str(&id).ok()
};
if let (Some(header_name), Some(trace_id)) = (
expose_trace_id_header,
trace_id().and_then(format_id),
) {
resp.response.headers_mut().append(header_name, trace_id);
}
if resp.context.contains_key(LOGGING_DISPLAY_HEADERS) {
let sorted_headers = resp
.response
.headers()
.iter()
.map(|(k, v)| (k.as_str(), v))
.collect::<BTreeMap<_, _>>();
::tracing::info!(http.response.headers = ?sorted_headers, "Supergraph response headers");
}
let display_body = resp.context.contains_key(LOGGING_DISPLAY_BODY);
resp.map_stream(move |gql_response| {
if display_body {
::tracing::info!(http.response.body = ?gql_response, "Supergraph GraphQL response");
}
gql_response
})
})
.map_future_with_request_data(
move |req: &SupergraphRequest| {
let custom_attributes = config.instrumentation.spans.supergraph.attributes.on_request(req);
Self::populate_context(config.clone(), field_level_instrumentation_ratio, req);
let custom_instruments = config
.instrumentation
.instruments
.new_supergraph_instruments(static_supergraph_instruments.clone());
custom_instruments.on_request(req);
let custom_graphql_instruments: GraphQLInstruments = config
.instrumentation
.instruments.new_graphql_instruments(static_graphql_instruments.clone());
custom_graphql_instruments.on_request(req);
let supergraph_events = config.instrumentation.events.new_supergraph_events();
supergraph_events.on_request(req);
(req.context.clone(), custom_instruments, custom_attributes, supergraph_events, custom_graphql_instruments)
},
move |(ctx, custom_instruments, mut custom_attributes, supergraph_events, custom_graphql_instruments): (Context, SupergraphInstruments, Vec<KeyValue>, SupergraphEvents, GraphQLInstruments), fut| {
let config = config_map_res.clone();
let sender = metrics_sender.clone();
let start = Instant::now();
async move {
let span = Span::current();
let mut result: Result<SupergraphResponse, BoxError> = fut.await;
add_query_attributes(&ctx, &mut custom_attributes);
add_cost_attributes(&ctx, &mut custom_attributes);
span.set_span_dyn_attributes(custom_attributes);
match &result {
Ok(resp) => {
span.set_span_dyn_attributes(config.instrumentation.spans.supergraph.attributes.on_response(resp));
custom_instruments.on_response(resp);
supergraph_events.on_response(resp);
custom_graphql_instruments.on_response(resp);
},
Err(err) => {
span.set_span_dyn_attributes(config.instrumentation.spans.supergraph.attributes.on_error(err, &ctx));
custom_instruments.on_error(err, &ctx);
supergraph_events.on_error(err, &ctx);
custom_graphql_instruments.on_error(err, &ctx);
},
}
result = Self::update_otel_metrics(
config.clone(),
ctx.clone(),
result,
start.elapsed(),
custom_instruments,
supergraph_events,
custom_graphql_instruments,
)
.await;
Self::update_metrics_on_response_events(
&ctx, config, field_level_instrumentation_ratio, sender, start, result,
)
}
},
)
.service(service)
.boxed()
}
fn execution_service(&self, service: execution::BoxService) -> execution::BoxService {
ServiceBuilder::new()
.instrument(move |req: &ExecutionRequest| {
let operation_kind = req.query_plan.query.operation.kind();
match operation_kind {
OperationKind::Subscription => info_span!(
EXECUTION_SPAN_NAME,
"otel.kind" = "INTERNAL",
"graphql.operation.type" = operation_kind.as_apollo_operation_type(),
"apollo_private.operation.subtype" =
OperationSubType::SubscriptionRequest.as_str(),
),
_ => info_span!(
EXECUTION_SPAN_NAME,
"otel.kind" = "INTERNAL",
"graphql.operation.type" = operation_kind.as_apollo_operation_type(),
),
}
})
.service(service)
.boxed()
}
fn subgraph_service(&self, name: &str, service: subgraph::BoxService) -> subgraph::BoxService {
let config = self.config.clone();
let span_mode = self.config.instrumentation.spans.mode;
let conf = self.config.clone();
let subgraph_attribute = KeyValue::new("subgraph", name.to_string());
let subgraph_metrics_conf_req = self.create_subgraph_metrics_conf(name);
let subgraph_metrics_conf_resp = subgraph_metrics_conf_req.clone();
let subgraph_name = ByteString::from(name);
let name = name.to_owned();
let static_subgraph_instruments = self.subgraph_custom_instruments.read().clone();
let static_cache_instruments = self.cache_custom_instruments.read().clone();
ServiceBuilder::new()
.instrument(move |req: &SubgraphRequest| span_mode.create_subgraph(name.as_str(), req))
.map_request(move |req: SubgraphRequest| request_ftv1(req))
.map_response(move |resp| store_ftv1(&subgraph_name, resp))
.map_future_with_request_data(
move |sub_request: &SubgraphRequest| {
Self::store_subgraph_request_attributes(
subgraph_metrics_conf_req.as_ref(),
sub_request,
);
let custom_attributes = config
.instrumentation
.spans
.subgraph
.attributes
.on_request(sub_request);
let custom_instruments = config
.instrumentation
.instruments
.new_subgraph_instruments(static_subgraph_instruments.clone());
custom_instruments.on_request(sub_request);
let custom_events = config.instrumentation.events.new_subgraph_events();
custom_events.on_request(sub_request);
let custom_cache_instruments: CacheInstruments = config
.instrumentation
.instruments
.new_cache_instruments(static_cache_instruments.clone());
custom_cache_instruments.on_request(sub_request);
(
sub_request.context.clone(),
custom_instruments,
custom_attributes,
custom_events,
custom_cache_instruments,
)
},
move |(
context,
custom_instruments,
custom_attributes,
custom_events,
custom_cache_instruments,
): (
Context,
SubgraphInstruments,
Vec<KeyValue>,
SubgraphEvents,
CacheInstruments,
),
f: BoxFuture<'static, Result<SubgraphResponse, BoxError>>| {
let subgraph_attribute = subgraph_attribute.clone();
let subgraph_metrics_conf = subgraph_metrics_conf_resp.clone();
let conf = conf.clone();
// Using Instant because it is guaranteed to be monotonically increasing.
let now = Instant::now();
async move {
let span = Span::current();
span.set_span_dyn_attributes(custom_attributes);
let result: Result<SubgraphResponse, BoxError> = f.await;
match &result {
Ok(resp) => {
if resp.response.status() >= StatusCode::BAD_REQUEST {
span.record(OTEL_STATUS_CODE, OTEL_STATUS_CODE_ERROR);
} else {
span.record(OTEL_STATUS_CODE, OTEL_STATUS_CODE_OK);
}
span.set_span_dyn_attributes(
conf.instrumentation
.spans
.subgraph
.attributes
.on_response(resp),
);
custom_cache_instruments.on_response(resp);
custom_instruments.on_response(resp);
custom_events.on_response(resp);
}
Err(err) => {
span.record(OTEL_STATUS_CODE, OTEL_STATUS_CODE_ERROR);
span.set_span_dyn_attributes(
conf.instrumentation
.spans
.subgraph
.attributes
.on_error(err, &context),
);
custom_cache_instruments.on_error(err, &context);
custom_instruments.on_error(err, &context);
custom_events.on_error(err, &context);
}
}
Self::store_subgraph_response_attributes(
&context,
subgraph_attribute,
subgraph_metrics_conf.as_ref(),
now,
&result,
);
result
}
},
)
.service(service)
.boxed()
}
fn web_endpoints(&self) -> MultiMap<ListenAddr, Endpoint> {
self.custom_endpoints.clone()
}
fn activate(&self) {
let mut activation = self.activation.lock();
if activation.is_active {
return;
}
// Only apply things if we were executing in the context of a vanilla the Apollo executable.
// Users that are rolling their own routers will need to set up telemetry themselves.
if let Some(hot_tracer) = OPENTELEMETRY_TRACER_HANDLE.get() {
// The reason that this has to happen here is that we are interacting with global state.
// If we do this logic during plugin init then if a subsequent plugin fails to init then we
// will already have set the new tracer provider and we will be in an inconsistent state.
// activate is infallible, so if we get here we know the new pipeline is ready to go.
let tracer_provider = activation
.tracer_provider
.take()
.expect("must have new tracer_provider");
let tracer = tracer_provider.versioned_tracer(
GLOBAL_TRACER_NAME,
Some(env!("CARGO_PKG_VERSION")),
None::<String>,
None,
);
hot_tracer.reload(tracer);
let last_provider = opentelemetry::global::set_tracer_provider(tracer_provider);
Self::checked_global_tracer_shutdown(last_provider);
let propagator = Self::create_propagator(&self.config);
opentelemetry::global::set_text_map_propagator(propagator);
}
activation.reload_metrics();
let BuiltinInstruments {
graphql_custom_instruments,
router_custom_instruments,
supergraph_custom_instruments,
subgraph_custom_instruments,
cache_custom_instruments,
} = create_builtin_instruments(&self.config.instrumentation.instruments);
*self.graphql_custom_instruments.write() = graphql_custom_instruments;
*self.router_custom_instruments.write() = router_custom_instruments;
*self.supergraph_custom_instruments.write() = supergraph_custom_instruments;
*self.subgraph_custom_instruments.write() = subgraph_custom_instruments;
*self.cache_custom_instruments.write() = cache_custom_instruments;
reload_fmt(create_fmt_layer(&self.config));
activation.is_active = true;
}
}
impl Telemetry {
fn create_propagator(config: &config::Conf) -> TextMapCompositePropagator {
let propagation = &config.exporters.tracing.propagation;
let tracing = &config.exporters.tracing;
let mut propagators: Vec<Box<dyn TextMapPropagator + Send + Sync + 'static>> = Vec::new();
// TLDR the jaeger propagator MUST BE the first one because the version of opentelemetry_jaeger is buggy.
// It overrides the current span context with an empty one if it doesn't find the corresponding headers.
// Waiting for the >=0.16.1 release
if propagation.jaeger || tracing.jaeger.enabled() {
propagators.push(Box::<opentelemetry_jaeger::Propagator>::default());
}
if propagation.baggage {
propagators.push(Box::<opentelemetry::sdk::propagation::BaggagePropagator>::default());
}
if propagation.trace_context || tracing.otlp.enabled {
propagators
.push(Box::<opentelemetry::sdk::propagation::TraceContextPropagator>::default());
}
if propagation.zipkin || tracing.zipkin.enabled {
propagators.push(Box::<opentelemetry_zipkin::Propagator>::default());
}
if propagation.datadog || tracing.datadog.enabled() {
propagators.push(Box::<tracing::datadog_exporter::DatadogPropagator>::default());
}
if propagation.aws_xray {
propagators.push(Box::<opentelemetry_aws::XrayPropagator>::default());
}
// This propagator MUST come last because the user is trying to override the default behavior of the
// other propagators.
if let Some(from_request_header) = &propagation.request.header_name {
propagators.push(Box::new(CustomTraceIdPropagator::new(
from_request_header.to_string(),
propagation.request.format.clone(),
)));
}
TextMapCompositePropagator::new(propagators)
}
fn create_tracer_provider(
config: &config::Conf,
) -> Result<opentelemetry::sdk::trace::TracerProvider, BoxError> {
let tracing_config = &config.exporters.tracing;
let spans_config = &config.instrumentation.spans;
let common = &tracing_config.common;
let mut builder =
opentelemetry::sdk::trace::TracerProvider::builder().with_config((common).into());
builder = setup_tracing(builder, &tracing_config.jaeger, common, spans_config)?;
builder = setup_tracing(builder, &tracing_config.zipkin, common, spans_config)?;
builder = setup_tracing(builder, &tracing_config.datadog, common, spans_config)?;
builder = setup_tracing(builder, &tracing_config.otlp, common, spans_config)?;
builder = setup_tracing(builder, &config.apollo, common, spans_config)?;
let tracer_provider = builder.build();
Ok(tracer_provider)
}
fn create_metrics_builder(config: &config::Conf) -> Result<MetricsBuilder, BoxError> {
let metrics_config = &config.exporters.metrics;
let metrics_common_config = &metrics_config.common;
let mut builder = MetricsBuilder::new(config);
builder = setup_metrics_exporter(builder, &config.apollo, metrics_common_config)?;
builder =
setup_metrics_exporter(builder, &metrics_config.prometheus, metrics_common_config)?;
builder = setup_metrics_exporter(builder, &metrics_config.otlp, metrics_common_config)?;
Ok(builder)
}
fn filter_variables_values(
variables: &Map<ByteString, Value>,
forward_rules: &ForwardValues,
) -> String {
let nb_var = variables.len();
#[allow(clippy::mutable_key_type)] // False positive lint
let variables = variables
.iter()
.map(|(name, value)| {
if match &forward_rules {
ForwardValues::None => false,
ForwardValues::All => true,
ForwardValues::Only(only) => only.contains(&name.as_str().to_string()),
ForwardValues::Except(except) => !except.contains(&name.as_str().to_string()),
} {
(
name,
serde_json::to_string(value).unwrap_or_else(|_| "<unknown>".to_string()),
)
} else {
(name, "".to_string())
}