forked from envoyproxy/envoy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
buffer_accounting_integration_test.cc
1681 lines (1408 loc) · 69.2 KB
/
buffer_accounting_integration_test.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 <sstream>
#include <vector>
#include "envoy/config/bootstrap/v3/bootstrap.pb.h"
#include "envoy/config/cluster/v3/cluster.pb.h"
#include "envoy/extensions/filters/network/http_connection_manager/v3/http_connection_manager.pb.h"
#include "envoy/network/address.h"
#include "source/common/buffer/buffer_impl.h"
#include "test/integration/autonomous_upstream.h"
#include "test/integration/base_overload_integration_test.h"
#include "test/integration/filters/tee_filter.h"
#include "test/integration/http_protocol_integration.h"
#include "test/integration/tracked_watermark_buffer.h"
#include "test/integration/utility.h"
#include "test/mocks/http/mocks.h"
#include "test/test_common/test_runtime.h"
#include "fake_upstream.h"
#include "gtest/gtest.h"
#include "http_integration.h"
#include "integration_stream_decoder.h"
#include "socket_interface_swap.h"
namespace Envoy {
namespace {
#if defined(__has_feature)
#if __has_feature(address_sanitizer)
#define ASANITIZED /* Sanitized by Clang */
#endif
#endif
#if defined(__SANITIZE_ADDRESS__)
#define ASANITIZED /* Sanitized by GCC */
#endif
using testing::HasSubstr;
std::string protocolTestParamsAndBoolToString(
const ::testing::TestParamInfo<std::tuple<HttpProtocolTestParams, bool>>& params) {
return fmt::format("{}_{}",
HttpProtocolIntegrationTest::protocolTestParamsToString(
::testing::TestParamInfo<HttpProtocolTestParams>(std::get<0>(params.param),
/*an_index=*/0)),
std::get<1>(params.param) ? "with_per_stream_buffer_accounting"
: "without_per_stream_buffer_accounting");
}
void runOnWorkerThreadsAndWaitforCompletion(Server::Instance& server, std::function<void()> func) {
absl::Notification done_notification;
ThreadLocal::TypedSlotPtr<> slot;
Envoy::Thread::ThreadId main_tid;
server.dispatcher().post([&] {
slot = ThreadLocal::TypedSlot<>::makeUnique(server.threadLocal());
slot->set(
[](Envoy::Event::Dispatcher&) -> std::shared_ptr<Envoy::ThreadLocal::ThreadLocalObject> {
return nullptr;
});
main_tid = server.api().threadFactory().currentThreadId();
slot->runOnAllThreads(
[main_tid, &server, &func](OptRef<ThreadLocal::ThreadLocalObject>) {
// Run on the worker thread.
if (server.api().threadFactory().currentThreadId() != main_tid) {
func();
}
},
[&slot, &done_notification] {
slot.reset(nullptr);
done_notification.Notify();
});
});
done_notification.WaitForNotification();
}
void waitForNumTurns(std::vector<uint64_t>& turns, absl::Mutex& mu, uint32_t expected_size) {
absl::MutexLock l(&mu);
auto check_data_in_connection_output_buffer = [&turns, &mu, expected_size]() {
mu.AssertHeld();
return turns.size() == expected_size;
};
ASSERT_TRUE(mu.AwaitWithTimeout(absl::Condition(&check_data_in_connection_output_buffer),
absl::FromChrono(TestUtility::DefaultTimeout)))
<< "Turns:" << absl::StrJoin(turns, ",") << std::endl;
}
} // namespace
class Http2BufferWatermarksTest
: public SocketInterfaceSwap,
public testing::TestWithParam<std::tuple<HttpProtocolTestParams, bool>>,
public HttpIntegrationTest {
public:
std::vector<IntegrationStreamDecoderPtr>
sendRequests(uint32_t num_responses, uint32_t request_body_size, uint32_t response_body_size,
absl::string_view cluster_to_wait_for = "") {
std::vector<IntegrationStreamDecoderPtr> responses;
Http::TestRequestHeaderMapImpl header_map{
{"response_data_blocks", absl::StrCat(1)},
{"response_size_bytes", absl::StrCat(response_body_size)},
{"no_trailers", "0"}};
header_map.copyFrom(default_request_headers_);
header_map.setContentLength(request_body_size);
for (uint32_t idx = 0; idx < num_responses; ++idx) {
responses.emplace_back(codec_client_->makeRequestWithBody(header_map, request_body_size));
if (!cluster_to_wait_for.empty()) {
test_server_->waitForGaugeEq(
absl::StrCat("cluster.", cluster_to_wait_for, ".upstream_rq_active"), idx + 1);
}
}
return responses;
}
Http2BufferWatermarksTest()
: HttpIntegrationTest(
std::get<0>(GetParam()).downstream_protocol, std::get<0>(GetParam()).version,
ConfigHelper::httpProxyConfig(
/*downstream_is_quic=*/std::get<0>(GetParam()).downstream_protocol ==
Http::CodecType::HTTP3)) {
// This test tracks the number of buffers created, and the tag extraction check uses some
// buffers, so disable it in this test.
skip_tag_extraction_rule_check_ = true;
if (streamBufferAccounting()) {
buffer_factory_ =
std::make_shared<Buffer::TrackedWatermarkBufferFactory>(absl::bit_width(4096u));
} else {
buffer_factory_ = std::make_shared<Buffer::TrackedWatermarkBufferFactory>();
}
const HttpProtocolTestParams& protocol_test_params = std::get<0>(GetParam());
setupHttp1ImplOverrides(protocol_test_params.http1_implementation);
setupHttp2ImplOverrides(protocol_test_params.http2_implementation);
config_helper_.addRuntimeOverride(
Runtime::defer_processing_backedup_streams,
protocol_test_params.defer_processing_backedup_streams ? "true" : "false");
setServerBufferFactory(buffer_factory_);
setUpstreamProtocol(protocol_test_params.upstream_protocol);
}
protected:
// For testing purposes, track >= 4096B accounts.
std::shared_ptr<Buffer::TrackedWatermarkBufferFactory> buffer_factory_;
bool streamBufferAccounting() { return std::get<1>(GetParam()); }
bool deferProcessingBackedUpStreams() {
return Runtime::runtimeFeatureEnabled(Runtime::defer_processing_backedup_streams);
}
std::string printAccounts() {
std::stringstream stream;
auto print_map =
[&stream](Buffer::TrackedWatermarkBufferFactory::AccountToBoundBuffersMap& map) {
stream << "Printing Account map. Size: " << map.size() << '\n';
for (auto& entry : map) {
// This runs in the context of the worker thread, so we can access
// the balance.
stream << " Account: " << entry.first << '\n';
stream << " Balance:"
<< static_cast<Buffer::BufferMemoryAccountImpl*>(entry.first.get())->balance()
<< '\n';
stream << " Number of associated buffers: " << entry.second.size() << '\n';
}
};
buffer_factory_->inspectAccounts(print_map, test_server_->server());
return stream.str();
}
};
// Run the tests using HTTP2 only since its the only protocol that's fully
// supported.
// TODO(kbaichoo): Instantiate with H3 and H1 as well when their buffers are
// bounded to accounts.
INSTANTIATE_TEST_SUITE_P(
IpVersions, Http2BufferWatermarksTest,
testing::Combine(testing::ValuesIn(HttpProtocolIntegrationTest::getProtocolTestParams(
{Http::CodecType::HTTP2}, {FakeHttpConnection::Type::HTTP2})),
testing::Bool()),
protocolTestParamsAndBoolToString);
// We should create four buffers each billing the same downstream request's
// account which originated the chain.
TEST_P(Http2BufferWatermarksTest, ShouldCreateFourBuffersPerAccount) {
FakeStreamPtr upstream_request1;
FakeStreamPtr upstream_request2;
default_request_headers_.setContentLength(1000);
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
// Sends the first request.
auto response1 = codec_client_->makeRequestWithBody(default_request_headers_, 1000);
waitForNextUpstreamRequest();
upstream_request1 = std::move(upstream_request_);
// Check the expected number of buffers per account
if (streamBufferAccounting()) {
EXPECT_TRUE(buffer_factory_->waitUntilExpectedNumberOfAccountsAndBoundBuffers(1, 4));
} else {
EXPECT_TRUE(buffer_factory_->waitUntilExpectedNumberOfAccountsAndBoundBuffers(0, 0));
}
// Send the second request.
auto response2 = codec_client_->makeRequestWithBody(default_request_headers_, 1000);
waitForNextUpstreamRequest();
upstream_request2 = std::move(upstream_request_);
// Check the expected number of buffers per account
if (streamBufferAccounting()) {
EXPECT_TRUE(buffer_factory_->waitUntilExpectedNumberOfAccountsAndBoundBuffers(2, 8));
} else {
EXPECT_TRUE(buffer_factory_->waitUntilExpectedNumberOfAccountsAndBoundBuffers(0, 0));
}
// Respond to the first request and wait for complete
upstream_request1->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, false);
upstream_request1->encodeData(1000, true);
ASSERT_TRUE(response1->waitForEndStream());
ASSERT_TRUE(upstream_request1->complete());
// Check the expected number of buffers per account
if (streamBufferAccounting()) {
// Wait for a short period less than the request timeout time.
EXPECT_TRUE(buffer_factory_->waitUntilExpectedNumberOfAccountsAndBoundBuffers(
1, 4, std::chrono::milliseconds(2000)));
} else {
EXPECT_TRUE(buffer_factory_->waitUntilExpectedNumberOfAccountsAndBoundBuffers(0, 0));
}
// Respond to the second request and wait for complete
upstream_request2->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, false);
upstream_request2->encodeData(1000, true);
ASSERT_TRUE(response2->waitForEndStream());
ASSERT_TRUE(upstream_request2->complete());
// Check the expected number of buffers per account
EXPECT_TRUE(buffer_factory_->waitUntilExpectedNumberOfAccountsAndBoundBuffers(0, 0));
}
TEST_P(Http2BufferWatermarksTest, AccountsAndInternalRedirect) {
const Http::TestResponseHeaderMapImpl redirect_response{
{":status", "302"}, {"content-length", "0"}, {"location", "http://authority2/new/url"}};
auto handle = config_helper_.createVirtualHost("handle.internal.redirect");
handle.mutable_routes(0)->set_name("redirect");
handle.mutable_routes(0)->mutable_route()->mutable_internal_redirect_policy();
config_helper_.addVirtualHost(handle);
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
default_request_headers_.setHost("handle.internal.redirect");
IntegrationStreamDecoderPtr response =
codec_client_->makeHeaderOnlyRequest(default_request_headers_);
waitForNextUpstreamRequest();
if (streamBufferAccounting()) {
EXPECT_EQ(buffer_factory_->numAccountsCreated(), 1);
} else {
EXPECT_EQ(buffer_factory_->numAccountsCreated(), 0);
}
upstream_request_->encodeHeaders(redirect_response, true);
waitForNextUpstreamRequest();
upstream_request_->encodeHeaders(default_response_headers_, true);
ASSERT_TRUE(response->waitForEndStream());
ASSERT_TRUE(response->complete());
if (streamBufferAccounting()) {
EXPECT_EQ(buffer_factory_->numAccountsCreated(), 1) << printAccounts();
EXPECT_TRUE(buffer_factory_->waitForExpectedAccountUnregistered(1)) << printAccounts();
} else {
EXPECT_EQ(buffer_factory_->numAccountsCreated(), 0);
EXPECT_TRUE(buffer_factory_->waitForExpectedAccountUnregistered(0));
}
}
TEST_P(Http2BufferWatermarksTest, AccountsAndInternalRedirectWithRequestBody) {
const Http::TestResponseHeaderMapImpl redirect_response{
{":status", "302"}, {"content-length", "0"}, {"location", "http://authority2/new/url"}};
auto handle = config_helper_.createVirtualHost("handle.internal.redirect");
handle.mutable_routes(0)->set_name("redirect");
handle.mutable_routes(0)->mutable_route()->mutable_internal_redirect_policy();
config_helper_.addVirtualHost(handle);
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
default_request_headers_.setHost("handle.internal.redirect");
default_request_headers_.setMethod("POST");
const std::string request_body = "foobarbizbaz";
buffer_factory_->setExpectedAccountBalance(request_body.size(), 1);
IntegrationStreamDecoderPtr response =
codec_client_->makeRequestWithBody(default_request_headers_, request_body);
waitForNextUpstreamRequest();
upstream_request_->encodeHeaders(redirect_response, true);
waitForNextUpstreamRequest();
upstream_request_->encodeHeaders(default_response_headers_, true);
ASSERT_TRUE(response->waitForEndStream());
ASSERT_TRUE(response->complete());
if (streamBufferAccounting()) {
EXPECT_EQ(buffer_factory_->numAccountsCreated(), 1) << printAccounts();
EXPECT_TRUE(buffer_factory_->waitForExpectedAccountUnregistered(1)) << printAccounts();
EXPECT_TRUE(
buffer_factory_->waitForExpectedAccountBalanceWithTimeout(TestUtility::DefaultTimeout))
<< "buffer total: " << buffer_factory_->totalBufferSize()
<< " buffer max: " << buffer_factory_->maxBufferSize() << printAccounts();
} else {
EXPECT_EQ(buffer_factory_->numAccountsCreated(), 0);
EXPECT_TRUE(buffer_factory_->waitForExpectedAccountUnregistered(0));
}
}
TEST_P(Http2BufferWatermarksTest, ShouldTrackAllocatedBytesToUpstream) {
const int num_requests = 5;
const uint32_t request_body_size = 4096;
const uint32_t response_body_size = 4096;
autonomous_upstream_ = true;
autonomous_allow_incomplete_streams_ = true;
initialize();
buffer_factory_->setExpectedAccountBalance(request_body_size, num_requests);
// Makes us have Envoy's writes to upstream return EAGAIN
write_matcher_->setDestinationPort(fake_upstreams_[0]->localAddress()->ip()->port());
write_matcher_->setWriteReturnsEgain();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto responses = sendRequests(num_requests, request_body_size, response_body_size,
/*cluster_to_wait_for=*/"cluster_0");
// Wait for all requests to have accounted for the requests we've sent.
if (streamBufferAccounting()) {
EXPECT_TRUE(
buffer_factory_->waitForExpectedAccountBalanceWithTimeout(TestUtility::DefaultTimeout))
<< "buffer total: " << buffer_factory_->totalBufferSize()
<< " buffer max: " << buffer_factory_->maxBufferSize() << printAccounts();
}
write_matcher_->setResumeWrites();
for (auto& response : responses) {
ASSERT_TRUE(response->waitForEndStream());
ASSERT_TRUE(response->complete());
}
}
TEST_P(Http2BufferWatermarksTest, ShouldTrackAllocatedBytesToShadowUpstream) {
const int num_requests = 5;
const uint32_t request_body_size = 4096;
const uint32_t response_body_size = 4096;
TestScopedRuntime scoped_runtime;
scoped_runtime.mergeValues({{"envoy.reloadable_features.streaming_shadow", "true"}});
autonomous_upstream_ = true;
autonomous_allow_incomplete_streams_ = true;
setUpstreamCount(2);
config_helper_.addConfigModifier([](envoy::config::bootstrap::v3::Bootstrap& bootstrap) {
auto* cluster = bootstrap.mutable_static_resources()->add_clusters();
cluster->MergeFrom(bootstrap.static_resources().clusters()[0]);
cluster->set_name("cluster_1");
});
config_helper_.addConfigModifier(
[=](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager&
hcm) -> void {
auto* mirror_policy = hcm.mutable_route_config()
->mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->add_request_mirror_policies();
mirror_policy->set_cluster("cluster_1");
});
initialize();
buffer_factory_->setExpectedAccountBalance(request_body_size, num_requests);
// Makes us have Envoy's writes to shadow upstream return EAGAIN
write_matcher_->setDestinationPort(fake_upstreams_[1]->localAddress()->ip()->port());
write_matcher_->setWriteReturnsEgain();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto responses = sendRequests(num_requests, request_body_size, response_body_size,
/*cluster_to_wait_for=*/"cluster_1");
// The main request should complete.
for (auto& response : responses) {
ASSERT_TRUE(response->waitForEndStream());
ASSERT_TRUE(response->complete());
}
// Wait for all requests to have accounted for the requests we've sent.
if (streamBufferAccounting()) {
EXPECT_TRUE(
buffer_factory_->waitForExpectedAccountBalanceWithTimeout(TestUtility::DefaultTimeout))
<< "buffer total: " << buffer_factory_->totalBufferSize() << "\n"
<< " buffer max: " << buffer_factory_->maxBufferSize() << "\n"
<< printAccounts();
}
write_matcher_->setResumeWrites();
test_server_->waitForCounterEq("cluster.cluster_1.upstream_rq_completed", num_requests);
}
TEST_P(Http2BufferWatermarksTest, ShouldTrackAllocatedBytesToDownstream) {
const int num_requests = 5;
const uint32_t request_body_size = 4096;
const uint32_t response_body_size = 16384;
autonomous_upstream_ = true;
autonomous_allow_incomplete_streams_ = true;
initialize();
buffer_factory_->setExpectedAccountBalance(response_body_size, num_requests);
write_matcher_->setSourcePort(lookupPort("http"));
codec_client_ = makeHttpConnection(lookupPort("http"));
// Simulate TCP push back on the Envoy's downstream network socket, so that outbound frames
// start to accumulate in the transport socket buffer.
write_matcher_->setWriteReturnsEgain();
auto responses = sendRequests(num_requests, request_body_size, response_body_size);
// Wait for all requests to buffered the response from upstream.
if (streamBufferAccounting()) {
EXPECT_TRUE(
buffer_factory_->waitForExpectedAccountBalanceWithTimeout(TestUtility::DefaultTimeout))
<< "buffer total: " << buffer_factory_->totalBufferSize()
<< " buffer max: " << buffer_factory_->maxBufferSize() << printAccounts();
}
write_matcher_->setResumeWrites();
// Wait for streams to terminate.
for (auto& response : responses) {
ASSERT_TRUE(response->waitForEndStream());
ASSERT_TRUE(response->complete());
}
}
// Focuses on tests using the various codec. Currently, the accounting is only
// fully wired through with H2, but it's important to test that H1 and H3 end
// up notifying the BufferMemoryAccount when the dtor of the downstream stream
// occurs.
class ProtocolsBufferWatermarksTest
: public testing::TestWithParam<std::tuple<HttpProtocolTestParams, bool>>,
public HttpIntegrationTest {
public:
ProtocolsBufferWatermarksTest()
: HttpIntegrationTest(
std::get<0>(GetParam()).downstream_protocol, std::get<0>(GetParam()).version,
ConfigHelper::httpProxyConfig(
/*downstream_is_quic=*/std::get<0>(GetParam()).downstream_protocol ==
Http::CodecType::HTTP3)) {
// This test tracks the number of buffers created, and the tag extraction check uses some
// buffers, so disable it in this test.
skip_tag_extraction_rule_check_ = true;
if (streamBufferAccounting()) {
buffer_factory_ =
std::make_shared<Buffer::TrackedWatermarkBufferFactory>(absl::bit_width(4096u));
} else {
buffer_factory_ = std::make_shared<Buffer::TrackedWatermarkBufferFactory>();
}
const HttpProtocolTestParams& protocol_test_params = std::get<0>(GetParam());
setupHttp1ImplOverrides(protocol_test_params.http1_implementation);
setupHttp2ImplOverrides(protocol_test_params.http2_implementation);
setServerBufferFactory(buffer_factory_);
setUpstreamProtocol(protocol_test_params.upstream_protocol);
}
protected:
std::shared_ptr<Buffer::TrackedWatermarkBufferFactory> buffer_factory_;
bool streamBufferAccounting() { return std::get<1>(GetParam()); }
};
INSTANTIATE_TEST_SUITE_P(
IpVersions, ProtocolsBufferWatermarksTest,
testing::Combine(testing::ValuesIn(HttpProtocolIntegrationTest::getProtocolTestParams(
{Http::CodecType::HTTP1, Http::CodecType::HTTP2, Http::CodecType::HTTP3},
{FakeHttpConnection::Type::HTTP2})),
testing::Bool()),
protocolTestParamsAndBoolToString);
TEST_P(ProtocolsBufferWatermarksTest, AccountShouldBeRegisteredAndUnregisteredOnce) {
FakeStreamPtr upstream_request1;
default_request_headers_.setContentLength(1000);
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
// Sends the first request.
auto response1 = codec_client_->makeRequestWithBody(default_request_headers_, 1000);
waitForNextUpstreamRequest();
upstream_request1 = std::move(upstream_request_);
if (streamBufferAccounting()) {
EXPECT_EQ(buffer_factory_->numAccountsCreated(), 1);
} else {
EXPECT_EQ(buffer_factory_->numAccountsCreated(), 0);
}
upstream_request1->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, false);
upstream_request1->encodeData(1000, true);
ASSERT_TRUE(response1->waitForEndStream());
ASSERT_TRUE(upstream_request1->complete());
// Check single call to unregister if stream account, 0 otherwise
if (streamBufferAccounting()) {
EXPECT_TRUE(buffer_factory_->waitForExpectedAccountUnregistered(1));
} else {
EXPECT_TRUE(buffer_factory_->waitForExpectedAccountUnregistered(0));
}
}
TEST_P(ProtocolsBufferWatermarksTest, ResettingStreamUnregistersAccount) {
FakeStreamPtr upstream_request1;
default_request_headers_.setContentLength(1000);
// H1 on RST ends up leveraging idle timeout if no active stream on the
// connection.
config_helper_.setDownstreamHttpIdleTimeout(std::chrono::milliseconds(100));
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
// Sends the first request.
auto response1 = codec_client_->makeRequestWithBody(default_request_headers_, 1000);
waitForNextUpstreamRequest();
upstream_request1 = std::move(upstream_request_);
if (streamBufferAccounting()) {
EXPECT_EQ(buffer_factory_->numAccountsCreated(), 1);
} else {
EXPECT_EQ(buffer_factory_->numAccountsCreated(), 0);
}
if (streamBufferAccounting()) {
// Reset the downstream via the account interface on the worker thread.
EXPECT_EQ(buffer_factory_->numAccountsCreated(), 1);
Buffer::BufferMemoryAccountSharedPtr account;
auto& server = test_server_->server();
// Get access to the account.
buffer_factory_->inspectAccounts(
[&account](Buffer::TrackedWatermarkBufferFactory::AccountToBoundBuffersMap& map) {
for (auto& [acct, _] : map) {
account = acct;
}
},
server);
// Reset the stream from the worker.
runOnWorkerThreadsAndWaitforCompletion(server, [&account]() { account->resetDownstream(); });
if (std::get<0>(GetParam()).downstream_protocol == Http::CodecType::HTTP1) {
// For H1, we use idleTimeouts to cancel streams unless there was an
// explicit protocol error prior to sending a response to the downstream.
// Since that's not the case, the reset will fire twice, once due to
// overload manager, and once due to timeout which will close the
// connection.
ASSERT_TRUE(codec_client_->waitForDisconnect(std::chrono::milliseconds(10000)));
} else {
ASSERT_TRUE(response1->waitForReset());
EXPECT_EQ(response1->resetReason(), Http::StreamResetReason::RemoteReset);
}
// Wait for the upstream request to receive the reset to avoid a race when
// cleaning up the test.
ASSERT_TRUE(upstream_request1->waitForReset());
} else {
upstream_request1->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, false);
upstream_request1->encodeData(1000, true);
ASSERT_TRUE(response1->waitForEndStream());
ASSERT_TRUE(upstream_request1->complete());
}
// Check single call to unregister if stream account, 0 otherwise
if (streamBufferAccounting()) {
EXPECT_TRUE(buffer_factory_->waitForExpectedAccountUnregistered(1));
} else {
EXPECT_TRUE(buffer_factory_->waitForExpectedAccountUnregistered(0));
}
}
class Http2OverloadManagerIntegrationTest : public Http2BufferWatermarksTest,
public Envoy::BaseOverloadIntegrationTest {
protected:
void initializeOverloadManagerInBootstrap(
const envoy::config::overload::v3::OverloadAction& overload_action) {
setupOverloadManagerConfig(overload_action);
overload_manager_config_.mutable_buffer_factory_config()
->set_minimum_account_to_track_power_of_two(absl::bit_width(4096u));
config_helper_.addConfigModifier([this](envoy::config::bootstrap::v3::Bootstrap& bootstrap) {
*bootstrap.mutable_overload_manager() = this->overload_manager_config_;
});
}
};
// Run the tests using HTTP2 only since its the only protocol that's fully
// supported.
// TODO(kbaichoo): Instantiate with H3 and H1 as well when their buffers are
// bounded to accounts.
INSTANTIATE_TEST_SUITE_P(
IpVersions, Http2OverloadManagerIntegrationTest,
testing::Combine(testing::ValuesIn(HttpProtocolIntegrationTest::getProtocolTestParams(
{Http::CodecType::HTTP2}, {FakeHttpConnection::Type::HTTP2})),
testing::Bool()),
protocolTestParamsAndBoolToString);
TEST_P(Http2OverloadManagerIntegrationTest,
ResetsExpensiveStreamsWhenUpstreamBuffersTakeTooMuchSpaceAndOverloaded) {
autonomous_upstream_ = true;
autonomous_allow_incomplete_streams_ = true;
initializeOverloadManagerInBootstrap(
TestUtility::parseYaml<envoy::config::overload::v3::OverloadAction>(R"EOF(
name: "envoy.overload_actions.reset_high_memory_stream"
triggers:
- name: "envoy.resource_monitors.testonly.fake_resource_monitor"
scaled:
scaling_threshold: 0.90
saturation_threshold: 0.98
)EOF"));
initialize();
// Makes us have Envoy's writes to upstream return EAGAIN
write_matcher_->setDestinationPort(fake_upstreams_[0]->localAddress()->ip()->port());
write_matcher_->setWriteReturnsEgain();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto smallest_request_response = std::move(sendRequests(1, 4096, 4096)[0]);
auto medium_request_response = std::move(sendRequests(1, 4096 * 2, 4096)[0]);
auto largest_request_response = std::move(sendRequests(1, 4096 * 4, 4096)[0]);
// Wait for requests to come into Envoy.
EXPECT_TRUE(buffer_factory_->waitUntilTotalBufferedExceeds(7 * 4096));
// Set the pressure so the overload action kicks in
updateResource(0.95);
test_server_->waitForGaugeEq(
"overload.envoy.overload_actions.reset_high_memory_stream.scale_percent", 62);
// Wait for the proxy to notice and take action for the overload by only
// resetting the largest stream.
if (streamBufferAccounting()) {
test_server_->waitForCounterGe("http.config_test.downstream_rq_rx_reset", 1);
test_server_->waitForCounterGe("envoy.overload_actions.reset_high_memory_stream.count", 1);
EXPECT_TRUE(largest_request_response->waitForReset());
EXPECT_TRUE(largest_request_response->reset());
ASSERT_FALSE(medium_request_response->complete());
}
// Increase resource pressure to reset the medium request
updateResource(0.96);
// Wait for the proxy to notice and take action for the overload.
if (streamBufferAccounting()) {
test_server_->waitForCounterGe("http.config_test.downstream_rq_rx_reset", 2);
test_server_->waitForCounterGe("envoy.overload_actions.reset_high_memory_stream.count", 2);
EXPECT_TRUE(medium_request_response->waitForReset());
EXPECT_TRUE(medium_request_response->reset());
ASSERT_FALSE(smallest_request_response->complete());
}
// Reduce resource pressure
updateResource(0.80);
test_server_->waitForGaugeEq(
"overload.envoy.overload_actions.reset_high_memory_stream.scale_percent", 0);
// Resume writes to upstream, any request streams that survive can go through.
write_matcher_->setResumeWrites();
if (!streamBufferAccounting()) {
// If we're not doing the accounting, we didn't end up resetting these
// streams.
ASSERT_TRUE(largest_request_response->waitForEndStream());
ASSERT_TRUE(largest_request_response->complete());
EXPECT_EQ(largest_request_response->headers().getStatusValue(), "200");
ASSERT_TRUE(medium_request_response->waitForEndStream());
ASSERT_TRUE(medium_request_response->complete());
EXPECT_EQ(medium_request_response->headers().getStatusValue(), "200");
}
ASSERT_TRUE(smallest_request_response->waitForEndStream());
ASSERT_TRUE(smallest_request_response->complete());
EXPECT_EQ(smallest_request_response->headers().getStatusValue(), "200");
}
TEST_P(Http2OverloadManagerIntegrationTest,
ResetsExpensiveStreamsWhenDownstreamBuffersTakeTooMuchSpaceAndOverloaded) {
initializeOverloadManagerInBootstrap(
TestUtility::parseYaml<envoy::config::overload::v3::OverloadAction>(R"EOF(
name: "envoy.overload_actions.reset_high_memory_stream"
triggers:
- name: "envoy.resource_monitors.testonly.fake_resource_monitor"
scaled:
scaling_threshold: 0.90
saturation_threshold: 0.98
)EOF"));
initialize();
// Makes us have Envoy's writes to downstream return EAGAIN
write_matcher_->setSourcePort(lookupPort("http"));
codec_client_ = makeHttpConnection(lookupPort("http"));
write_matcher_->setWriteReturnsEgain();
auto smallest_response = std::move(sendRequests(1, 10, 4096)[0]);
waitForNextUpstreamRequest();
FakeStreamPtr upstream_request_for_smallest_response = std::move(upstream_request_);
auto medium_response = std::move(sendRequests(1, 20, 4096 * 2)[0]);
waitForNextUpstreamRequest();
FakeStreamPtr upstream_request_for_medium_response = std::move(upstream_request_);
auto largest_response = std::move(sendRequests(1, 30, 4096 * 4)[0]);
waitForNextUpstreamRequest();
FakeStreamPtr upstream_request_for_largest_response = std::move(upstream_request_);
// Send the responses back, without yet ending the stream.
upstream_request_for_largest_response->encodeHeaders(
Http::TestResponseHeaderMapImpl{{":status", "200"}}, false);
upstream_request_for_largest_response->encodeData(4096 * 4, false);
upstream_request_for_medium_response->encodeHeaders(
Http::TestResponseHeaderMapImpl{{":status", "200"}}, false);
upstream_request_for_medium_response->encodeData(4096 * 2, false);
upstream_request_for_smallest_response->encodeHeaders(
Http::TestResponseHeaderMapImpl{{":status", "200"}}, false);
upstream_request_for_smallest_response->encodeData(4096, false);
// Wait for the responses to come back
EXPECT_TRUE(buffer_factory_->waitUntilTotalBufferedExceeds(7 * 4096));
// Set the pressure so the overload action kills largest response
updateResource(0.95);
test_server_->waitForGaugeEq(
"overload.envoy.overload_actions.reset_high_memory_stream.scale_percent", 62);
if (streamBufferAccounting()) {
test_server_->waitForCounterGe("http.config_test.downstream_rq_rx_reset", 1);
test_server_->waitForCounterGe("envoy.overload_actions.reset_high_memory_stream.count", 1);
ASSERT_TRUE(upstream_request_for_largest_response->waitForReset());
}
// Set the pressure so the overload action kills medium response
updateResource(0.96);
if (streamBufferAccounting()) {
test_server_->waitForCounterGe("http.config_test.downstream_rq_rx_reset", 2);
test_server_->waitForCounterGe("envoy.overload_actions.reset_high_memory_stream.count", 2);
ASSERT_TRUE(upstream_request_for_medium_response->waitForReset());
}
// Reduce resource pressure
updateResource(0.80);
test_server_->waitForGaugeEq(
"overload.envoy.overload_actions.reset_high_memory_stream.scale_percent", 0);
// Resume writes to downstream, any responses that survive can go through.
write_matcher_->setResumeWrites();
if (streamBufferAccounting()) {
EXPECT_TRUE(largest_response->waitForReset());
EXPECT_TRUE(largest_response->reset());
EXPECT_TRUE(medium_response->waitForReset());
EXPECT_TRUE(medium_response->reset());
} else {
// If we're not doing the accounting, we didn't end up resetting these
// streams. Finish sending data.
upstream_request_for_largest_response->encodeData(100, true);
upstream_request_for_medium_response->encodeData(100, true);
ASSERT_TRUE(largest_response->waitForEndStream());
ASSERT_TRUE(largest_response->complete());
EXPECT_EQ(largest_response->headers().getStatusValue(), "200");
ASSERT_TRUE(medium_response->waitForEndStream());
ASSERT_TRUE(medium_response->complete());
EXPECT_EQ(medium_response->headers().getStatusValue(), "200");
}
// Have the smallest response finish.
upstream_request_for_smallest_response->encodeData(100, true);
ASSERT_TRUE(smallest_response->waitForEndStream());
ASSERT_TRUE(smallest_response->complete());
EXPECT_EQ(smallest_response->headers().getStatusValue(), "200");
}
TEST_P(Http2OverloadManagerIntegrationTest, CanResetStreamIfEnvoyLevelStreamEnded) {
// This test is not applicable if expand_agnostic_stream_lifetime is enabled
// as the gap between lifetimes of the codec level and envoy level stream
// shrinks.
if (Runtime::runtimeFeatureEnabled(Runtime::expand_agnostic_stream_lifetime)) {
return;
}
useAccessLog("%RESPONSE_CODE%");
initializeOverloadManagerInBootstrap(
TestUtility::parseYaml<envoy::config::overload::v3::OverloadAction>(R"EOF(
name: "envoy.overload_actions.reset_high_memory_stream"
triggers:
- name: "envoy.resource_monitors.testonly.fake_resource_monitor"
scaled:
scaling_threshold: 0.90
saturation_threshold: 0.98
)EOF"));
initialize();
// Set 10MiB receive window for the client.
const int downstream_window_size = 10 * 1024 * 1024;
envoy::config::core::v3::Http2ProtocolOptions http2_options =
::Envoy::Http2::Utility::initializeAndValidateOptions(
envoy::config::core::v3::Http2ProtocolOptions());
http2_options.mutable_initial_stream_window_size()->set_value(downstream_window_size);
http2_options.mutable_initial_connection_window_size()->set_value(downstream_window_size);
codec_client_ = makeRawHttpConnection(makeClientConnection(lookupPort("http")), http2_options);
// Makes us have Envoy's writes to downstream return EAGAIN
write_matcher_->setSourcePort(lookupPort("http"));
write_matcher_->setWriteReturnsEgain();
// Send a request
auto encoder_decoder = codec_client_->startRequest(Http::TestRequestHeaderMapImpl{
{":method", "POST"},
{":path", "/"},
{":scheme", "http"},
{":authority", "host"},
{"content-length", "10"},
});
auto& encoder = encoder_decoder.first;
const std::string data(10, 'a');
codec_client_->sendData(encoder, data, true);
auto response = std::move(encoder_decoder.second);
waitForNextUpstreamRequest();
FakeStreamPtr upstream_request_for_response = std::move(upstream_request_);
// Send the responses back. It is larger than the downstream's receive window
// size. Thus, the codec will not end the stream, but the Envoy level stream
// should.
upstream_request_for_response->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}},
false);
const int response_size = downstream_window_size + 1024; // Slightly over the window size.
upstream_request_for_response->encodeData(response_size, true);
if (streamBufferAccounting()) {
if (deferProcessingBackedUpStreams()) {
// Wait for an accumulation of data, as we cannot rely on the access log
// output since we're deferring the processing of the stream data.
EXPECT_TRUE(buffer_factory_->waitUntilTotalBufferedExceeds(10 * 10 * 1024));
} else {
// Wait for access log to know the Envoy level stream has been deleted.
EXPECT_THAT(waitForAccessLog(access_log_name_), HasSubstr("200"));
}
}
// Set the pressure so the overload action kills the response if doing stream
// accounting
updateResource(0.95);
test_server_->waitForGaugeEq(
"overload.envoy.overload_actions.reset_high_memory_stream.scale_percent", 62);
if (streamBufferAccounting()) {
test_server_->waitForCounterGe("envoy.overload_actions.reset_high_memory_stream.count", 1);
}
// Reduce resource pressure
updateResource(0.80);
test_server_->waitForGaugeEq(
"overload.envoy.overload_actions.reset_high_memory_stream.scale_percent", 0);
// Resume writes to downstream.
write_matcher_->setResumeWrites();
if (streamBufferAccounting()) {
EXPECT_TRUE(response->waitForReset());
EXPECT_TRUE(response->reset());
} else {
// If we're not doing the accounting, we didn't end up resetting the
// streams.
ASSERT_TRUE(response->waitForEndStream());
ASSERT_TRUE(response->complete());
EXPECT_EQ(response->headers().getStatusValue(), "200");
}
}
class Http2DeferredProcessingIntegrationTest : public Http2BufferWatermarksTest {
public:
Http2DeferredProcessingIntegrationTest() : registered_tee_factory_(tee_filter_factory_) {
config_helper_.prependFilter(R"EOF(
name: stream-tee-filter
)EOF");
}
protected:
StreamTeeFilterConfig tee_filter_factory_;
Registry::InjectFactory<Server::Configuration::NamedHttpFilterConfigFactory>
registered_tee_factory_;
void testCrashDumpWhenProcessingBufferedData() {
// Stop writes to the upstream.
write_matcher_->setDestinationPort(fake_upstreams_[0]->localAddress()->ip()->port());
write_matcher_->setWriteReturnsEgain();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto [request_encoder, response_decoder] =
codec_client_->startRequest(default_request_headers_);
codec_client_->sendData(request_encoder, 1000, false);
// Wait for an upstream request to have our reach its buffer limit and read
// disable.
test_server_->waitForGaugeEq("cluster.cluster_0.upstream_rq_active", 1);
test_server_->waitForCounterEq("cluster.cluster_0.upstream_flow_control_backed_up_total", 1);
test_server_->waitForCounterEq("http.config_test.downstream_flow_control_paused_reading_total",
1);
codec_client_->sendData(request_encoder, 1000, true);
// Verify codec received but is buffered as we're still read disabled.
buffer_factory_->waitUntilTotalBufferedExceeds(2000);
test_server_->waitForCounterEq("http.config_test.downstream_flow_control_resumed_reading_total",
0);
EXPECT_TRUE(tee_filter_factory_.inspectStreamTee(1, [](const StreamTee& tee) {
absl::MutexLock l{&tee.mutex_};
EXPECT_EQ(tee.request_body_.length(), 1000);
}));
// Set the filter to crash when processing the deferred bytes.
auto crash_if_over_1000 =
[](StreamTee& tee, Http::StreamDecoderFilterCallbacks*)
ABSL_EXCLUSIVE_LOCKS_REQUIRED(tee.mutex_) -> Http::FilterDataStatus {
if (tee.request_body_.length() > 1000) {
RELEASE_ASSERT(false, "Crashing as request body over 1000!");
}
return Http::FilterDataStatus::Continue;
};
// Allow draining to the upstream, and complete the stream.
EXPECT_TRUE(tee_filter_factory_.setDecodeDataCallback(1, crash_if_over_1000));
write_matcher_->setResumeWrites();
waitForNextUpstreamRequest();
FakeStreamPtr upstream_request = std::move(upstream_request_);
ASSERT_TRUE(upstream_request->complete());
}
void testCrashDumpWhenProcessingBufferedDataOfDeferredCloseStream() {
// Stop writes to the downstream.
write_matcher_->setSourcePort(lookupPort("http"));
codec_client_ = makeHttpConnection(lookupPort("http"));
write_matcher_->setWriteReturnsEgain();
auto [request_encoder, response_decoder] =
codec_client_->startRequest(default_request_headers_);
codec_client_->sendData(request_encoder, 100, true);
waitForNextUpstreamRequest();
FakeStreamPtr upstream_request = std::move(upstream_request_);
upstream_request->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, false);
upstream_request->encodeData(1000, false);
// Wait for an upstream response to have our reach its buffer limit and read
// disable.
test_server_->waitForGaugeEq("cluster.cluster_0.upstream_rq_active", 1);
test_server_->waitForCounterEq("cluster.cluster_0.upstream_flow_control_paused_reading_total",
1);
upstream_request->encodeData(500, true);
ASSERT_TRUE(upstream_request->complete());
// Verify codec received and has buffered onStreamClose for upstream as we're still read
// disabled.
buffer_factory_->waitUntilTotalBufferedExceeds(1500);
test_server_->waitForGaugeEq("cluster.cluster_0.http2.deferred_stream_close", 1);