-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
conn_manager_impl.cc
2324 lines (2050 loc) · 102 KB
/
conn_manager_impl.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/http/conn_manager_impl.h"
#include <chrono>
#include <cstdint>
#include <functional>
#include <iterator>
#include <list>
#include <memory>
#include <string>
#include <vector>
#include "envoy/buffer/buffer.h"
#include "envoy/common/time.h"
#include "envoy/event/dispatcher.h"
#include "envoy/event/scaled_range_timer_manager.h"
#include "envoy/extensions/filters/network/http_connection_manager/v3/http_connection_manager.pb.h"
#include "envoy/http/header_map.h"
#include "envoy/http/header_validator_errors.h"
#include "envoy/network/drain_decision.h"
#include "envoy/router/router.h"
#include "envoy/ssl/connection.h"
#include "envoy/stats/scope.h"
#include "envoy/stream_info/filter_state.h"
#include "envoy/stream_info/stream_info.h"
#include "envoy/tracing/tracer.h"
#include "envoy/type/v3/percent.pb.h"
#include "source/common/buffer/buffer_impl.h"
#include "source/common/common/assert.h"
#include "source/common/common/empty_string.h"
#include "source/common/common/enum_to_int.h"
#include "source/common/common/fmt.h"
#include "source/common/common/perf_tracing.h"
#include "source/common/common/scope_tracker.h"
#include "source/common/common/utility.h"
#include "source/common/http/codes.h"
#include "source/common/http/conn_manager_utility.h"
#include "source/common/http/exception.h"
#include "source/common/http/header_map_impl.h"
#include "source/common/http/header_utility.h"
#include "source/common/http/headers.h"
#include "source/common/http/http1/codec_impl.h"
#include "source/common/http/http2/codec_impl.h"
#include "source/common/http/path_utility.h"
#include "source/common/http/status.h"
#include "source/common/http/utility.h"
#include "source/common/network/utility.h"
#include "source/common/router/config_impl.h"
#include "source/common/runtime/runtime_features.h"
#include "source/common/stats/timespan_impl.h"
#include "source/common/stream_info/utility.h"
#include "absl/strings/escaping.h"
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
namespace Envoy {
namespace Http {
const absl::string_view ConnectionManagerImpl::PrematureResetTotalStreamCountKey =
"overload.premature_reset_total_stream_count";
const absl::string_view ConnectionManagerImpl::PrematureResetMinStreamLifetimeSecondsKey =
"overload.premature_reset_min_stream_lifetime_seconds";
// Runtime key for maximum number of requests that can be processed from a single connection per
// I/O cycle. Requests over this limit are deferred until the next I/O cycle.
const absl::string_view ConnectionManagerImpl::MaxRequestsPerIoCycle =
"http.max_requests_per_io_cycle";
// Don't attempt to intelligently delay close: https://github.com/envoyproxy/envoy/issues/30010
const absl::string_view ConnectionManagerImpl::OptionallyDelayClose =
"http1.optionally_delay_close";
bool requestWasConnect(const RequestHeaderMapSharedPtr& headers, Protocol protocol) {
if (!headers) {
return false;
}
if (protocol <= Protocol::Http11) {
return HeaderUtility::isConnect(*headers);
}
// All HTTP/2 style upgrades were originally connect requests.
return HeaderUtility::isConnect(*headers) || Utility::isUpgrade(*headers);
}
ConnectionManagerStats ConnectionManagerImpl::generateStats(const std::string& prefix,
Stats::Scope& scope) {
return ConnectionManagerStats(
{ALL_HTTP_CONN_MAN_STATS(POOL_COUNTER_PREFIX(scope, prefix), POOL_GAUGE_PREFIX(scope, prefix),
POOL_HISTOGRAM_PREFIX(scope, prefix))},
prefix, scope);
}
ConnectionManagerTracingStats ConnectionManagerImpl::generateTracingStats(const std::string& prefix,
Stats::Scope& scope) {
return {CONN_MAN_TRACING_STATS(POOL_COUNTER_PREFIX(scope, prefix + "tracing."))};
}
ConnectionManagerListenerStats
ConnectionManagerImpl::generateListenerStats(const std::string& prefix, Stats::Scope& scope) {
return {CONN_MAN_LISTENER_STATS(POOL_COUNTER_PREFIX(scope, prefix))};
}
ConnectionManagerImpl::ConnectionManagerImpl(ConnectionManagerConfigSharedPtr config,
const Network::DrainDecision& drain_close,
Random::RandomGenerator& random_generator,
Http::Context& http_context, Runtime::Loader& runtime,
const LocalInfo::LocalInfo& local_info,
Upstream::ClusterManager& cluster_manager,
Server::OverloadManager& overload_manager,
TimeSource& time_source)
: config_(std::move(config)), stats_(config_->stats()),
conn_length_(new Stats::HistogramCompletableTimespanImpl(
stats_.named_.downstream_cx_length_ms_, time_source)),
drain_close_(drain_close), user_agent_(http_context.userAgentContext()),
random_generator_(random_generator), runtime_(runtime), local_info_(local_info),
cluster_manager_(cluster_manager), listener_stats_(config_->listenerStats()),
overload_manager_(overload_manager),
overload_state_(overload_manager.getThreadLocalOverloadState()),
accept_new_http_stream_(
overload_manager.getLoadShedPoint(Server::LoadShedPointName::get().HcmDecodeHeaders)),
hcm_ondata_creating_codec_(
overload_manager.getLoadShedPoint(Server::LoadShedPointName::get().HcmCodecCreation)),
overload_stop_accepting_requests_ref_(
overload_state_.getState(Server::OverloadActionNames::get().StopAcceptingRequests)),
overload_disable_keepalive_ref_(
overload_state_.getState(Server::OverloadActionNames::get().DisableHttpKeepAlive)),
time_source_(time_source), proxy_name_(StreamInfo::ProxyStatusUtils::makeProxyName(
/*node_id=*/local_info_.node().id(),
/*server_name=*/config_->serverName(),
/*proxy_status_config=*/config_->proxyStatusConfig())),
max_requests_during_dispatch_(
runtime_.snapshot().getInteger(ConnectionManagerImpl::MaxRequestsPerIoCycle, UINT32_MAX)),
allow_upstream_half_close_(Runtime::runtimeFeatureEnabled(
"envoy.reloadable_features.allow_multiplexed_upstream_half_close")) {
ENVOY_LOG_ONCE_IF(
trace, accept_new_http_stream_ == nullptr,
"LoadShedPoint envoy.load_shed_points.http_connection_manager_decode_headers is not "
"found. Is it configured?");
ENVOY_LOG_ONCE_IF(trace, hcm_ondata_creating_codec_ == nullptr,
"LoadShedPoint envoy.load_shed_points.hcm_ondata_creating_codec is not found. "
"Is it configured?");
}
const ResponseHeaderMap& ConnectionManagerImpl::continueHeader() {
static const auto headers = createHeaderMap<ResponseHeaderMapImpl>(
{{Http::Headers::get().Status, std::to_string(enumToInt(Code::Continue))}});
return *headers;
}
void ConnectionManagerImpl::initializeReadFilterCallbacks(Network::ReadFilterCallbacks& callbacks) {
read_callbacks_ = &callbacks;
dispatcher_ = &callbacks.connection().dispatcher();
if (max_requests_during_dispatch_ != UINT32_MAX) {
deferred_request_processing_callback_ =
dispatcher_->createSchedulableCallback([this]() -> void { onDeferredRequestProcessing(); });
}
stats_.named_.downstream_cx_total_.inc();
stats_.named_.downstream_cx_active_.inc();
if (read_callbacks_->connection().ssl()) {
stats_.named_.downstream_cx_ssl_total_.inc();
stats_.named_.downstream_cx_ssl_active_.inc();
}
read_callbacks_->connection().addConnectionCallbacks(*this);
if (config_->addProxyProtocolConnectionState() &&
!read_callbacks_->connection()
.streamInfo()
.filterState()
->hasData<Network::ProxyProtocolFilterState>(Network::ProxyProtocolFilterState::key())) {
read_callbacks_->connection().streamInfo().filterState()->setData(
Network::ProxyProtocolFilterState::key(),
std::make_unique<Network::ProxyProtocolFilterState>(Network::ProxyProtocolData{
read_callbacks_->connection().connectionInfoProvider().remoteAddress(),
read_callbacks_->connection().connectionInfoProvider().localAddress()}),
StreamInfo::FilterState::StateType::ReadOnly,
StreamInfo::FilterState::LifeSpan::Connection);
}
if (config_->idleTimeout()) {
connection_idle_timer_ =
dispatcher_->createScaledTimer(Event::ScaledTimerType::HttpDownstreamIdleConnectionTimeout,
[this]() -> void { onIdleTimeout(); });
connection_idle_timer_->enableTimer(config_->idleTimeout().value());
}
if (config_->maxConnectionDuration()) {
connection_duration_timer_ =
dispatcher_->createTimer([this]() -> void { onConnectionDurationTimeout(); });
connection_duration_timer_->enableTimer(config_->maxConnectionDuration().value());
}
read_callbacks_->connection().setDelayedCloseTimeout(config_->delayedCloseTimeout());
read_callbacks_->connection().setConnectionStats(
{stats_.named_.downstream_cx_rx_bytes_total_, stats_.named_.downstream_cx_rx_bytes_buffered_,
stats_.named_.downstream_cx_tx_bytes_total_, stats_.named_.downstream_cx_tx_bytes_buffered_,
nullptr, &stats_.named_.downstream_cx_delayed_close_timeout_});
}
ConnectionManagerImpl::~ConnectionManagerImpl() {
stats_.named_.downstream_cx_destroy_.inc();
stats_.named_.downstream_cx_active_.dec();
if (read_callbacks_->connection().ssl()) {
stats_.named_.downstream_cx_ssl_active_.dec();
}
if (codec_) {
if (codec_->protocol() == Protocol::Http2) {
stats_.named_.downstream_cx_http2_active_.dec();
} else if (codec_->protocol() == Protocol::Http3) {
stats_.named_.downstream_cx_http3_active_.dec();
} else {
stats_.named_.downstream_cx_http1_active_.dec();
}
}
if (soft_drain_http1_) {
stats_.named_.downstream_cx_http1_soft_drain_.dec();
}
conn_length_->complete();
user_agent_.completeConnectionLength(*conn_length_);
}
void ConnectionManagerImpl::checkForDeferredClose(bool skip_delay_close) {
Network::ConnectionCloseType close = Network::ConnectionCloseType::FlushWriteAndDelay;
if (runtime_.snapshot().getBoolean(ConnectionManagerImpl::OptionallyDelayClose, true) &&
skip_delay_close) {
close = Network::ConnectionCloseType::FlushWrite;
}
if (drain_state_ == DrainState::Closing && streams_.empty() && !codec_->wantsToWrite()) {
// We are closing a draining connection with no active streams and the codec has
// nothing to write.
doConnectionClose(close, absl::nullopt,
StreamInfo::LocalCloseReasons::get().DeferredCloseOnDrainedConnection);
}
}
void ConnectionManagerImpl::doEndStream(ActiveStream& stream, bool check_for_deferred_close) {
// The order of what happens in this routine is important and a little complicated. We first see
// if the stream needs to be reset. If it needs to be, this will end up invoking reset callbacks
// and then moving the stream to the deferred destruction list. If the stream has not been reset,
// we move it to the deferred deletion list here. Then, we potentially close the connection. This
// must be done after deleting the stream since the stream refers to the connection and must be
// deleted first.
bool reset_stream = false;
// If the response encoder is still associated with the stream, reset the stream. The exception
// here is when Envoy "ends" the stream by calling recreateStream at which point recreateStream
// explicitly nulls out response_encoder to avoid the downstream being notified of the
// Envoy-internal stream instance being ended.
if (stream.response_encoder_ != nullptr &&
(!stream.filter_manager_.hasLastDownstreamByteReceived() ||
!stream.state_.codec_saw_local_complete_)) {
// Indicate local is complete at this point so that if we reset during a continuation, we don't
// raise further data or trailers.
ENVOY_STREAM_LOG(debug, "doEndStream() resetting stream", stream);
// TODO(snowp): This call might not be necessary, try to clean up + remove setter function.
stream.filter_manager_.setLocalComplete();
stream.state_.codec_saw_local_complete_ = true;
// Per https://tools.ietf.org/html/rfc7540#section-8.3 if there was an error
// with the TCP connection during a CONNECT request, it should be
// communicated via CONNECT_ERROR
if (requestWasConnect(stream.request_headers_, codec_->protocol()) &&
(stream.filter_manager_.streamInfo().hasResponseFlag(
StreamInfo::CoreResponseFlag::UpstreamConnectionFailure) ||
stream.filter_manager_.streamInfo().hasResponseFlag(
StreamInfo::CoreResponseFlag::UpstreamConnectionTermination))) {
stream.response_encoder_->getStream().resetStream(StreamResetReason::ConnectError);
} else {
if (stream.filter_manager_.streamInfo().hasResponseFlag(
StreamInfo::CoreResponseFlag::UpstreamProtocolError)) {
stream.response_encoder_->getStream().resetStream(StreamResetReason::ProtocolError);
} else {
stream.response_encoder_->getStream().resetStream(StreamResetReason::LocalReset);
}
}
reset_stream = true;
}
if (!reset_stream) {
doDeferredStreamDestroy(stream);
}
if (reset_stream && codec_->protocol() < Protocol::Http2) {
drain_state_ = DrainState::Closing;
}
if (check_for_deferred_close) {
// If HTTP/1.0 has no content length, it is framed by close and won't consider
// the request complete until the FIN is read. Don't delay close in this case.
const bool http_10_sans_cl =
(codec_->protocol() == Protocol::Http10) &&
(!stream.response_headers_ || !stream.response_headers_->ContentLength());
// We also don't delay-close in the case of HTTP/1.1 where the request is
// fully read, as there's no race condition to avoid.
const bool connection_close =
stream.filter_manager_.streamInfo().shouldDrainConnectionUponCompletion();
const bool request_complete = stream.filter_manager_.hasLastDownstreamByteReceived();
// Don't do delay close for HTTP/1.0 or if the request is complete.
checkForDeferredClose(connection_close && (request_complete || http_10_sans_cl));
}
}
void ConnectionManagerImpl::doDeferredStreamDestroy(ActiveStream& stream) {
if (!stream.state_.is_internally_destroyed_) {
++closed_non_internally_destroyed_requests_;
if (isPrematureRstStream(stream)) {
++number_premature_stream_resets_;
}
}
if (stream.max_stream_duration_timer_ != nullptr) {
stream.max_stream_duration_timer_->disableTimer();
stream.max_stream_duration_timer_ = nullptr;
}
if (stream.stream_idle_timer_ != nullptr) {
stream.stream_idle_timer_->disableTimer();
stream.stream_idle_timer_ = nullptr;
}
stream.filter_manager_.disarmRequestTimeout();
if (stream.request_header_timer_ != nullptr) {
stream.request_header_timer_->disableTimer();
stream.request_header_timer_ = nullptr;
}
if (stream.access_log_flush_timer_ != nullptr) {
stream.access_log_flush_timer_->disableTimer();
stream.access_log_flush_timer_ = nullptr;
}
// Only destroy the active stream if the underlying codec has notified us of
// completion or we've internal redirect the stream.
if (!stream.canDestroyStream()) {
// Track that this stream is not expecting any additional calls apart from
// codec notification.
stream.state_.is_zombie_stream_ = true;
return;
}
if (stream.response_encoder_ != nullptr) {
stream.response_encoder_->getStream().registerCodecEventCallbacks(nullptr);
}
stream.completeRequest();
stream.filter_manager_.onStreamComplete();
// For HTTP/3, skip access logging here and add deferred logging info
// to stream info for QuicStatsGatherer to use later.
if (codec_ && codec_->protocol() == Protocol::Http3 &&
// There was a downstream reset, log immediately.
!stream.filter_manager_.sawDownstreamReset() &&
// On recreate stream, log immediately.
stream.response_encoder_ != nullptr &&
Runtime::runtimeFeatureEnabled(
"envoy.reloadable_features.quic_defer_logging_to_ack_listener")) {
stream.deferHeadersAndTrailers();
} else {
// For HTTP/1 and HTTP/2, log here as usual.
stream.log(AccessLog::AccessLogType::DownstreamEnd);
}
stream.filter_manager_.destroyFilters();
dispatcher_->deferredDelete(stream.removeFromList(streams_));
// The response_encoder should never be dangling (unless we're destroying a
// stream we are recreating) as the codec level stream will either outlive the
// ActiveStream, or be alive in deferred deletion queue at this point.
if (stream.response_encoder_) {
stream.response_encoder_->getStream().removeCallbacks(stream);
}
if (connection_idle_timer_ && streams_.empty()) {
connection_idle_timer_->enableTimer(config_->idleTimeout().value());
}
maybeDrainDueToPrematureResets();
}
RequestDecoderHandlePtr ConnectionManagerImpl::newStreamHandle(ResponseEncoder& response_encoder,
bool is_internally_created) {
RequestDecoder& decoder = newStream(response_encoder, is_internally_created);
return std::make_unique<ActiveStreamHandle>(static_cast<ActiveStream&>(decoder));
}
RequestDecoder& ConnectionManagerImpl::newStream(ResponseEncoder& response_encoder,
bool is_internally_created) {
TRACE_EVENT("core", "ConnectionManagerImpl::newStream");
if (connection_idle_timer_) {
connection_idle_timer_->disableTimer();
}
ENVOY_CONN_LOG(debug, "new stream", read_callbacks_->connection());
Buffer::BufferMemoryAccountSharedPtr downstream_stream_account =
response_encoder.getStream().account();
if (downstream_stream_account == nullptr) {
// Create account, wiring the stream to use it for tracking bytes.
// If tracking is disabled, the wiring becomes a NOP.
auto& buffer_factory = dispatcher_->getWatermarkFactory();
downstream_stream_account = buffer_factory.createAccount(response_encoder.getStream());
response_encoder.getStream().setAccount(downstream_stream_account);
}
auto new_stream = std::make_unique<ActiveStream>(
*this, response_encoder.getStream().bufferLimit(), std::move(downstream_stream_account));
accumulated_requests_++;
if (config_->maxRequestsPerConnection() > 0 &&
accumulated_requests_ >= config_->maxRequestsPerConnection()) {
if (codec_->protocol() < Protocol::Http2) {
new_stream->filter_manager_.streamInfo().setShouldDrainConnectionUponCompletion(true);
// Prevent erroneous debug log of closing due to incoming connection close header.
drain_state_ = DrainState::Closing;
} else if (drain_state_ == DrainState::NotDraining) {
startDrainSequence();
}
ENVOY_CONN_LOG(debug, "max requests per connection reached", read_callbacks_->connection());
stats_.named_.downstream_cx_max_requests_reached_.inc();
}
if (soft_drain_http1_) {
new_stream->filter_manager_.streamInfo().setShouldDrainConnectionUponCompletion(true);
// Prevent erroneous debug log of closing due to incoming connection close header.
drain_state_ = DrainState::Closing;
}
new_stream->state_.is_internally_created_ = is_internally_created;
new_stream->response_encoder_ = &response_encoder;
new_stream->response_encoder_->getStream().addCallbacks(*new_stream);
new_stream->response_encoder_->getStream().registerCodecEventCallbacks(new_stream.get());
new_stream->response_encoder_->getStream().setFlushTimeout(new_stream->idle_timeout_ms_);
new_stream->streamInfo().setDownstreamBytesMeter(response_encoder.getStream().bytesMeter());
// If the network connection is backed up, the stream should be made aware of it on creation.
// Both HTTP/1.x and HTTP/2 codecs handle this in StreamCallbackHelper::addCallbacksHelper.
ASSERT(read_callbacks_->connection().aboveHighWatermark() == false ||
new_stream->filter_manager_.aboveHighWatermark());
LinkedList::moveIntoList(std::move(new_stream), streams_);
return **streams_.begin();
}
void ConnectionManagerImpl::handleCodecErrorImpl(absl::string_view error, absl::string_view details,
StreamInfo::CoreResponseFlag response_flag) {
ENVOY_CONN_LOG(debug, "dispatch error: {}", read_callbacks_->connection(), error);
read_callbacks_->connection().streamInfo().setResponseFlag(response_flag);
// HTTP/1.1 codec has already sent a 400 response if possible. HTTP/2 codec has already sent
// GOAWAY.
doConnectionClose(Network::ConnectionCloseType::FlushWriteAndDelay, response_flag, details);
}
void ConnectionManagerImpl::handleCodecError(absl::string_view error) {
handleCodecErrorImpl(error, absl::StrCat("codec_error:", StringUtil::replaceAllEmptySpace(error)),
StreamInfo::CoreResponseFlag::DownstreamProtocolError);
}
void ConnectionManagerImpl::handleCodecOverloadError(absl::string_view error) {
handleCodecErrorImpl(error,
absl::StrCat("overload_error:", StringUtil::replaceAllEmptySpace(error)),
StreamInfo::CoreResponseFlag::OverloadManager);
}
void ConnectionManagerImpl::createCodec(Buffer::Instance& data) {
ASSERT(!codec_);
codec_ = config_->createCodec(read_callbacks_->connection(), data, *this, overload_manager_);
switch (codec_->protocol()) {
case Protocol::Http3:
stats_.named_.downstream_cx_http3_total_.inc();
stats_.named_.downstream_cx_http3_active_.inc();
break;
case Protocol::Http2:
stats_.named_.downstream_cx_http2_total_.inc();
stats_.named_.downstream_cx_http2_active_.inc();
break;
case Protocol::Http11:
case Protocol::Http10:
stats_.named_.downstream_cx_http1_total_.inc();
stats_.named_.downstream_cx_http1_active_.inc();
break;
}
}
Network::FilterStatus ConnectionManagerImpl::onData(Buffer::Instance& data, bool) {
requests_during_dispatch_count_ = 0;
if (!codec_) {
// Close connections if Envoy is under pressure, typically memory, before creating codec.
if (hcm_ondata_creating_codec_ != nullptr && hcm_ondata_creating_codec_->shouldShedLoad()) {
stats_.named_.downstream_rq_overload_close_.inc();
handleCodecOverloadError("onData codec creation overload");
return Network::FilterStatus::StopIteration;
}
// Http3 codec should have been instantiated by now.
createCodec(data);
}
bool redispatch;
do {
redispatch = false;
const Status status = codec_->dispatch(data);
if (isBufferFloodError(status) || isInboundFramesWithEmptyPayloadError(status)) {
handleCodecError(status.message());
return Network::FilterStatus::StopIteration;
} else if (isCodecProtocolError(status)) {
stats_.named_.downstream_cx_protocol_error_.inc();
handleCodecError(status.message());
return Network::FilterStatus::StopIteration;
} else if (isEnvoyOverloadError(status)) {
// The other codecs aren't wired to send this status.
ASSERT(codec_->protocol() < Protocol::Http2,
"Expected only HTTP1.1 and below to send overload error.");
stats_.named_.downstream_rq_overload_close_.inc();
handleCodecOverloadError(status.message());
return Network::FilterStatus::StopIteration;
}
ASSERT(status.ok());
// Processing incoming data may release outbound data so check for closure here as well.
checkForDeferredClose(false);
// The HTTP/1 codec will pause dispatch after a single message is complete. We want to
// either redispatch if there are no streams and we have more data. If we have a single
// complete non-WebSocket stream but have not responded yet we will pause socket reads
// to apply back pressure.
if (codec_->protocol() < Protocol::Http2) {
if (read_callbacks_->connection().state() == Network::Connection::State::Open &&
data.length() > 0 && streams_.empty()) {
redispatch = true;
}
}
} while (redispatch);
if (!read_callbacks_->connection().streamInfo().protocol()) {
read_callbacks_->connection().streamInfo().protocol(codec_->protocol());
}
return Network::FilterStatus::StopIteration;
}
Network::FilterStatus ConnectionManagerImpl::onNewConnection() {
if (!read_callbacks_->connection().streamInfo().protocol()) {
// For Non-QUIC traffic, continue passing data to filters.
return Network::FilterStatus::Continue;
}
// Only QUIC connection's stream_info_ specifies protocol.
Buffer::OwnedImpl dummy;
createCodec(dummy);
ASSERT(codec_->protocol() == Protocol::Http3);
// Stop iterating through network filters for QUIC. Currently QUIC connections bypass the
// onData() interface because QUICHE already handles de-multiplexing.
return Network::FilterStatus::StopIteration;
}
void ConnectionManagerImpl::resetAllStreams(
absl::optional<StreamInfo::CoreResponseFlag> response_flag, absl::string_view details) {
while (!streams_.empty()) {
// Mimic a downstream reset in this case. We must also remove callbacks here. Though we are
// about to close the connection and will disable further reads, it is possible that flushing
// data out can cause stream callbacks to fire (e.g., low watermark callbacks).
//
// TODO(mattklein123): I tried to actually reset through the codec here, but ran into issues
// with nghttp2 state and being unhappy about sending reset frames after the connection had
// been terminated via GOAWAY. It might be possible to do something better here inside the h2
// codec but there are no easy answers and this seems simpler.
auto& stream = *streams_.front();
stream.response_encoder_->getStream().removeCallbacks(stream);
if (!stream.response_encoder_->getStream().responseDetails().empty()) {
stream.filter_manager_.streamInfo().setResponseCodeDetails(
stream.response_encoder_->getStream().responseDetails());
} else if (!details.empty()) {
stream.filter_manager_.streamInfo().setResponseCodeDetails(details);
}
if (response_flag.has_value()) {
stream.filter_manager_.streamInfo().setResponseFlag(response_flag.value());
}
stream.onResetStream(StreamResetReason::ConnectionTermination, absl::string_view());
}
}
void ConnectionManagerImpl::onEvent(Network::ConnectionEvent event) {
if (event == Network::ConnectionEvent::LocalClose) {
stats_.named_.downstream_cx_destroy_local_.inc();
}
if (event == Network::ConnectionEvent::RemoteClose ||
event == Network::ConnectionEvent::LocalClose) {
std::string details;
if (event == Network::ConnectionEvent::RemoteClose) {
remote_close_ = true;
stats_.named_.downstream_cx_destroy_remote_.inc();
details = StreamInfo::ResponseCodeDetails::get().DownstreamRemoteDisconnect;
} else {
absl::string_view local_close_reason = read_callbacks_->connection().localCloseReason();
ENVOY_BUG(!local_close_reason.empty(), "Local Close Reason was not set!");
details = fmt::format(
fmt::runtime(StreamInfo::ResponseCodeDetails::get().DownstreamLocalDisconnect),
StringUtil::replaceAllEmptySpace(local_close_reason));
}
// TODO(mattklein123): It is technically possible that something outside of the filter causes
// a local connection close, so we still guard against that here. A better solution would be to
// have some type of "pre-close" callback that we could hook for cleanup that would get called
// regardless of where local close is invoked from.
// NOTE: that this will cause doConnectionClose() to get called twice in the common local close
// cases, but the method protects against that.
// NOTE: In the case where a local close comes from outside the filter, this will cause any
// stream closures to increment remote close stats. We should do better here in the future,
// via the pre-close callback mentioned above.
doConnectionClose(absl::nullopt, StreamInfo::CoreResponseFlag::DownstreamConnectionTermination,
details);
}
}
void ConnectionManagerImpl::doConnectionClose(
absl::optional<Network::ConnectionCloseType> close_type,
absl::optional<StreamInfo::CoreResponseFlag> response_flag, absl::string_view details) {
if (connection_idle_timer_) {
connection_idle_timer_->disableTimer();
connection_idle_timer_.reset();
}
if (connection_duration_timer_) {
connection_duration_timer_->disableTimer();
connection_duration_timer_.reset();
}
if (drain_timer_) {
drain_timer_->disableTimer();
drain_timer_.reset();
}
if (!streams_.empty()) {
const Network::ConnectionEvent event = close_type.has_value()
? Network::ConnectionEvent::LocalClose
: Network::ConnectionEvent::RemoteClose;
if (event == Network::ConnectionEvent::LocalClose) {
stats_.named_.downstream_cx_destroy_local_active_rq_.inc();
}
if (event == Network::ConnectionEvent::RemoteClose) {
stats_.named_.downstream_cx_destroy_remote_active_rq_.inc();
}
stats_.named_.downstream_cx_destroy_active_rq_.inc();
user_agent_.onConnectionDestroy(event, true);
// Note that resetAllStreams() does not actually write anything to the wire. It just resets
// all upstream streams and their filter stacks. Thus, there are no issues around recursive
// entry.
resetAllStreams(response_flag, details);
}
if (close_type.has_value()) {
read_callbacks_->connection().close(close_type.value(), details);
}
}
bool ConnectionManagerImpl::isPrematureRstStream(const ActiveStream& stream) const {
// Check if the request was prematurely reset, by comparing its lifetime to the configured
// threshold.
ASSERT(!stream.state_.is_internally_destroyed_);
absl::optional<std::chrono::nanoseconds> duration =
stream.filter_manager_.streamInfo().currentDuration();
// Check if request lifetime is longer than the premature reset threshold.
if (duration) {
const uint64_t lifetime = std::chrono::duration_cast<std::chrono::seconds>(*duration).count();
const uint64_t min_lifetime = runtime_.snapshot().getInteger(
ConnectionManagerImpl::PrematureResetMinStreamLifetimeSecondsKey, 1);
if (lifetime > min_lifetime) {
return false;
}
}
// If request has completed before configured threshold, also check if the Envoy proxied the
// response from the upstream. Requests without the response status were reset.
// TODO(RyanTheOptimist): Possibly support half_closed_local instead.
return !stream.filter_manager_.streamInfo().responseCode();
}
// Sends a GOAWAY if too many streams have been reset prematurely on this
// connection.
void ConnectionManagerImpl::maybeDrainDueToPrematureResets() {
if (closed_non_internally_destroyed_requests_ == 0) {
return;
}
const uint64_t limit =
runtime_.snapshot().getInteger(ConnectionManagerImpl::PrematureResetTotalStreamCountKey, 500);
if (closed_non_internally_destroyed_requests_ < limit) {
// Even though the total number of streams have not reached `limit`, check if the number of bad
// streams is high enough that even if every subsequent stream is good, the connection
// would be closed once the limit is reached, and if so close the connection now.
if (number_premature_stream_resets_ * 2 < limit) {
return;
}
} else {
if (number_premature_stream_resets_ * 2 < closed_non_internally_destroyed_requests_) {
return;
}
}
if (read_callbacks_->connection().state() == Network::Connection::State::Open) {
stats_.named_.downstream_rq_too_many_premature_resets_.inc();
doConnectionClose(Network::ConnectionCloseType::Abort, absl::nullopt,
"too_many_premature_resets");
}
}
void ConnectionManagerImpl::onGoAway(GoAwayErrorCode) {
// Currently we do nothing with remote go away frames. In the future we can decide to no longer
// push resources if applicable.
}
void ConnectionManagerImpl::onIdleTimeout() {
ENVOY_CONN_LOG(debug, "idle timeout", read_callbacks_->connection());
stats_.named_.downstream_cx_idle_timeout_.inc();
if (!codec_) {
// No need to delay close after flushing since an idle timeout has already fired. Attempt to
// write out buffered data one last time and issue a local close if successful.
doConnectionClose(Network::ConnectionCloseType::FlushWrite, absl::nullopt,
StreamInfo::LocalCloseReasons::get().IdleTimeoutOnConnection);
} else if (drain_state_ == DrainState::NotDraining) {
startDrainSequence();
}
}
void ConnectionManagerImpl::onConnectionDurationTimeout() {
ENVOY_CONN_LOG(debug, "max connection duration reached", read_callbacks_->connection());
stats_.named_.downstream_cx_max_duration_reached_.inc();
if (!codec_) {
// Attempt to write out buffered data one last time and issue a local close if successful.
doConnectionClose(Network::ConnectionCloseType::FlushWrite,
StreamInfo::CoreResponseFlag::DurationTimeout,
StreamInfo::ResponseCodeDetails::get().DurationTimeout);
} else if (drain_state_ == DrainState::NotDraining) {
if (config_->http1SafeMaxConnectionDuration() && codec_->protocol() < Protocol::Http2) {
ENVOY_CONN_LOG(debug,
"HTTP1-safe max connection duration is configured -- skipping drain sequence.",
read_callbacks_->connection());
stats_.named_.downstream_cx_http1_soft_drain_.inc();
soft_drain_http1_ = true;
} else {
startDrainSequence();
}
}
}
void ConnectionManagerImpl::onDrainTimeout() {
ASSERT(drain_state_ != DrainState::NotDraining);
codec_->goAway();
drain_state_ = DrainState::Closing;
checkForDeferredClose(false);
}
void ConnectionManagerImpl::chargeTracingStats(const Tracing::Reason& tracing_reason,
ConnectionManagerTracingStats& tracing_stats) {
switch (tracing_reason) {
case Tracing::Reason::ClientForced:
tracing_stats.client_enabled_.inc();
break;
case Tracing::Reason::Sampling:
tracing_stats.random_sampling_.inc();
break;
case Tracing::Reason::ServiceForced:
tracing_stats.service_forced_.inc();
break;
default:
tracing_stats.not_traceable_.inc();
break;
}
}
absl::optional<absl::string_view>
ConnectionManagerImpl::HttpStreamIdProviderImpl::toStringView() const {
if (parent_.request_headers_ == nullptr) {
return {};
}
ASSERT(parent_.connection_manager_.config_->requestIDExtension() != nullptr);
return parent_.connection_manager_.config_->requestIDExtension()->get(*parent_.request_headers_);
}
absl::optional<uint64_t> ConnectionManagerImpl::HttpStreamIdProviderImpl::toInteger() const {
if (parent_.request_headers_ == nullptr) {
return {};
}
ASSERT(parent_.connection_manager_.config_->requestIDExtension() != nullptr);
return parent_.connection_manager_.config_->requestIDExtension()->getInteger(
*parent_.request_headers_);
}
namespace {
constexpr absl::string_view kRouteFactoryName = "envoy.route_config_update_requester.default";
} // namespace
ConnectionManagerImpl::ActiveStream::ActiveStream(ConnectionManagerImpl& connection_manager,
uint32_t buffer_limit,
Buffer::BufferMemoryAccountSharedPtr account)
: connection_manager_(connection_manager),
connection_manager_tracing_config_(connection_manager_.config_->tracingConfig() == nullptr
? absl::nullopt
: makeOptRef<const TracingConnectionManagerConfig>(
*connection_manager_.config_->tracingConfig())),
stream_id_(connection_manager.random_generator_.random()),
filter_manager_(*this, *connection_manager_.dispatcher_,
connection_manager_.read_callbacks_->connection(), stream_id_,
std::move(account), connection_manager_.config_->proxy100Continue(),
buffer_limit, connection_manager_.config_->filterFactory(),
connection_manager_.config_->localReply(),
connection_manager_.codec_->protocol(), connection_manager_.timeSource(),
connection_manager_.read_callbacks_->connection().streamInfo().filterState(),
connection_manager_.overload_manager_),
request_response_timespan_(new Stats::HistogramCompletableTimespanImpl(
connection_manager_.stats_.named_.downstream_rq_time_, connection_manager_.timeSource())),
header_validator_(
connection_manager.config_->makeHeaderValidator(connection_manager.codec_->protocol())) {
ASSERT(!connection_manager.config_->isRoutable() ||
((connection_manager.config_->routeConfigProvider() == nullptr &&
connection_manager.config_->scopedRouteConfigProvider() != nullptr &&
connection_manager.config_->scopeKeyBuilder().has_value()) ||
(connection_manager.config_->routeConfigProvider() != nullptr &&
connection_manager.config_->scopedRouteConfigProvider() == nullptr &&
!connection_manager.config_->scopeKeyBuilder().has_value())),
"Either routeConfigProvider or (scopedRouteConfigProvider and scopeKeyBuilder) should be "
"set in "
"ConnectionManagerImpl.");
filter_manager_.streamInfo().setStreamIdProvider(
std::make_shared<HttpStreamIdProviderImpl>(*this));
filter_manager_.streamInfo().setShouldSchemeMatchUpstream(
connection_manager.config_->shouldSchemeMatchUpstream());
// TODO(chaoqin-li1123): can this be moved to the on demand filter?
auto factory = Envoy::Config::Utility::getFactoryByName<RouteConfigUpdateRequesterFactory>(
kRouteFactoryName);
if (connection_manager_.config_->isRoutable() &&
connection_manager.config_->routeConfigProvider() != nullptr && factory) {
route_config_update_requester_ = factory->createRouteConfigUpdateRequester(
connection_manager.config_->routeConfigProvider());
} else if (connection_manager_.config_->isRoutable() &&
connection_manager.config_->scopedRouteConfigProvider() != nullptr &&
connection_manager.config_->scopeKeyBuilder().has_value() && factory) {
route_config_update_requester_ = factory->createRouteConfigUpdateRequester(
connection_manager.config_->scopedRouteConfigProvider(),
connection_manager.config_->scopeKeyBuilder());
}
ScopeTrackerScopeState scope(this,
connection_manager_.read_callbacks_->connection().dispatcher());
connection_manager_.stats_.named_.downstream_rq_total_.inc();
connection_manager_.stats_.named_.downstream_rq_active_.inc();
if (connection_manager_.codec_->protocol() == Protocol::Http2) {
connection_manager_.stats_.named_.downstream_rq_http2_total_.inc();
} else if (connection_manager_.codec_->protocol() == Protocol::Http3) {
connection_manager_.stats_.named_.downstream_rq_http3_total_.inc();
} else {
connection_manager_.stats_.named_.downstream_rq_http1_total_.inc();
}
if (connection_manager_.config_->streamIdleTimeout().count()) {
idle_timeout_ms_ = connection_manager_.config_->streamIdleTimeout();
stream_idle_timer_ = connection_manager_.dispatcher_->createScaledTimer(
Event::ScaledTimerType::HttpDownstreamIdleStreamTimeout,
[this]() -> void { onIdleTimeout(); });
resetIdleTimer();
}
if (connection_manager_.config_->requestTimeout().count()) {
std::chrono::milliseconds request_timeout = connection_manager_.config_->requestTimeout();
request_timer_ =
connection_manager.dispatcher_->createTimer([this]() -> void { onRequestTimeout(); });
request_timer_->enableTimer(request_timeout, this);
}
if (connection_manager_.config_->requestHeadersTimeout().count()) {
std::chrono::milliseconds request_headers_timeout =
connection_manager_.config_->requestHeadersTimeout();
request_header_timer_ =
connection_manager.dispatcher_->createTimer([this]() -> void { onRequestHeaderTimeout(); });
request_header_timer_->enableTimer(request_headers_timeout, this);
}
const auto max_stream_duration = connection_manager_.config_->maxStreamDuration();
if (max_stream_duration.has_value() && max_stream_duration.value().count()) {
max_stream_duration_timer_ = connection_manager.dispatcher_->createTimer(
[this]() -> void { onStreamMaxDurationReached(); });
max_stream_duration_timer_->enableTimer(
connection_manager_.config_->maxStreamDuration().value(), this);
}
if (connection_manager_.config_->accessLogFlushInterval().has_value()) {
access_log_flush_timer_ = connection_manager.dispatcher_->createTimer([this]() -> void {
// If the request is complete, we've already done the stream-end access-log, and shouldn't
// do the periodic log.
if (!streamInfo().requestComplete().has_value()) {
log(AccessLog::AccessLogType::DownstreamPeriodic);
refreshAccessLogFlushTimer();
}
const SystemTime now = connection_manager_.timeSource().systemTime();
// Downstream bytes meter is guaranteed to be non-null because ActiveStream and the timer
// event are created on the same thread that sets the meter in
// ConnectionManagerImpl::newStream.
filter_manager_.streamInfo().getDownstreamBytesMeter()->takeDownstreamPeriodicLoggingSnapshot(
now);
if (auto& upstream_bytes_meter = filter_manager_.streamInfo().getUpstreamBytesMeter();
upstream_bytes_meter != nullptr) {
upstream_bytes_meter->takeDownstreamPeriodicLoggingSnapshot(now);
}
});
refreshAccessLogFlushTimer();
}
}
void ConnectionManagerImpl::ActiveStream::log(AccessLog::AccessLogType type) {
const Formatter::HttpFormatterContext log_context{
request_headers_.get(), response_headers_.get(), response_trailers_.get(), {}, type,
active_span_.get()};
const bool filter_access_loggers_first =
Runtime::runtimeFeatureEnabled("envoy.reloadable_features.filter_access_loggers_first");
if (!filter_access_loggers_first) {
for (const auto& access_logger : connection_manager_.config_->accessLogs()) {
access_logger->log(log_context, filter_manager_.streamInfo());
}
}
filter_manager_.log(log_context);
if (filter_access_loggers_first) {
for (const auto& access_logger : connection_manager_.config_->accessLogs()) {
access_logger->log(log_context, filter_manager_.streamInfo());
}
}
}
void ConnectionManagerImpl::ActiveStream::completeRequest() {
filter_manager_.streamInfo().onRequestComplete();
connection_manager_.stats_.named_.downstream_rq_active_.dec();
if (filter_manager_.streamInfo().healthCheck()) {
connection_manager_.config_->tracingStats().health_check_.inc();
}
if (active_span_) {
Tracing::HttpTracerUtility::finalizeDownstreamSpan(
*active_span_, request_headers_.get(), response_headers_.get(), response_trailers_.get(),
filter_manager_.streamInfo(), *this);
}
if (state_.successful_upgrade_) {
connection_manager_.stats_.named_.downstream_cx_upgrades_active_.dec();
}
}
void ConnectionManagerImpl::ActiveStream::resetIdleTimer() {
if (stream_idle_timer_ != nullptr) {
// TODO(htuch): If this shows up in performance profiles, optimize by only
// updating a timestamp here and doing periodic checks for idle timeouts
// instead, or reducing the accuracy of timers.
stream_idle_timer_->enableTimer(idle_timeout_ms_);
}
}
void ConnectionManagerImpl::ActiveStream::onIdleTimeout() {
connection_manager_.stats_.named_.downstream_rq_idle_timeout_.inc();
filter_manager_.streamInfo().setResponseFlag(StreamInfo::CoreResponseFlag::StreamIdleTimeout);
sendLocalReply(
Http::Utility::maybeRequestTimeoutCode(filter_manager_.hasLastDownstreamByteReceived()),
"stream timeout", nullptr, absl::nullopt,
StreamInfo::ResponseCodeDetails::get().StreamIdleTimeout);
}
void ConnectionManagerImpl::ActiveStream::onRequestTimeout() {
connection_manager_.stats_.named_.downstream_rq_timeout_.inc();
sendLocalReply(
Http::Utility::maybeRequestTimeoutCode(filter_manager_.hasLastDownstreamByteReceived()),
"request timeout", nullptr, absl::nullopt,
StreamInfo::ResponseCodeDetails::get().RequestOverallTimeout);
}
void ConnectionManagerImpl::ActiveStream::onRequestHeaderTimeout() {
connection_manager_.stats_.named_.downstream_rq_header_timeout_.inc();
sendLocalReply(
Http::Utility::maybeRequestTimeoutCode(filter_manager_.hasLastDownstreamByteReceived()),
"request header timeout", nullptr, absl::nullopt,
StreamInfo::ResponseCodeDetails::get().RequestHeaderTimeout);
}
void ConnectionManagerImpl::ActiveStream::onStreamMaxDurationReached() {
ENVOY_STREAM_LOG(debug, "Stream max duration time reached", *this);
connection_manager_.stats_.named_.downstream_rq_max_duration_reached_.inc();
sendLocalReply(
Http::Utility::maybeRequestTimeoutCode(filter_manager_.hasLastDownstreamByteReceived()),
"downstream duration timeout", nullptr, Grpc::Status::WellKnownGrpcStatus::DeadlineExceeded,
StreamInfo::ResponseCodeDetails::get().MaxDurationTimeout);