-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathrouter.cc
2350 lines (2068 loc) · 107 KB
/
router.cc
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
#include "source/common/router/router.h"
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include "envoy/event/dispatcher.h"
#include "envoy/event/timer.h"
#include "envoy/grpc/status.h"
#include "envoy/http/conn_pool.h"
#include "envoy/runtime/runtime.h"
#include "envoy/upstream/cluster_manager.h"
#include "envoy/upstream/health_check_host_monitor.h"
#include "envoy/upstream/upstream.h"
#include "source/common/common/assert.h"
#include "source/common/common/cleanup.h"
#include "source/common/common/empty_string.h"
#include "source/common/common/enum_to_int.h"
#include "source/common/common/scope_tracker.h"
#include "source/common/common/utility.h"
#include "source/common/config/utility.h"
#include "source/common/grpc/common.h"
#include "source/common/http/codes.h"
#include "source/common/http/header_map_impl.h"
#include "source/common/http/headers.h"
#include "source/common/http/message_impl.h"
#include "source/common/http/utility.h"
#include "source/common/network/application_protocol.h"
#include "source/common/network/socket_option_factory.h"
#include "source/common/network/transport_socket_options_impl.h"
#include "source/common/network/upstream_server_name.h"
#include "source/common/network/upstream_socket_options_filter_state.h"
#include "source/common/network/upstream_subject_alt_names.h"
#include "source/common/orca/orca_load_metrics.h"
#include "source/common/orca/orca_parser.h"
#include "source/common/router/config_impl.h"
#include "source/common/router/debug_config.h"
#include "source/common/router/retry_state_impl.h"
#include "source/common/runtime/runtime_features.h"
#include "source/common/stream_info/uint32_accessor_impl.h"
#include "source/common/tracing/http_tracer_impl.h"
namespace Envoy {
namespace Router {
namespace {
constexpr char NumInternalRedirectsFilterStateName[] = "num_internal_redirects";
uint32_t getLength(const Buffer::Instance* instance) { return instance ? instance->length() : 0; }
bool schemeIsHttp(const Http::RequestHeaderMap& downstream_headers,
OptRef<const Network::Connection> connection) {
if (Http::Utility::schemeIsHttp(downstream_headers.getSchemeValue())) {
return true;
}
if (connection.has_value() && !connection->ssl()) {
return true;
}
return false;
}
constexpr uint64_t TimeoutPrecisionFactor = 100;
} // namespace
absl::StatusOr<std::unique_ptr<FilterConfig>>
FilterConfig::create(Stats::StatName stat_prefix, Server::Configuration::FactoryContext& context,
ShadowWriterPtr&& shadow_writer,
const envoy::extensions::filters::http::router::v3::Router& config) {
absl::Status creation_status = absl::OkStatus();
auto ret = std::unique_ptr<FilterConfig>(
new FilterConfig(stat_prefix, context, std::move(shadow_writer), config, creation_status));
RETURN_IF_NOT_OK(creation_status);
return ret;
}
FilterConfig::FilterConfig(Stats::StatName stat_prefix,
Server::Configuration::FactoryContext& context,
ShadowWriterPtr&& shadow_writer,
const envoy::extensions::filters::http::router::v3::Router& config,
absl::Status& creation_status)
: FilterConfig(
context.serverFactoryContext(), stat_prefix, context.serverFactoryContext().localInfo(),
context.scope(), context.serverFactoryContext().clusterManager(),
context.serverFactoryContext().runtime(),
context.serverFactoryContext().api().randomGenerator(), std::move(shadow_writer),
PROTOBUF_GET_WRAPPED_OR_DEFAULT(config, dynamic_stats, true), config.start_child_span(),
config.suppress_envoy_headers(), config.respect_expected_rq_timeout(),
config.suppress_grpc_request_failure_code_stats(),
config.has_upstream_log_options()
? config.upstream_log_options().flush_upstream_log_on_upstream_stream()
: false,
config.strict_check_headers(), context.serverFactoryContext().api().timeSource(),
context.serverFactoryContext().httpContext(),
context.serverFactoryContext().routerContext()) {
for (const auto& upstream_log : config.upstream_log()) {
upstream_logs_.push_back(AccessLog::AccessLogFactory::fromProto(upstream_log, context));
}
if (config.has_upstream_log_options() &&
config.upstream_log_options().has_upstream_log_flush_interval()) {
upstream_log_flush_interval_ = std::chrono::milliseconds(DurationUtil::durationToMilliseconds(
config.upstream_log_options().upstream_log_flush_interval()));
}
if (!config.upstream_http_filters().empty()) {
// TODO(wbpcode): To validate the terminal filter is upstream codec filter by the proto.
Server::Configuration::ServerFactoryContext& server_factory_ctx =
context.serverFactoryContext();
std::shared_ptr<Http::UpstreamFilterConfigProviderManager> filter_config_provider_manager =
Http::FilterChainUtility::createSingletonUpstreamFilterConfigProviderManager(
server_factory_ctx);
std::string prefix = context.scope().symbolTable().toString(context.scope().prefix());
upstream_ctx_ = std::make_unique<Upstream::UpstreamFactoryContextImpl>(
server_factory_ctx, context.initManager(), context.scope());
Http::FilterChainHelper<Server::Configuration::UpstreamFactoryContext,
Server::Configuration::UpstreamHttpFilterConfigFactory>
helper(*filter_config_provider_manager, server_factory_ctx,
context.serverFactoryContext().clusterManager(), *upstream_ctx_, prefix);
SET_AND_RETURN_IF_NOT_OK(helper.processFilters(config.upstream_http_filters(),
"router upstream http", "router upstream http",
upstream_http_filter_factories_),
creation_status);
}
}
// Express percentage as [0, TimeoutPrecisionFactor] because stats do not accept floating point
// values, and getting multiple significant figures on the histogram would be nice.
uint64_t FilterUtility::percentageOfTimeout(const std::chrono::milliseconds response_time,
const std::chrono::milliseconds timeout) {
// Timeouts of 0 are considered infinite. Any portion of an infinite timeout used is still
// none of it.
if (timeout.count() == 0) {
return 0;
}
return static_cast<uint64_t>(response_time.count() * TimeoutPrecisionFactor / timeout.count());
}
void FilterUtility::setUpstreamScheme(Http::RequestHeaderMap& headers, bool downstream_ssl,
bool upstream_ssl, bool use_upstream) {
if (use_upstream) {
if (upstream_ssl) {
headers.setReferenceScheme(Http::Headers::get().SchemeValues.Https);
} else {
headers.setReferenceScheme(Http::Headers::get().SchemeValues.Http);
}
return;
}
if (Http::Utility::schemeIsValid(headers.getSchemeValue())) {
return;
}
// After all the changes in https://github.com/envoyproxy/envoy/issues/14587
// this path should only occur if a buggy filter has removed the :scheme
// header. In that case best-effort set from X-Forwarded-Proto.
absl::string_view xfp = headers.getForwardedProtoValue();
if (Http::Utility::schemeIsValid(xfp)) {
headers.setScheme(xfp);
return;
}
if (downstream_ssl) {
headers.setReferenceScheme(Http::Headers::get().SchemeValues.Https);
} else {
headers.setReferenceScheme(Http::Headers::get().SchemeValues.Http);
}
}
bool FilterUtility::shouldShadow(const ShadowPolicy& policy, Runtime::Loader& runtime,
uint64_t stable_random) {
// The policy's default value is set correctly regardless of whether there is a runtime key
// or not, thus this call is sufficient for all cases (100% if no runtime set, otherwise
// using the default value within the runtime fractional percent setting).
return runtime.snapshot().featureEnabled(policy.runtimeKey(), policy.defaultValue(),
stable_random);
}
TimeoutData FilterUtility::finalTimeout(const RouteEntry& route,
Http::RequestHeaderMap& request_headers,
bool insert_envoy_expected_request_timeout_ms,
bool grpc_request, bool per_try_timeout_hedging_enabled,
bool respect_expected_rq_timeout) {
// See if there is a user supplied timeout in a request header. If there is we take that.
// Otherwise if the request is gRPC and a maximum gRPC timeout is configured we use the timeout
// in the gRPC headers (or infinity when gRPC headers have no timeout), but cap that timeout to
// the configured maximum gRPC timeout (which may also be infinity, represented by a 0 value),
// or the default from the route config otherwise.
TimeoutData timeout;
if (!route.usingNewTimeouts()) {
if (grpc_request && route.maxGrpcTimeout()) {
const std::chrono::milliseconds max_grpc_timeout = route.maxGrpcTimeout().value();
auto header_timeout = Grpc::Common::getGrpcTimeout(request_headers);
std::chrono::milliseconds grpc_timeout =
header_timeout ? header_timeout.value() : std::chrono::milliseconds(0);
if (route.grpcTimeoutOffset()) {
// We only apply the offset if it won't result in grpc_timeout hitting 0 or below, as
// setting it to 0 means infinity and a negative timeout makes no sense.
const auto offset = *route.grpcTimeoutOffset();
if (offset < grpc_timeout) {
grpc_timeout -= offset;
}
}
// Cap gRPC timeout to the configured maximum considering that 0 means infinity.
if (max_grpc_timeout != std::chrono::milliseconds(0) &&
(grpc_timeout == std::chrono::milliseconds(0) || grpc_timeout > max_grpc_timeout)) {
grpc_timeout = max_grpc_timeout;
}
timeout.global_timeout_ = grpc_timeout;
} else {
timeout.global_timeout_ = route.timeout();
}
}
timeout.per_try_timeout_ = route.retryPolicy().perTryTimeout();
timeout.per_try_idle_timeout_ = route.retryPolicy().perTryIdleTimeout();
uint64_t header_timeout;
if (respect_expected_rq_timeout) {
// Check if there is timeout set by egress Envoy.
// If present, use that value as route timeout and don't override
// *x-envoy-expected-rq-timeout-ms* header. At this point *x-envoy-upstream-rq-timeout-ms*
// header should have been sanitized by egress Envoy.
const Http::HeaderEntry* header_expected_timeout_entry =
request_headers.EnvoyExpectedRequestTimeoutMs();
if (header_expected_timeout_entry) {
trySetGlobalTimeout(*header_expected_timeout_entry, timeout);
} else {
const Http::HeaderEntry* header_timeout_entry =
request_headers.EnvoyUpstreamRequestTimeoutMs();
if (header_timeout_entry) {
trySetGlobalTimeout(*header_timeout_entry, timeout);
request_headers.removeEnvoyUpstreamRequestTimeoutMs();
}
}
} else {
const Http::HeaderEntry* header_timeout_entry = request_headers.EnvoyUpstreamRequestTimeoutMs();
if (header_timeout_entry) {
trySetGlobalTimeout(*header_timeout_entry, timeout);
request_headers.removeEnvoyUpstreamRequestTimeoutMs();
}
}
// See if there is a per try/retry timeout. If it's >= global we just ignore it.
const absl::string_view per_try_timeout_entry =
request_headers.getEnvoyUpstreamRequestPerTryTimeoutMsValue();
if (!per_try_timeout_entry.empty()) {
if (absl::SimpleAtoi(per_try_timeout_entry, &header_timeout)) {
timeout.per_try_timeout_ = std::chrono::milliseconds(header_timeout);
}
request_headers.removeEnvoyUpstreamRequestPerTryTimeoutMs();
}
if (timeout.per_try_timeout_ >= timeout.global_timeout_ && timeout.global_timeout_.count() != 0) {
timeout.per_try_timeout_ = std::chrono::milliseconds(0);
}
setTimeoutHeaders(0, timeout, route, request_headers, insert_envoy_expected_request_timeout_ms,
grpc_request, per_try_timeout_hedging_enabled);
return timeout;
}
void FilterUtility::setTimeoutHeaders(uint64_t elapsed_time, const TimeoutData& timeout,
const RouteEntry& route,
Http::RequestHeaderMap& request_headers,
bool insert_envoy_expected_request_timeout_ms,
bool grpc_request, bool per_try_timeout_hedging_enabled) {
const uint64_t global_timeout = timeout.global_timeout_.count();
// See if there is any timeout to write in the expected timeout header.
uint64_t expected_timeout = timeout.per_try_timeout_.count();
// Use the global timeout if no per try timeout was specified or if we're
// doing hedging when there are per try timeouts. Either of these scenarios
// mean that the upstream server can use the full global timeout.
if (per_try_timeout_hedging_enabled || expected_timeout == 0) {
expected_timeout = global_timeout;
}
// If the expected timeout is 0 set no timeout, as Envoy treats 0 as infinite timeout.
if (expected_timeout > 0) {
if (global_timeout > 0) {
if (elapsed_time >= global_timeout) {
// We are out of time, but 0 would be an infinite timeout. So instead we send a 1ms timeout
// and assume the timers armed by onRequestComplete() will fire very soon.
expected_timeout = 1;
} else {
expected_timeout = std::min(expected_timeout, global_timeout - elapsed_time);
}
}
if (insert_envoy_expected_request_timeout_ms) {
request_headers.setEnvoyExpectedRequestTimeoutMs(expected_timeout);
}
// If we've configured max_grpc_timeout, override the grpc-timeout header with
// the expected timeout. This ensures that the optional per try timeout is reflected
// in grpc-timeout, ensuring that the upstream gRPC server is aware of the actual timeout.
if (grpc_request && !route.usingNewTimeouts() && route.maxGrpcTimeout()) {
Grpc::Common::toGrpcTimeout(std::chrono::milliseconds(expected_timeout), request_headers);
}
}
}
absl::optional<std::chrono::milliseconds>
FilterUtility::tryParseHeaderTimeout(const Http::HeaderEntry& header_timeout_entry) {
uint64_t header_timeout;
if (absl::SimpleAtoi(header_timeout_entry.value().getStringView(), &header_timeout)) {
return std::chrono::milliseconds(header_timeout);
}
return absl::nullopt;
}
void FilterUtility::trySetGlobalTimeout(const Http::HeaderEntry& header_timeout_entry,
TimeoutData& timeout) {
const auto timeout_ms = tryParseHeaderTimeout(header_timeout_entry);
if (timeout_ms.has_value()) {
timeout.global_timeout_ = timeout_ms.value();
}
}
FilterUtility::HedgingParams
FilterUtility::finalHedgingParams(const RouteEntry& route,
Http::RequestHeaderMap& request_headers) {
HedgingParams hedging_params;
hedging_params.hedge_on_per_try_timeout_ = route.hedgePolicy().hedgeOnPerTryTimeout();
const Http::HeaderEntry* hedge_on_per_try_timeout_entry =
request_headers.EnvoyHedgeOnPerTryTimeout();
if (hedge_on_per_try_timeout_entry) {
if (hedge_on_per_try_timeout_entry->value() == "true") {
hedging_params.hedge_on_per_try_timeout_ = true;
}
if (hedge_on_per_try_timeout_entry->value() == "false") {
hedging_params.hedge_on_per_try_timeout_ = false;
}
request_headers.removeEnvoyHedgeOnPerTryTimeout();
}
return hedging_params;
}
Filter::~Filter() {
// Upstream resources should already have been cleaned.
ASSERT(upstream_requests_.empty());
ASSERT(!retry_state_);
}
const FilterUtility::StrictHeaderChecker::HeaderCheckResult
FilterUtility::StrictHeaderChecker::checkHeader(Http::RequestHeaderMap& headers,
const Http::LowerCaseString& target_header) {
if (target_header == Http::Headers::get().EnvoyUpstreamRequestTimeoutMs) {
return isInteger(headers.EnvoyUpstreamRequestTimeoutMs());
} else if (target_header == Http::Headers::get().EnvoyUpstreamRequestPerTryTimeoutMs) {
return isInteger(headers.EnvoyUpstreamRequestPerTryTimeoutMs());
} else if (target_header == Http::Headers::get().EnvoyMaxRetries) {
return isInteger(headers.EnvoyMaxRetries());
} else if (target_header == Http::Headers::get().EnvoyRetryOn) {
return hasValidRetryFields(headers.EnvoyRetryOn(), &Router::RetryStateImpl::parseRetryOn);
} else if (target_header == Http::Headers::get().EnvoyRetryGrpcOn) {
return hasValidRetryFields(headers.EnvoyRetryGrpcOn(),
&Router::RetryStateImpl::parseRetryGrpcOn);
}
// Should only validate headers for which we have implemented a validator.
PANIC("unexpectedly reached");
}
Stats::StatName Filter::upstreamZone(Upstream::HostDescriptionOptConstRef upstream_host) {
return upstream_host ? upstream_host->localityZoneStatName() : config_->empty_stat_name_;
}
void Filter::chargeUpstreamCode(uint64_t response_status_code,
const Http::ResponseHeaderMap& response_headers,
Upstream::HostDescriptionOptConstRef upstream_host, bool dropped) {
// Passing the response_status_code explicitly is an optimization to avoid
// multiple calls to slow Http::Utility::getResponseStatus.
ASSERT(response_status_code == Http::Utility::getResponseStatus(response_headers));
if (config_->emit_dynamic_stats_ && !callbacks_->streamInfo().healthCheck()) {
const Http::HeaderEntry* upstream_canary_header = response_headers.EnvoyUpstreamCanary();
const bool is_canary = (upstream_canary_header && upstream_canary_header->value() == "true") ||
(upstream_host ? upstream_host->canary() : false);
const bool internal_request = Http::HeaderUtility::isEnvoyInternalRequest(*downstream_headers_);
Stats::StatName upstream_zone = upstreamZone(upstream_host);
Http::CodeStats::ResponseStatInfo info{
config_->scope_,
cluster_->statsScope(),
config_->empty_stat_name_,
response_status_code,
internal_request,
route_->virtualHost().statName(),
request_vcluster_ ? request_vcluster_->statName() : config_->empty_stat_name_,
route_stats_context_.has_value() ? route_stats_context_->statName()
: config_->empty_stat_name_,
config_->zone_name_,
upstream_zone,
is_canary};
Http::CodeStats& code_stats = httpContext().codeStats();
code_stats.chargeResponseStat(info, exclude_http_code_stats_);
if (alt_stat_prefix_ != nullptr) {
Http::CodeStats::ResponseStatInfo alt_info{config_->scope_,
cluster_->statsScope(),
alt_stat_prefix_->statName(),
response_status_code,
internal_request,
config_->empty_stat_name_,
config_->empty_stat_name_,
config_->empty_stat_name_,
config_->zone_name_,
upstream_zone,
is_canary};
code_stats.chargeResponseStat(alt_info, exclude_http_code_stats_);
}
if (dropped) {
cluster_->loadReportStats().upstream_rq_dropped_.inc();
}
if (upstream_host && Http::CodeUtility::is5xx(response_status_code)) {
upstream_host->stats().rq_error_.inc();
}
}
}
void Filter::chargeUpstreamCode(Http::Code code, Upstream::HostDescriptionOptConstRef upstream_host,
bool dropped) {
const uint64_t response_status_code = enumToInt(code);
const auto fake_response_headers = Http::createHeaderMap<Http::ResponseHeaderMapImpl>(
{{Http::Headers::get().Status, std::to_string(response_status_code)}});
chargeUpstreamCode(response_status_code, *fake_response_headers, upstream_host, dropped);
}
Http::FilterHeadersStatus Filter::decodeHeaders(Http::RequestHeaderMap& headers, bool end_stream) {
downstream_headers_ = &headers;
// Extract debug configuration from filter state. This is used further along to determine whether
// we should append cluster and host headers to the response, and whether to forward the request
// upstream.
const StreamInfo::FilterStateSharedPtr& filter_state = callbacks_->streamInfo().filterState();
const DebugConfig* debug_config = filter_state->getDataReadOnly<DebugConfig>(DebugConfig::key());
// TODO: Maybe add a filter API for this.
grpc_request_ = Grpc::Common::isGrpcRequestHeaders(headers);
exclude_http_code_stats_ = grpc_request_ && config_->suppress_grpc_request_failure_code_stats_;
// Only increment rq total stat if we actually decode headers here. This does not count requests
// that get handled by earlier filters.
stats_.rq_total_.inc();
// Initialize the `modify_headers` function as a no-op (so we don't have to remember to check it
// against nullptr before calling it), and feed it behavior later if/when we have cluster info
// headers to append.
std::function<void(Http::ResponseHeaderMap&)> modify_headers = [](Http::ResponseHeaderMap&) {};
// Determine if there is a route entry or a direct response for the request.
route_ = callbacks_->route();
if (!route_) {
stats_.no_route_.inc();
ENVOY_STREAM_LOG(debug, "no route match for URL '{}'", *callbacks_, headers.getPathValue());
callbacks_->streamInfo().setResponseFlag(StreamInfo::CoreResponseFlag::NoRouteFound);
callbacks_->sendLocalReply(Http::Code::NotFound, "", modify_headers, absl::nullopt,
StreamInfo::ResponseCodeDetails::get().RouteNotFound);
return Http::FilterHeadersStatus::StopIteration;
}
// Determine if there is a direct response for the request.
const auto* direct_response = route_->directResponseEntry();
if (direct_response != nullptr) {
stats_.rq_direct_response_.inc();
direct_response->rewritePathHeader(headers, !config_->suppress_envoy_headers_);
callbacks_->sendLocalReply(
direct_response->responseCode(), direct_response->responseBody(),
[this, direct_response,
&request_headers = headers](Http::ResponseHeaderMap& response_headers) -> void {
std::string new_uri;
if (request_headers.Path()) {
new_uri = direct_response->newUri(request_headers);
}
// See https://tools.ietf.org/html/rfc7231#section-7.1.2.
const auto add_location =
direct_response->responseCode() == Http::Code::Created ||
Http::CodeUtility::is3xx(enumToInt(direct_response->responseCode()));
if (!new_uri.empty() && add_location) {
response_headers.addReferenceKey(Http::Headers::get().Location, new_uri);
}
direct_response->finalizeResponseHeaders(response_headers, callbacks_->streamInfo());
},
absl::nullopt, StreamInfo::ResponseCodeDetails::get().DirectResponse);
return Http::FilterHeadersStatus::StopIteration;
}
// A route entry matches for the request.
route_entry_ = route_->routeEntry();
// If there's a route specific limit and it's smaller than general downstream
// limits, apply the new cap.
retry_shadow_buffer_limit_ =
std::min(retry_shadow_buffer_limit_, route_entry_->retryShadowBufferLimit());
if (debug_config && debug_config->append_cluster_) {
// The cluster name will be appended to any local or upstream responses from this point.
modify_headers = [this, debug_config](Http::ResponseHeaderMap& headers) {
headers.addCopy(debug_config->cluster_header_.value_or(Http::Headers::get().EnvoyCluster),
route_entry_->clusterName());
};
}
Upstream::ThreadLocalCluster* cluster =
config_->cm_.getThreadLocalCluster(route_entry_->clusterName());
if (!cluster) {
stats_.no_cluster_.inc();
ENVOY_STREAM_LOG(debug, "unknown cluster '{}'", *callbacks_, route_entry_->clusterName());
callbacks_->streamInfo().setResponseFlag(StreamInfo::CoreResponseFlag::NoClusterFound);
callbacks_->sendLocalReply(route_entry_->clusterNotFoundResponseCode(), "", modify_headers,
absl::nullopt,
StreamInfo::ResponseCodeDetails::get().ClusterNotFound);
return Http::FilterHeadersStatus::StopIteration;
}
cluster_ = cluster->info();
// Set up stat prefixes, etc.
request_vcluster_ = route_->virtualHost().virtualCluster(headers);
if (request_vcluster_ != nullptr) {
callbacks_->streamInfo().setVirtualClusterName(request_vcluster_->name());
}
route_stats_context_ = route_entry_->routeStatsContext();
ENVOY_STREAM_LOG(debug, "cluster '{}' match for URL '{}'", *callbacks_,
route_entry_->clusterName(), headers.getPathValue());
if (config_->strict_check_headers_ != nullptr) {
for (const auto& header : *config_->strict_check_headers_) {
const auto res = FilterUtility::StrictHeaderChecker::checkHeader(headers, header);
if (!res.valid_) {
callbacks_->streamInfo().setResponseFlag(
StreamInfo::CoreResponseFlag::InvalidEnvoyRequestHeaders);
const std::string body = fmt::format("invalid header '{}' with value '{}'",
std::string(res.entry_->key().getStringView()),
std::string(res.entry_->value().getStringView()));
const std::string details =
absl::StrCat(StreamInfo::ResponseCodeDetails::get().InvalidEnvoyRequestHeaders, "{",
StringUtil::replaceAllEmptySpace(res.entry_->key().getStringView()), "}");
callbacks_->sendLocalReply(Http::Code::BadRequest, body, nullptr, absl::nullopt, details);
return Http::FilterHeadersStatus::StopIteration;
}
}
}
const Http::HeaderEntry* request_alt_name = headers.EnvoyUpstreamAltStatName();
if (request_alt_name) {
alt_stat_prefix_ = std::make_unique<Stats::StatNameDynamicStorage>(
request_alt_name->value().getStringView(), config_->scope_.symbolTable());
headers.removeEnvoyUpstreamAltStatName();
}
// See if we are supposed to immediately kill some percentage of this cluster's traffic.
if (cluster_->maintenanceMode()) {
callbacks_->streamInfo().setResponseFlag(StreamInfo::CoreResponseFlag::UpstreamOverflow);
chargeUpstreamCode(Http::Code::ServiceUnavailable, {}, true);
callbacks_->sendLocalReply(
Http::Code::ServiceUnavailable, "maintenance mode",
[modify_headers, this](Http::ResponseHeaderMap& headers) {
if (!config_->suppress_envoy_headers_) {
headers.addReference(Http::Headers::get().EnvoyOverloaded,
Http::Headers::get().EnvoyOverloadedValues.True);
}
// Note: append_cluster_info does not respect suppress_envoy_headers.
modify_headers(headers);
},
absl::nullopt, StreamInfo::ResponseCodeDetails::get().MaintenanceMode);
cluster_->trafficStats()->upstream_rq_maintenance_mode_.inc();
return Http::FilterHeadersStatus::StopIteration;
}
// Support DROP_OVERLOAD config from control plane to drop certain percentage of traffic.
if (checkDropOverload(*cluster, modify_headers)) {
return Http::FilterHeadersStatus::StopIteration;
}
// Fetch a connection pool for the upstream cluster.
const auto& upstream_http_protocol_options = cluster_->upstreamHttpProtocolOptions();
if (upstream_http_protocol_options.has_value() &&
(upstream_http_protocol_options.value().auto_sni() ||
upstream_http_protocol_options.value().auto_san_validation())) {
// Default the header to Host/Authority header.
std::string header_value = route_entry_->getRequestHostValue(headers);
if (!Runtime::runtimeFeatureEnabled(
"envoy.reloadable_features.use_route_host_mutation_for_auto_sni_san")) {
header_value = std::string(headers.getHostValue());
}
// Check whether `override_auto_sni_header` is specified.
const auto override_auto_sni_header =
upstream_http_protocol_options.value().override_auto_sni_header();
if (!override_auto_sni_header.empty()) {
// Use the header value from `override_auto_sni_header` to set the SNI value.
const auto overridden_header_value = Http::HeaderUtility::getAllOfHeaderAsString(
headers, Http::LowerCaseString(override_auto_sni_header));
if (overridden_header_value.result().has_value() &&
!overridden_header_value.result().value().empty()) {
header_value = overridden_header_value.result().value();
}
}
const auto parsed_authority = Http::Utility::parseAuthority(header_value);
bool should_set_sni = !parsed_authority.is_ip_address_;
// `host_` returns a string_view so doing this should be safe.
absl::string_view sni_value = parsed_authority.host_;
if (should_set_sni && upstream_http_protocol_options.value().auto_sni() &&
!callbacks_->streamInfo().filterState()->hasDataWithName(
Network::UpstreamServerName::key())) {
callbacks_->streamInfo().filterState()->setData(
Network::UpstreamServerName::key(),
std::make_unique<Network::UpstreamServerName>(sni_value),
StreamInfo::FilterState::StateType::Mutable);
}
if (upstream_http_protocol_options.value().auto_san_validation() &&
!callbacks_->streamInfo().filterState()->hasDataWithName(
Network::UpstreamSubjectAltNames::key())) {
callbacks_->streamInfo().filterState()->setData(
Network::UpstreamSubjectAltNames::key(),
std::make_unique<Network::UpstreamSubjectAltNames>(
std::vector<std::string>{std::string(sni_value)}),
StreamInfo::FilterState::StateType::Mutable);
}
}
transport_socket_options_ = Network::TransportSocketOptionsUtility::fromFilterState(
*callbacks_->streamInfo().filterState());
if (auto downstream_connection = downstreamConnection(); downstream_connection != nullptr) {
if (auto typed_state = downstream_connection->streamInfo()
.filterState()
.getDataReadOnly<Network::UpstreamSocketOptionsFilterState>(
Network::UpstreamSocketOptionsFilterState::key());
typed_state != nullptr) {
auto downstream_options = typed_state->value();
if (!upstream_options_) {
upstream_options_ = std::make_shared<Network::Socket::Options>();
}
Network::Socket::appendOptions(upstream_options_, downstream_options);
}
}
if (upstream_options_ && callbacks_->getUpstreamSocketOptions()) {
Network::Socket::appendOptions(upstream_options_, callbacks_->getUpstreamSocketOptions());
}
callbacks_->streamInfo().downstreamTiming().setValue(
"envoy.router.host_selection_start_ms",
callbacks_->dispatcher().timeSource().monotonicTime());
auto host_selection_response = cluster->chooseHost(this);
if (!host_selection_response.cancelable ||
!Runtime::runtimeFeatureEnabled("envoy.reloadable_features.async_host_selection")) {
if (host_selection_response.cancelable) {
host_selection_response.cancelable->cancel();
}
// This branch handles the common case of synchronous host selection, as
// well as handling unsupported asynchronous host selection by treating it
// as host selection failure and calling sendNoHealthyUpstreamResponse.
return continueDecodeHeaders(cluster, headers, end_stream, modify_headers, nullptr,
std::move(host_selection_response.host),
std::string(host_selection_response.details));
}
ENVOY_STREAM_LOG(debug, "Doing asynchronous host selection\n", *callbacks_);
// Latch the cancel handle and call it in Filter::onDestroy to avoid any use-after-frees for cases
// like stream timeout.
host_selection_cancelable_ = std::move(host_selection_response.cancelable);
// Configure a callback to be called on asynchronous host selection.
on_host_selected_ = ([this, cluster, end_stream,
modify_headers](Upstream::HostConstSharedPtr&& host,
std::string host_selection_details) -> void {
// It should always be safe to call continueDecodeHeaders. In the case the
// stream had a local reply before host selection completed,
// the lookup should be canceled.
bool should_continue_decoding = false;
continueDecodeHeaders(cluster, *downstream_headers_, end_stream, modify_headers,
&should_continue_decoding, std::move(host), host_selection_details);
// continueDecodeHeaders can itself send a local reply, in which case should_continue_decoding
// should be false. If this is not the case, we can continue the filter chain due to successful
// asynchronous host selection.
if (should_continue_decoding) {
ENVOY_STREAM_LOG(debug, "Continuing stream now that host resolution is complete\n",
*callbacks_);
callbacks_->continueDecoding();
} else {
ENVOY_STREAM_LOG(debug, "Aborting stream after host resolution is complete\n", *callbacks_);
}
});
return Http::FilterHeadersStatus::StopAllIterationAndWatermark;
}
// When asynchronous host selection is complete, call the pre-configured on_host_selected_function.
void Filter::onAsyncHostSelection(Upstream::HostConstSharedPtr&& host, std::string&& details) {
ENVOY_STREAM_LOG(debug, "Completing asynchronous host selection [{}]\n", *callbacks_, details);
std::unique_ptr<Upstream::AsyncHostSelectionHandle> local_scope =
std::move(host_selection_cancelable_);
on_host_selected_(std::move(host), details);
}
Http::FilterHeadersStatus Filter::continueDecodeHeaders(
Upstream::ThreadLocalCluster* cluster, Http::RequestHeaderMap& headers, bool end_stream,
std::function<void(Http::ResponseHeaderMap&)> modify_headers, bool* should_continue_decoding,
Upstream::HostConstSharedPtr&& selected_host,
absl::optional<std::string> host_selection_details) {
const StreamInfo::FilterStateSharedPtr& filter_state = callbacks_->streamInfo().filterState();
const DebugConfig* debug_config = filter_state->getDataReadOnly<DebugConfig>(DebugConfig::key());
callbacks_->streamInfo().downstreamTiming().setValue(
"envoy.router.host_selection_end_ms", callbacks_->dispatcher().timeSource().monotonicTime());
std::unique_ptr<GenericConnPool> generic_conn_pool = createConnPool(*cluster, selected_host);
if (!generic_conn_pool) {
sendNoHealthyUpstreamResponse(host_selection_details);
return Http::FilterHeadersStatus::StopIteration;
}
Upstream::HostDescriptionConstSharedPtr host = generic_conn_pool->host();
if (debug_config && debug_config->append_upstream_host_) {
// The hostname and address will be appended to any local or upstream responses from this point,
// possibly in addition to the cluster name.
modify_headers = [modify_headers, debug_config, host](Http::ResponseHeaderMap& headers) {
modify_headers(headers);
headers.addCopy(
debug_config->hostname_header_.value_or(Http::Headers::get().EnvoyUpstreamHostname),
host->hostname());
headers.addCopy(debug_config->host_address_header_.value_or(
Http::Headers::get().EnvoyUpstreamHostAddress),
host->address()->asString());
};
}
// If we've been instructed not to forward the request upstream, send an empty local response.
if (debug_config && debug_config->do_not_forward_) {
modify_headers = [modify_headers, debug_config](Http::ResponseHeaderMap& headers) {
modify_headers(headers);
headers.addCopy(
debug_config->not_forwarded_header_.value_or(Http::Headers::get().EnvoyNotForwarded),
"true");
};
callbacks_->sendLocalReply(Http::Code::NoContent, "", modify_headers, absl::nullopt, "");
return Http::FilterHeadersStatus::StopIteration;
}
if (callbacks_->shouldLoadShed()) {
callbacks_->sendLocalReply(Http::Code::ServiceUnavailable, "envoy overloaded", nullptr,
absl::nullopt, StreamInfo::ResponseCodeDetails::get().Overload);
stats_.rq_overload_local_reply_.inc();
return Http::FilterHeadersStatus::StopIteration;
}
hedging_params_ = FilterUtility::finalHedgingParams(*route_entry_, headers);
timeout_ = FilterUtility::finalTimeout(*route_entry_, headers, !config_->suppress_envoy_headers_,
grpc_request_, hedging_params_.hedge_on_per_try_timeout_,
config_->respect_expected_rq_timeout_);
const Http::HeaderEntry* header_max_stream_duration_entry =
headers.EnvoyUpstreamStreamDurationMs();
if (header_max_stream_duration_entry) {
dynamic_max_stream_duration_ =
FilterUtility::tryParseHeaderTimeout(*header_max_stream_duration_entry);
headers.removeEnvoyUpstreamStreamDurationMs();
}
// If this header is set with any value, use an alternate response code on timeout
if (headers.EnvoyUpstreamRequestTimeoutAltResponse()) {
timeout_response_code_ = Http::Code::NoContent;
headers.removeEnvoyUpstreamRequestTimeoutAltResponse();
}
include_attempt_count_in_request_ = route_entry_->includeAttemptCountInRequest();
if (include_attempt_count_in_request_) {
headers.setEnvoyAttemptCount(attempt_count_);
}
// The router has reached a point where it is going to try to send a request upstream,
// so now modify_headers should attach x-envoy-attempt-count to the downstream response if the
// config flag is true.
if (route_entry_->includeAttemptCountInResponse()) {
modify_headers = [modify_headers, this](Http::ResponseHeaderMap& headers) {
modify_headers(headers);
// This header is added without checking for config_->suppress_envoy_headers_ to mirror what
// is done for upstream requests.
headers.setEnvoyAttemptCount(attempt_count_);
};
}
callbacks_->streamInfo().setAttemptCount(attempt_count_);
route_entry_->finalizeRequestHeaders(headers, callbacks_->streamInfo(),
!config_->suppress_envoy_headers_);
FilterUtility::setUpstreamScheme(
headers, callbacks_->streamInfo().downstreamAddressProvider().sslConnection() != nullptr,
host->transportSocketFactory().sslCtx() != nullptr,
callbacks_->streamInfo().shouldSchemeMatchUpstream());
// Ensure an http transport scheme is selected before continuing with decoding.
ASSERT(headers.Scheme());
retry_state_ = createRetryState(
route_entry_->retryPolicy(), headers, *cluster_, request_vcluster_, route_stats_context_,
config_->factory_context_, callbacks_->dispatcher(), route_entry_->priority());
// Determine which shadow policies to use. It's possible that we don't do any shadowing due to
// runtime keys. Also the method CONNECT doesn't support shadowing.
auto method = headers.getMethodValue();
if (method != Http::Headers::get().MethodValues.Connect) {
for (const auto& shadow_policy : route_entry_->shadowPolicies()) {
const auto& policy_ref = *shadow_policy;
if (FilterUtility::shouldShadow(policy_ref, config_->runtime_, callbacks_->streamId())) {
active_shadow_policies_.push_back(std::cref(policy_ref));
shadow_headers_ = Http::createHeaderMap<Http::RequestHeaderMapImpl>(*downstream_headers_);
}
}
}
ENVOY_STREAM_LOG(debug, "router decoding headers:\n{}", *callbacks_, headers);
// Hang onto the modify_headers function for later use in handling upstream responses.
modify_headers_ = modify_headers;
const bool can_send_early_data =
route_entry_->earlyDataPolicy().allowsEarlyDataForRequest(*downstream_headers_);
include_timeout_retry_header_in_request_ = route_->virtualHost().includeIsTimeoutRetryHeader();
// Set initial HTTP/3 use based on the presence of HTTP/1.1 proxy config.
// For retries etc, HTTP/3 usability may transition from true to false, but
// will never transition from false to true.
bool can_use_http3 =
!transport_socket_options_ || !transport_socket_options_->http11ProxyInfo().has_value();
UpstreamRequestPtr upstream_request = std::make_unique<UpstreamRequest>(
*this, std::move(generic_conn_pool), can_send_early_data, can_use_http3,
allow_multiplexed_upstream_half_close_ /*enable_half_close*/);
LinkedList::moveIntoList(std::move(upstream_request), upstream_requests_);
upstream_requests_.front()->acceptHeadersFromRouter(end_stream);
if (streaming_shadows_) {
// start the shadow streams.
for (const auto& shadow_policy_wrapper : active_shadow_policies_) {
const auto& shadow_policy = shadow_policy_wrapper.get();
const absl::optional<absl::string_view> shadow_cluster_name =
getShadowCluster(shadow_policy, *downstream_headers_);
if (!shadow_cluster_name.has_value()) {
continue;
}
auto shadow_headers = Http::createHeaderMap<Http::RequestHeaderMapImpl>(*shadow_headers_);
const auto options =
Http::AsyncClient::RequestOptions()
.setTimeout(timeout_.global_timeout_)
.setParentSpan(callbacks_->activeSpan())
.setChildSpanName("mirror")
.setSampled(shadow_policy.traceSampled())
.setIsShadow(true)
.setIsShadowSuffixDisabled(shadow_policy.disableShadowHostSuffixAppend())
.setBufferAccount(callbacks_->account())
// A buffer limit of 1 is set in the case that retry_shadow_buffer_limit_ == 0,
// because a buffer limit of zero on async clients is interpreted as no buffer limit.
.setBufferLimit(1 > retry_shadow_buffer_limit_ ? 1 : retry_shadow_buffer_limit_)
.setDiscardResponseBody(true)
.setFilterConfig(config_)
.setParentContext(Http::AsyncClient::ParentContext{&callbacks_->streamInfo()});
if (end_stream) {
// This is a header-only request, and can be dispatched immediately to the shadow
// without waiting.
Http::RequestMessagePtr request(new Http::RequestMessageImpl(
Http::createHeaderMap<Http::RequestHeaderMapImpl>(*shadow_headers_)));
config_->shadowWriter().shadow(std::string(shadow_cluster_name.value()), std::move(request),
options);
} else {
Http::AsyncClient::OngoingRequest* shadow_stream = config_->shadowWriter().streamingShadow(
std::string(shadow_cluster_name.value()), std::move(shadow_headers), options);
if (shadow_stream != nullptr) {
shadow_streams_.insert(shadow_stream);
shadow_stream->setDestructorCallback(
[this, shadow_stream]() { shadow_streams_.erase(shadow_stream); });
shadow_stream->setWatermarkCallbacks(watermark_callbacks_);
}
}
}
}
if (end_stream) {
onRequestComplete();
}
// If this was called due to asynchronous host selection, the caller should continueDecoding
if (should_continue_decoding) {
*should_continue_decoding = true;
}
return Http::FilterHeadersStatus::StopIteration;
}
std::unique_ptr<GenericConnPool> Filter::createConnPool(Upstream::ThreadLocalCluster& cluster,
Upstream::HostConstSharedPtr host) {
if (host == nullptr) {
return nullptr;
}
GenericConnPoolFactory* factory = nullptr;
ProtobufTypes::MessagePtr message;
if (cluster_->upstreamConfig().has_value()) {
factory = Envoy::Config::Utility::getFactory<GenericConnPoolFactory>(
cluster_->upstreamConfig().ref());
ENVOY_BUG(factory != nullptr,
fmt::format("invalid factory type '{}', failing over to default upstream",
cluster_->upstreamConfig().ref().DebugString()));
if (!cluster_->upstreamConfig()->typed_config().value().empty()) {
message = Envoy::Config::Utility::translateToFactoryConfig(
*cluster_->upstreamConfig(), config_->factory_context_.messageValidationVisitor(),
*factory);
}
}
if (!factory) {
factory = &config_->router_context_.genericConnPoolFactory();
}
if (!message) {
message = factory->createEmptyConfigProto();
}
using UpstreamProtocol = Envoy::Router::GenericConnPoolFactory::UpstreamProtocol;
UpstreamProtocol upstream_protocol = UpstreamProtocol::HTTP;
if (route_entry_->connectConfig().has_value()) {
auto method = downstream_headers_->getMethodValue();
if (Http::HeaderUtility::isConnectUdpRequest(*downstream_headers_)) {
upstream_protocol = UpstreamProtocol::UDP;
} else if (method == Http::Headers::get().MethodValues.Connect ||
(route_entry_->connectConfig()->allow_post() &&
method == Http::Headers::get().MethodValues.Post)) {
// Allow POST for proxying raw TCP if it is configured.
upstream_protocol = UpstreamProtocol::TCP;
}
}
return factory->createGenericConnPool(host, cluster, upstream_protocol, route_entry_->priority(),
callbacks_->streamInfo().protocol(), this, *message);
}
void Filter::sendNoHealthyUpstreamResponse(absl::optional<std::string> optional_details) {
callbacks_->streamInfo().setResponseFlag(StreamInfo::CoreResponseFlag::NoHealthyUpstream);
chargeUpstreamCode(Http::Code::ServiceUnavailable, {}, false);
absl::string_view details = (optional_details.has_value() && !optional_details->empty())
? absl::string_view(*optional_details)
: StreamInfo::ResponseCodeDetails::get().NoHealthyUpstream;
callbacks_->sendLocalReply(Http::Code::ServiceUnavailable, "no healthy upstream", modify_headers_,
absl::nullopt, details);
}
Http::FilterDataStatus Filter::decodeData(Buffer::Instance& data, bool end_stream) {
// upstream_requests_.size() cannot be > 1 because that only happens when a per
// try timeout occurs with hedge_on_per_try_timeout enabled but the per
// try timeout timer is not started until onRequestComplete(). It could be zero
// if the first request attempt has already failed and a retry is waiting for
// a backoff timer.
ASSERT(upstream_requests_.size() <= 1);
bool buffering = (retry_state_ && retry_state_->enabled()) ||
(!active_shadow_policies_.empty() && !streaming_shadows_) ||
(route_entry_ && route_entry_->internalRedirectPolicy().enabled());
if (buffering &&
getLength(callbacks_->decodingBuffer()) + data.length() > retry_shadow_buffer_limit_) {
ENVOY_LOG(debug,
"The request payload has at least {} bytes data which exceeds buffer limit {}. Give "
"up on the retry/shadow.",
getLength(callbacks_->decodingBuffer()) + data.length(), retry_shadow_buffer_limit_);
cluster_->trafficStats()->retry_or_shadow_abandoned_.inc();
retry_state_.reset();
buffering = false;
active_shadow_policies_.clear();
request_buffer_overflowed_ = true;
// If we had to abandon buffering and there's no request in progress, abort the request and
// clean up. This happens if the initial upstream request failed, and we are currently waiting
// for a backoff timer before starting the next upstream attempt.
if (upstream_requests_.empty()) {
cleanup();
callbacks_->sendLocalReply(
Http::Code::InsufficientStorage, "exceeded request buffer limit while retrying upstream",
modify_headers_, absl::nullopt,
StreamInfo::ResponseCodeDetails::get().RequestPayloadExceededRetryBufferLimit);
return Http::FilterDataStatus::StopIterationNoBuffer;
}
}
for (auto* shadow_stream : shadow_streams_) {
if (end_stream) {
shadow_stream->removeDestructorCallback();
shadow_stream->removeWatermarkCallbacks();
}