-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathconn_manager_impl.cc
2271 lines (1975 loc) · 99 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 "common/http/conn_manager_impl.h"
#include <cstdint>
#include <functional>
#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/network/drain_decision.h"
#include "envoy/router/router.h"
#include "envoy/server/admin.h"
#include "envoy/ssl/connection.h"
#include "envoy/stats/scope.h"
#include "envoy/tracing/http_tracer.h"
#include "common/buffer/buffer_impl.h"
#include "common/common/assert.h"
#include "common/common/empty_string.h"
#include "common/common/enum_to_int.h"
#include "common/common/fmt.h"
#include "common/common/scope_tracker.h"
#include "common/common/utility.h"
#include "common/http/codes.h"
#include "common/http/conn_manager_utility.h"
#include "common/http/exception.h"
#include "common/http/header_map_impl.h"
#include "common/http/headers.h"
#include "common/http/http1/codec_impl.h"
#include "common/http/http2/codec_impl.h"
#include "common/http/path_utility.h"
#include "common/http/utility.h"
#include "common/network/utility.h"
#include "common/router/config_impl.h"
#include "common/runtime/runtime_impl.h"
#include "absl/strings/escaping.h"
#include "absl/strings/match.h"
namespace Envoy {
namespace Http {
namespace {
template <class T> using FilterList = std::list<std::unique_ptr<T>>;
// Shared helper for recording the latest filter used.
template <class T>
void recordLatestDataFilter(const typename FilterList<T>::iterator current_filter,
T*& latest_filter, const FilterList<T>& filters) {
// If this is the first time we're calling onData, just record the current filter.
if (latest_filter == nullptr) {
latest_filter = current_filter->get();
return;
}
// We want to keep this pointing at the latest filter in the filter list that has received the
// onData callback. To do so, we compare the current latest with the *previous* filter. If they
// match, then we must be processing a new filter for the first time. We omit this check if we're
// the first filter, since the above check handles that case.
//
// We compare against the previous filter to avoid multiple filter iterations from reseting the
// pointer: If we just set latest to current, then the first onData filter iteration would
// correctly iterate over the filters and set latest, but on subsequent onData iterations
// we'd start from the beginning again, potentially allowing filter N to modify the buffer even
// though filter M > N was the filter that inserted data into the buffer.
if (current_filter != filters.begin() && latest_filter == std::prev(current_filter)->get()) {
latest_filter = current_filter->get();
}
}
} // namespace
ConnectionManagerStats ConnectionManagerImpl::generateStats(const std::string& prefix,
Stats::Scope& scope) {
return {
{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(ConnectionManagerConfig& config,
const Network::DrainDecision& drain_close,
Runtime::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_(config), stats_(config_.stats()),
conn_length_(new Stats::Timespan(stats_.named_.downstream_cx_length_ms_, time_source)),
drain_close_(drain_close), random_generator_(random_generator), http_context_(http_context),
runtime_(runtime), local_info_(local_info), cluster_manager_(cluster_manager),
listener_stats_(config_.listenerStats()),
overload_stop_accepting_requests_ref_(
overload_manager ? overload_manager->getThreadLocalOverloadState().getState(
Server::OverloadActionNames::get().StopAcceptingRequests)
: Server::OverloadManager::getInactiveState()),
overload_disable_keepalive_ref_(
overload_manager ? overload_manager->getThreadLocalOverloadState().getState(
Server::OverloadActionNames::get().DisableHttpKeepAlive)
: Server::OverloadManager::getInactiveState()),
time_source_(time_source) {}
const HeaderMapImpl& ConnectionManagerImpl::continueHeader() {
CONSTRUCT_ON_FIRST_USE(HeaderMapImpl,
{Http::Headers::get().Status, std::to_string(enumToInt(Code::Continue))});
}
void ConnectionManagerImpl::initializeReadFilterCallbacks(Network::ReadFilterCallbacks& callbacks) {
read_callbacks_ = &callbacks;
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_.idleTimeout()) {
connection_idle_timer_ = read_callbacks_->connection().dispatcher().createTimer(
[this]() -> void { onIdleTimeout(); });
connection_idle_timer_->enableTimer(config_.idleTimeout().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 {
stats_.named_.downstream_cx_http1_active_.dec();
}
}
conn_length_->complete();
user_agent_.completeConnectionLength(*conn_length_);
}
void ConnectionManagerImpl::checkForDeferredClose() {
if (drain_state_ == DrainState::Closing && streams_.empty() && !codec_->wantsToWrite()) {
read_callbacks_->connection().close(Network::ConnectionCloseType::FlushWriteAndDelay);
}
}
void ConnectionManagerImpl::doEndStream(ActiveStream& stream) {
// 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.state_.remote_complete_ || !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);
stream.state_.local_complete_ = true;
stream.state_.codec_saw_local_complete_ = true;
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;
}
checkForDeferredClose();
// Reading may have been disabled for the non-multiplexing case, so enable it again.
// Also be sure to unwind any read-disable done by the prior downstream
// connection.
if (drain_state_ != DrainState::Closing && codec_->protocol() != Protocol::Http2) {
while (!read_callbacks_->connection().readEnabled()) {
read_callbacks_->connection().readDisable(false);
}
}
if (connection_idle_timer_ && streams_.empty()) {
connection_idle_timer_->enableTimer(config_.idleTimeout().value());
}
}
void ConnectionManagerImpl::doDeferredStreamDestroy(ActiveStream& stream) {
if (stream.stream_idle_timer_ != nullptr) {
stream.stream_idle_timer_->disableTimer();
stream.stream_idle_timer_ = nullptr;
}
stream.disarmRequestTimeout();
stream.state_.destroyed_ = true;
for (auto& filter : stream.decoder_filters_) {
filter->handle_->onDestroy();
}
for (auto& filter : stream.encoder_filters_) {
// Do not call on destroy twice for dual registered filters.
if (!filter->dual_filter_) {
filter->handle_->onDestroy();
}
}
read_callbacks_->connection().dispatcher().deferredDelete(stream.removeFromList(streams_));
}
StreamDecoder& ConnectionManagerImpl::newStream(StreamEncoder& response_encoder,
bool is_internally_created) {
if (connection_idle_timer_) {
connection_idle_timer_->disableTimer();
}
ENVOY_CONN_LOG(debug, "new stream", read_callbacks_->connection());
ActiveStreamPtr new_stream(new ActiveStream(*this));
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->buffer_limit_ = new_stream->response_encoder_->getStream().bufferLimit();
// 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::addCallbacks_.
ASSERT(read_callbacks_->connection().aboveHighWatermark() == false ||
new_stream->high_watermark_count_ > 0);
new_stream->moveIntoList(std::move(new_stream), streams_);
return **streams_.begin();
}
void ConnectionManagerImpl::handleCodecException(const char* error) {
ENVOY_CONN_LOG(debug, "dispatch error: {}", read_callbacks_->connection(), error);
// In the protocol error case, we need to reset all streams now. The connection might stick around
// long enough for a pending stream to come back and try to encode.
resetAllStreams();
// HTTP/1.1 codec has already sent a 400 response if possible. HTTP/2 codec has already sent
// GOAWAY.
read_callbacks_->connection().close(Network::ConnectionCloseType::FlushWriteAndDelay);
}
Network::FilterStatus ConnectionManagerImpl::onData(Buffer::Instance& data, bool) {
if (!codec_) {
codec_ = config_.createCodec(read_callbacks_->connection(), data, *this);
if (codec_->protocol() == Protocol::Http2) {
stats_.named_.downstream_cx_http2_total_.inc();
stats_.named_.downstream_cx_http2_active_.inc();
} else {
stats_.named_.downstream_cx_http1_total_.inc();
stats_.named_.downstream_cx_http1_active_.inc();
}
}
bool redispatch;
do {
redispatch = false;
try {
codec_->dispatch(data);
} catch (const FrameFloodException& e) {
// TODO(mattklein123): This is an emergency substitute for the lack of connection level
// logging in the HCM. In a public follow up change we will add full support for connection
// level logging in the HCM, similar to what we have in tcp_proxy. This will allow abuse
// indicators to be stored in the connection level stream info, and then matched, sampled,
// etc. when logged.
const envoy::type::FractionalPercent default_value; // 0
if (runtime_.snapshot().featureEnabled("http.connection_manager.log_flood_exception",
default_value)) {
ENVOY_CONN_LOG(warn, "downstream HTTP flood from IP '{}': {}",
read_callbacks_->connection(),
read_callbacks_->connection().remoteAddress()->asString(), e.what());
}
handleCodecException(e.what());
return Network::FilterStatus::StopIteration;
} catch (const CodecProtocolException& e) {
stats_.named_.downstream_cx_protocol_error_.inc();
handleCodecException(e.what());
return Network::FilterStatus::StopIteration;
}
// Processing incoming data may release outbound data so check for closure here as well.
checkForDeferredClose();
// 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;
}
if (!streams_.empty() && streams_.front()->state_.remote_complete_) {
read_callbacks_->connection().readDisable(true);
}
}
} while (redispatch);
return Network::FilterStatus::StopIteration;
}
void ConnectionManagerImpl::resetAllStreams() {
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);
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) {
stats_.named_.downstream_cx_destroy_remote_.inc();
}
if (event == Network::ConnectionEvent::RemoteClose ||
event == Network::ConnectionEvent::LocalClose) {
if (connection_idle_timer_) {
connection_idle_timer_->disableTimer();
connection_idle_timer_.reset();
}
if (drain_timer_) {
drain_timer_->disableTimer();
drain_timer_.reset();
}
}
if (!streams_.empty()) {
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);
resetAllStreams();
}
}
void ConnectionManagerImpl::onGoAway() {
// 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.
read_callbacks_->connection().close(Network::ConnectionCloseType::FlushWrite);
} else if (drain_state_ == DrainState::NotDraining) {
startDrainSequence();
}
}
void ConnectionManagerImpl::onDrainTimeout() {
ASSERT(drain_state_ != DrainState::NotDraining);
codec_->goAway();
drain_state_ = DrainState::Closing;
checkForDeferredClose();
}
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::NotTraceableRequestId:
tracing_stats.not_traceable_.inc();
break;
case Tracing::Reason::Sampling:
tracing_stats.random_sampling_.inc();
break;
case Tracing::Reason::ServiceForced:
tracing_stats.service_forced_.inc();
break;
default:
throw std::invalid_argument(
fmt::format("invalid tracing reason, value: {}", static_cast<int32_t>(tracing_reason)));
}
}
ConnectionManagerImpl::ActiveStream::ActiveStream(ConnectionManagerImpl& connection_manager)
: connection_manager_(connection_manager),
stream_id_(connection_manager.random_generator_.random()),
request_response_timespan_(new Stats::Timespan(
connection_manager_.stats_.named_.downstream_rq_time_, connection_manager_.timeSource())),
stream_info_(connection_manager_.codec_->protocol(), connection_manager_.timeSource()),
upstream_options_(std::make_shared<Network::Socket::Options>()) {
// For Server::Admin, no routeConfigProvider or SRDS route provider is used.
ASSERT(dynamic_cast<Server::Admin*>(&connection_manager_.config_) != nullptr ||
((connection_manager.config_.routeConfigProvider() == nullptr &&
connection_manager.config_.scopedRouteConfigProvider() != nullptr) ||
(connection_manager.config_.routeConfigProvider() != nullptr &&
connection_manager.config_.scopedRouteConfigProvider() == nullptr)),
"Either routeConfigProvider or scopedRouteConfigProvider should be set in "
"ConnectionManagerImpl.");
if (connection_manager.config_.routeConfigProvider() != nullptr) {
snapped_route_config_ = connection_manager.config_.routeConfigProvider()->config();
} else if (connection_manager.config_.scopedRouteConfigProvider() != nullptr) {
snapped_scoped_routes_config_ =
connection_manager_.config_.scopedRouteConfigProvider()->config<Router::ScopedConfig>();
ASSERT(snapped_scoped_routes_config_ != nullptr,
"Scoped rds provider returns null for scoped routes config.");
}
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 {
connection_manager_.stats_.named_.downstream_rq_http1_total_.inc();
}
stream_info_.setDownstreamLocalAddress(
connection_manager_.read_callbacks_->connection().localAddress());
stream_info_.setDownstreamDirectRemoteAddress(
connection_manager_.read_callbacks_->connection().remoteAddress());
// Initially, the downstream remote address is the source address of the
// downstream connection. That can change later in the request's lifecycle,
// based on XFF processing, but setting the downstream remote address here
// prevents surprises for logging code in edge cases.
stream_info_.setDownstreamRemoteAddress(
connection_manager_.read_callbacks_->connection().remoteAddress());
stream_info_.setDownstreamSslConnection(connection_manager_.read_callbacks_->connection().ssl());
if (connection_manager_.config_.streamIdleTimeout().count()) {
idle_timeout_ms_ = connection_manager_.config_.streamIdleTimeout();
stream_idle_timer_ = connection_manager_.read_callbacks_->connection().dispatcher().createTimer(
[this]() -> void { onIdleTimeout(); });
resetIdleTimer();
}
if (connection_manager_.config_.requestTimeout().count()) {
std::chrono::milliseconds request_timeout_ms_ = connection_manager_.config_.requestTimeout();
request_timer_ = connection_manager.read_callbacks_->connection().dispatcher().createTimer(
[this]() -> void { onRequestTimeout(); });
request_timer_->enableTimer(request_timeout_ms_, this);
}
stream_info_.setRequestedServerName(
connection_manager_.read_callbacks_->connection().requestedServerName());
}
ConnectionManagerImpl::ActiveStream::~ActiveStream() {
stream_info_.onRequestComplete();
// A downstream disconnect can be identified for HTTP requests when the upstream returns with a 0
// response code and when no other response flags are set.
if (!stream_info_.hasAnyResponseFlag() && !stream_info_.responseCode()) {
stream_info_.setResponseFlag(StreamInfo::ResponseFlag::DownstreamConnectionTermination);
}
connection_manager_.stats_.named_.downstream_rq_active_.dec();
for (const AccessLog::InstanceSharedPtr& access_log : connection_manager_.config_.accessLogs()) {
access_log->log(request_headers_.get(), response_headers_.get(), response_trailers_.get(),
stream_info_);
}
for (const auto& log_handler : access_log_handlers_) {
log_handler->log(request_headers_.get(), response_headers_.get(), response_trailers_.get(),
stream_info_);
}
if (stream_info_.healthCheck()) {
connection_manager_.config_.tracingStats().health_check_.inc();
}
if (active_span_) {
Tracing::HttpTracerUtility::finalizeSpan(*active_span_, request_headers_.get(),
response_headers_.get(), response_trailers_.get(),
stream_info_, *this);
}
if (state_.successful_upgrade_) {
connection_manager_.stats_.named_.downstream_cx_upgrades_active_.dec();
}
ASSERT(state_.filter_call_state_ == 0);
}
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();
// If headers have not been sent to the user, send a 408.
if (response_headers_ != nullptr) {
// TODO(htuch): We could send trailers here with an x-envoy timeout header
// or gRPC status code, and/or set H2 RST_STREAM error.
connection_manager_.doEndStream(*this);
} else {
stream_info_.setResponseFlag(StreamInfo::ResponseFlag::StreamIdleTimeout);
sendLocalReply(request_headers_ != nullptr &&
Grpc::Common::hasGrpcContentType(*request_headers_),
Http::Code::RequestTimeout, "stream timeout", nullptr, is_head_request_,
absl::nullopt, StreamInfo::ResponseCodeDetails::get().StreamIdleTimeout);
}
}
void ConnectionManagerImpl::ActiveStream::onRequestTimeout() {
connection_manager_.stats_.named_.downstream_rq_timeout_.inc();
sendLocalReply(request_headers_ != nullptr && Grpc::Common::hasGrpcContentType(*request_headers_),
Http::Code::RequestTimeout, "request timeout", nullptr, is_head_request_,
absl::nullopt, StreamInfo::ResponseCodeDetails::get().RequestOverallTimeout);
}
void ConnectionManagerImpl::ActiveStream::addStreamDecoderFilterWorker(
StreamDecoderFilterSharedPtr filter, bool dual_filter) {
ActiveStreamDecoderFilterPtr wrapper(new ActiveStreamDecoderFilter(*this, filter, dual_filter));
filter->setDecoderFilterCallbacks(*wrapper);
wrapper->moveIntoListBack(std::move(wrapper), decoder_filters_);
}
void ConnectionManagerImpl::ActiveStream::addStreamEncoderFilterWorker(
StreamEncoderFilterSharedPtr filter, bool dual_filter) {
ActiveStreamEncoderFilterPtr wrapper(new ActiveStreamEncoderFilter(*this, filter, dual_filter));
filter->setEncoderFilterCallbacks(*wrapper);
wrapper->moveIntoList(std::move(wrapper), encoder_filters_);
}
void ConnectionManagerImpl::ActiveStream::addAccessLogHandler(
AccessLog::InstanceSharedPtr handler) {
access_log_handlers_.push_back(handler);
}
void ConnectionManagerImpl::ActiveStream::chargeStats(const HeaderMap& headers) {
uint64_t response_code = Utility::getResponseStatus(headers);
stream_info_.response_code_ = response_code;
if (stream_info_.health_check_request_) {
return;
}
connection_manager_.stats_.named_.downstream_rq_completed_.inc();
connection_manager_.listener_stats_.downstream_rq_completed_.inc();
if (CodeUtility::is1xx(response_code)) {
connection_manager_.stats_.named_.downstream_rq_1xx_.inc();
connection_manager_.listener_stats_.downstream_rq_1xx_.inc();
} else if (CodeUtility::is2xx(response_code)) {
connection_manager_.stats_.named_.downstream_rq_2xx_.inc();
connection_manager_.listener_stats_.downstream_rq_2xx_.inc();
} else if (CodeUtility::is3xx(response_code)) {
connection_manager_.stats_.named_.downstream_rq_3xx_.inc();
connection_manager_.listener_stats_.downstream_rq_3xx_.inc();
} else if (CodeUtility::is4xx(response_code)) {
connection_manager_.stats_.named_.downstream_rq_4xx_.inc();
connection_manager_.listener_stats_.downstream_rq_4xx_.inc();
} else if (CodeUtility::is5xx(response_code)) {
connection_manager_.stats_.named_.downstream_rq_5xx_.inc();
connection_manager_.listener_stats_.downstream_rq_5xx_.inc();
}
}
const Network::Connection* ConnectionManagerImpl::ActiveStream::connection() {
return &connection_manager_.read_callbacks_->connection();
}
// Ordering in this function is complicated, but important.
//
// We want to do minimal work before selecting route and creating a filter
// chain to maximize the number of requests which get custom filter behavior,
// e.g. registering access logging.
//
// This must be balanced by doing sanity checking for invalid requests (one
// can't route select properly without full headers), checking state required to
// serve error responses (connection close, head requests, etc), and
// modifications which may themselves affect route selection.
//
// TODO(alyssawilk) all the calls here should be audited for order priority,
// e.g. many early returns do not currently handle connection: close properly.
void ConnectionManagerImpl::ActiveStream::decodeHeaders(HeaderMapPtr&& headers, bool end_stream) {
ScopeTrackerScopeState scope(this,
connection_manager_.read_callbacks_->connection().dispatcher());
request_headers_ = std::move(headers);
// For Admin thread, we don't use routeConfigProvider or SRDS route provider.
if (dynamic_cast<Server::Admin*>(&connection_manager_.config_) == nullptr &&
connection_manager_.config_.scopedRouteConfigProvider() != nullptr) {
ASSERT(snapped_route_config_ == nullptr,
"Route config already latched to the active stream when scoped RDS is enabled.");
// We need to snap snapped_route_config_ here as it's used in mutateRequestHeaders later.
snapScopedRouteConfig();
}
if (Http::Headers::get().MethodValues.Head ==
request_headers_->Method()->value().getStringView()) {
is_head_request_ = true;
}
ENVOY_STREAM_LOG(debug, "request headers complete (end_stream={}):\n{}", *this, end_stream,
*request_headers_);
// We end the decode here only if the request is header only. If we convert the request to a
// header only, the stream will be marked as done once a subsequent decodeData/decodeTrailers is
// called with end_stream=true.
maybeEndDecode(end_stream);
// Drop new requests when overloaded as soon as we have decoded the headers.
if (connection_manager_.overload_stop_accepting_requests_ref_ ==
Server::OverloadActionState::Active) {
// In this one special case, do not create the filter chain. If there is a risk of memory
// overload it is more important to avoid unnecessary allocation than to create the filters.
state_.created_filter_chain_ = true;
connection_manager_.stats_.named_.downstream_rq_overload_close_.inc();
sendLocalReply(Grpc::Common::hasGrpcContentType(*request_headers_),
Http::Code::ServiceUnavailable, "envoy overloaded", nullptr, is_head_request_,
absl::nullopt, StreamInfo::ResponseCodeDetails::get().Overload);
return;
}
if (!connection_manager_.config_.proxy100Continue() && request_headers_->Expect() &&
request_headers_->Expect()->value() == Headers::get().ExpectValues._100Continue.c_str()) {
// Note in the case Envoy is handling 100-Continue complexity, it skips the filter chain
// and sends the 100-Continue directly to the encoder.
chargeStats(continueHeader());
response_encoder_->encode100ContinueHeaders(continueHeader());
// Remove the Expect header so it won't be handled again upstream.
request_headers_->removeExpect();
}
connection_manager_.user_agent_.initializeFromHeaders(
*request_headers_, connection_manager_.stats_.prefix_, connection_manager_.stats_.scope_);
// Make sure we are getting a codec version we support.
Protocol protocol = connection_manager_.codec_->protocol();
if (protocol == Protocol::Http10) {
// Assume this is HTTP/1.0. This is fine for HTTP/0.9 but this code will also affect any
// requests with non-standard version numbers (0.9, 1.3), basically anything which is not
// HTTP/1.1.
//
// The protocol may have shifted in the HTTP/1.0 case so reset it.
stream_info_.protocol(protocol);
if (!connection_manager_.config_.http1Settings().accept_http_10_) {
// Send "Upgrade Required" if HTTP/1.0 support is not explicitly configured on.
sendLocalReply(false, Code::UpgradeRequired, "", nullptr, is_head_request_, absl::nullopt,
StreamInfo::ResponseCodeDetails::get().LowVersion);
return;
} else {
// HTTP/1.0 defaults to single-use connections. Make sure the connection
// will be closed unless Keep-Alive is present.
state_.saw_connection_close_ = true;
if (request_headers_->Connection() &&
absl::EqualsIgnoreCase(request_headers_->Connection()->value().getStringView(),
Http::Headers::get().ConnectionValues.KeepAlive)) {
state_.saw_connection_close_ = false;
}
}
}
if (!request_headers_->Host()) {
if ((protocol == Protocol::Http10) &&
!connection_manager_.config_.http1Settings().default_host_for_http_10_.empty()) {
// Add a default host if configured to do so.
request_headers_->insertHost().value(
connection_manager_.config_.http1Settings().default_host_for_http_10_);
} else {
// Require host header. For HTTP/1.1 Host has already been translated to :authority.
sendLocalReply(Grpc::Common::hasGrpcContentType(*request_headers_), Code::BadRequest, "",
nullptr, is_head_request_, absl::nullopt,
StreamInfo::ResponseCodeDetails::get().MissingHost);
return;
}
}
ASSERT(connection_manager_.config_.maxRequestHeadersKb() > 0);
if (request_headers_->byteSize() > (connection_manager_.config_.maxRequestHeadersKb() * 1024)) {
sendLocalReply(Grpc::Common::hasGrpcContentType(*request_headers_),
Code::RequestHeaderFieldsTooLarge, "", nullptr, is_head_request_, absl::nullopt,
StreamInfo::ResponseCodeDetails::get().RequestHeadersTooLarge);
return;
}
// Currently we only support relative paths at the application layer. We expect the codec to have
// broken the path into pieces if applicable. NOTE: Currently the HTTP/1.1 codec only does this
// when the allow_absolute_url flag is enabled on the HCM.
// https://tools.ietf.org/html/rfc7230#section-5.3 We also need to check for the existence of
// :path because CONNECT does not have a path, and we don't support that currently.
if (!request_headers_->Path() || request_headers_->Path()->value().getStringView().empty() ||
request_headers_->Path()->value().getStringView()[0] != '/') {
const bool has_path =
request_headers_->Path() && !request_headers_->Path()->value().getStringView().empty();
connection_manager_.stats_.named_.downstream_rq_non_relative_path_.inc();
sendLocalReply(Grpc::Common::hasGrpcContentType(*request_headers_), Code::NotFound, "", nullptr,
is_head_request_, absl::nullopt,
has_path ? StreamInfo::ResponseCodeDetails::get().AbsolutePath
: StreamInfo::ResponseCodeDetails::get().MissingPath);
return;
}
// Path sanitization should happen before any path access other than the above sanity check.
if (!ConnectionManagerUtility::maybeNormalizePath(*request_headers_,
connection_manager_.config_)) {
sendLocalReply(Grpc::Common::hasGrpcContentType(*request_headers_), Code::BadRequest, "",
nullptr, is_head_request_, absl::nullopt,
StreamInfo::ResponseCodeDetails::get().PathNormalizationFailed);
return;
}
if (protocol == Protocol::Http11 && request_headers_->Connection() &&
absl::EqualsIgnoreCase(request_headers_->Connection()->value().getStringView(),
Http::Headers::get().ConnectionValues.Close)) {
state_.saw_connection_close_ = true;
}
// Note: Proxy-Connection is not a standard header, but is supported here
// since it is supported by http-parser the underlying parser for http
// requests.
if (protocol != Protocol::Http2 && !state_.saw_connection_close_ &&
request_headers_->ProxyConnection() &&
absl::EqualsIgnoreCase(request_headers_->ProxyConnection()->value().getStringView(),
Http::Headers::get().ConnectionValues.Close)) {
state_.saw_connection_close_ = true;
}
if (!state_.is_internally_created_) { // Only sanitize headers on first pass.
// Modify the downstream remote address depending on configuration and headers.
stream_info_.setDownstreamRemoteAddress(ConnectionManagerUtility::mutateRequestHeaders(
*request_headers_, connection_manager_.read_callbacks_->connection(),
connection_manager_.config_, *snapped_route_config_, connection_manager_.random_generator_,
connection_manager_.local_info_));
}
ASSERT(stream_info_.downstreamRemoteAddress() != nullptr);
ASSERT(!cached_route_);
refreshCachedRoute();
if (!state_.is_internally_created_) { // Only mutate tracing headers on first pass.
ConnectionManagerUtility::mutateTracingRequestHeader(
*request_headers_, connection_manager_.runtime_, connection_manager_.config_,
cached_route_.value().get());
}
const bool upgrade_rejected = createFilterChain() == false;
// TODO if there are no filters when starting a filter iteration, the connection manager
// should return 404. The current returns no response if there is no router filter.
if (protocol == Protocol::Http11 && hasCachedRoute()) {
if (upgrade_rejected) {
// Do not allow upgrades if the route does not support it.
connection_manager_.stats_.named_.downstream_rq_ws_on_non_ws_route_.inc();
sendLocalReply(Grpc::Common::hasGrpcContentType(*request_headers_), Code::Forbidden, "",
nullptr, is_head_request_, absl::nullopt,
StreamInfo::ResponseCodeDetails::get().UpgradeFailed);
return;
}
// Allow non websocket requests to go through websocket enabled routes.
}
if (hasCachedRoute()) {
const Router::RouteEntry* route_entry = cached_route_.value()->routeEntry();
if (route_entry != nullptr && route_entry->idleTimeout()) {
idle_timeout_ms_ = route_entry->idleTimeout().value();
if (idle_timeout_ms_.count()) {
// If we have a route-level idle timeout but no global stream idle timeout, create a timer.
if (stream_idle_timer_ == nullptr) {
stream_idle_timer_ =
connection_manager_.read_callbacks_->connection().dispatcher().createTimer(
[this]() -> void { onIdleTimeout(); });
}
} else if (stream_idle_timer_ != nullptr) {
// If we had a global stream idle timeout but the route-level idle timeout is set to zero
// (to override), we disable the idle timer.
stream_idle_timer_->disableTimer();
stream_idle_timer_ = nullptr;
}
}
}
// Check if tracing is enabled at all.
if (connection_manager_.config_.tracingConfig()) {
traceRequest();
}
decodeHeaders(nullptr, *request_headers_, end_stream);
// Reset it here for both global and overridden cases.
resetIdleTimer();
}
void ConnectionManagerImpl::ActiveStream::traceRequest() {
Tracing::Decision tracing_decision =
Tracing::HttpTracerUtility::isTracing(stream_info_, *request_headers_);
ConnectionManagerImpl::chargeTracingStats(tracing_decision.reason,
connection_manager_.config_.tracingStats());
active_span_ = connection_manager_.tracer().startSpan(*this, *request_headers_, stream_info_,
tracing_decision);
if (!active_span_) {
return;
}
// TODO: Need to investigate the following code based on the cached route, as may
// be broken in the case a filter changes the route.
// If a decorator has been defined, apply it to the active span.
if (hasCachedRoute() && cached_route_.value()->decorator()) {
cached_route_.value()->decorator()->apply(*active_span_);
// Cache decorated operation.
if (!cached_route_.value()->decorator()->getOperation().empty()) {
decorated_operation_ = &cached_route_.value()->decorator()->getOperation();
}
}
if (connection_manager_.config_.tracingConfig()->operation_name_ ==
Tracing::OperationName::Egress) {
// For egress (outbound) requests, pass the decorator's operation name (if defined)
// as a request header to enable the receiving service to use it in its server span.
if (decorated_operation_) {
request_headers_->insertEnvoyDecoratorOperation().value(*decorated_operation_);
}
} else {
const HeaderEntry* req_operation_override = request_headers_->EnvoyDecoratorOperation();
// For ingress (inbound) requests, if a decorator operation name has been provided, it
// should be used to override the active span's operation.
if (req_operation_override) {
if (!req_operation_override->value().empty()) {
active_span_->setOperation(req_operation_override->value().getStringView());
// Clear the decorated operation so won't be used in the response header, as
// it has been overridden by the inbound decorator operation request header.
decorated_operation_ = nullptr;
}
// Remove header so not propagated to service
request_headers_->removeEnvoyDecoratorOperation();
}
}
}
void ConnectionManagerImpl::ActiveStream::decodeHeaders(ActiveStreamDecoderFilter* filter,
HeaderMap& headers, bool end_stream) {
// Headers filter iteration should always start with the next filter if available.
std::list<ActiveStreamDecoderFilterPtr>::iterator entry =
commonDecodePrefix(filter, FilterIterationStartState::AlwaysStartFromNext);
std::list<ActiveStreamDecoderFilterPtr>::iterator continue_data_entry = decoder_filters_.end();
for (; entry != decoder_filters_.end(); entry++) {
ASSERT(!(state_.filter_call_state_ & FilterCallState::DecodeHeaders));
state_.filter_call_state_ |= FilterCallState::DecodeHeaders;
(*entry)->end_stream_ =
decoding_headers_only_ || (end_stream && continue_data_entry == decoder_filters_.end());
FilterHeadersStatus status = (*entry)->decodeHeaders(headers, (*entry)->end_stream_);
ASSERT(!(status == FilterHeadersStatus::ContinueAndEndStream && (*entry)->end_stream_));
state_.filter_call_state_ &= ~FilterCallState::DecodeHeaders;
ENVOY_STREAM_LOG(trace, "decode headers called: filter={} status={}", *this,
static_cast<const void*>((*entry).get()), static_cast<uint64_t>(status));
const bool new_metadata_added = processNewlyAddedMetadata();
// If end_stream is set in headers, and a filter adds new metadata, we need to delay end_stream
// in headers by inserting an empty data frame with end_stream set. The empty data frame is sent
// after the new metadata.
if ((*entry)->end_stream_ && new_metadata_added && !buffered_request_data_) {
Buffer::OwnedImpl empty_data("");
ENVOY_STREAM_LOG(
trace, "inserting an empty data frame for end_stream due metadata being added.", *this);
// Metadata frame doesn't carry end of stream bit. We need an empty data frame to end the
// stream.
addDecodedData(*((*entry).get()), empty_data, true);
}
(*entry)->decode_headers_called_ = true;
if (!(*entry)->commonHandleAfterHeadersCallback(status, decoding_headers_only_) &&
std::next(entry) != decoder_filters_.end()) {
// Stop iteration IFF this is not the last filter. If it is the last filter, continue with
// processing since we need to handle the case where a terminal filter wants to buffer, but
// a previous filter has added body.
return;
}
// Here we handle the case where we have a header only request, but a filter adds a body
// to it. We need to not raise end_stream = true to further filters during inline iteration.
if (end_stream && buffered_request_data_ && continue_data_entry == decoder_filters_.end()) {
continue_data_entry = entry;
}
}
if (continue_data_entry != decoder_filters_.end()) {
// We use the continueDecoding() code since it will correctly handle not calling
// decodeHeaders() again. Fake setting StopSingleIteration since the continueDecoding() code
// expects it.
ASSERT(buffered_request_data_);
(*continue_data_entry)->iteration_state_ =
ActiveStreamFilterBase::IterationState::StopSingleIteration;
(*continue_data_entry)->continueDecoding();
}
if (end_stream) {
disarmRequestTimeout();
}
}
void ConnectionManagerImpl::ActiveStream::decodeData(Buffer::Instance& data, bool end_stream) {
ScopeTrackerScopeState scope(this,
connection_manager_.read_callbacks_->connection().dispatcher());
maybeEndDecode(end_stream);
stream_info_.addBytesReceived(data.length());
decodeData(nullptr, data, end_stream, FilterIterationStartState::CanStartFromCurrent);
}
void ConnectionManagerImpl::ActiveStream::decodeData(
ActiveStreamDecoderFilter* filter, Buffer::Instance& data, bool end_stream,
FilterIterationStartState filter_iteration_start_state) {
ScopeTrackerScopeState scope(this,
connection_manager_.read_callbacks_->connection().dispatcher());
resetIdleTimer();
// If we previously decided to decode only the headers, do nothing here.
if (decoding_headers_only_) {
return;
}
// If a response is complete or a reset has been sent, filters do not care about further body
// data. Just drop it.
if (state_.local_complete_) {
return;
}
auto trailers_added_entry = decoder_filters_.end();
const bool trailers_exists_at_start = request_trailers_ != nullptr;
// Filter iteration may start at the current filter.
std::list<ActiveStreamDecoderFilterPtr>::iterator entry =
commonDecodePrefix(filter, filter_iteration_start_state);
for (; entry != decoder_filters_.end(); entry++) {
// If the filter pointed by entry has stopped for all frame types, return now.
if (handleDataIfStopAll(**entry, data, state_.decoder_filters_streaming_)) {
return;
}
// If end_stream_ is marked for a filter, the data is not for this filter and filters after.
//
// In following case, ActiveStreamFilterBase::commonContinue() could be called recursively and
// its doData() is called with wrong data.
//
// There are 3 decode filters and "wrapper" refers to ActiveStreamFilter object.
//
// filter0->decodeHeaders(_, true)
// return STOP
// filter0->continueDecoding()
// wrapper0->commonContinue()
// wrapper0->decodeHeaders(_, _, true)
// filter1->decodeHeaders(_, true)