/
conn_pool_test.cc
1173 lines (963 loc) · 41.8 KB
/
conn_pool_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 <memory>
#include <vector>
#include "source/common/event/dispatcher_impl.h"
#include "source/common/network/transport_socket_options_impl.h"
#include "source/common/network/utility.h"
#include "source/common/tcp/conn_pool.h"
#include "source/common/tcp/original_conn_pool.h"
#include "source/common/upstream/upstream_impl.h"
#include "test/common/upstream/utility.h"
#include "test/mocks/common.h"
#include "test/mocks/event/mocks.h"
#include "test/mocks/network/mocks.h"
#include "test/mocks/runtime/mocks.h"
#include "test/mocks/ssl/mocks.h"
#include "test/mocks/tcp/mocks.h"
#include "test/mocks/upstream/cluster_info.h"
#include "test/test_common/printers.h"
#include "test/test_common/simulated_time_system.h"
#include "test/test_common/utility.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using testing::_;
using testing::AnyNumber;
using testing::Invoke;
using testing::InvokeWithoutArgs;
using testing::NiceMock;
using testing::Property;
using testing::Return;
using testing::StrictMock;
namespace Envoy {
namespace Tcp {
namespace {
struct TestConnectionState : public ConnectionPool::ConnectionState {
TestConnectionState(int id, std::function<void()> on_destructor)
: id_(id), on_destructor_(on_destructor) {}
~TestConnectionState() override { on_destructor_(); }
int id_;
std::function<void()> on_destructor_;
};
} // namespace
/**
* Mock callbacks used for conn pool testing.
*/
struct ConnPoolCallbacks : public Tcp::ConnectionPool::Callbacks {
void onPoolReady(ConnectionPool::ConnectionDataPtr&& conn,
Upstream::HostDescriptionConstSharedPtr host) override {
conn_data_ = std::move(conn);
conn_data_->addUpstreamCallbacks(callbacks_);
host_ = host;
pool_ready_.ready();
}
void onPoolFailure(ConnectionPool::PoolFailureReason reason, absl::string_view,
Upstream::HostDescriptionConstSharedPtr host) override {
reason_ = reason;
host_ = host;
pool_failure_.ready();
}
StrictMock<ConnectionPool::MockUpstreamCallbacks> callbacks_;
ReadyWatcher pool_failure_;
ReadyWatcher pool_ready_;
ConnectionPool::ConnectionDataPtr conn_data_{};
absl::optional<ConnectionPool::PoolFailureReason> reason_;
Upstream::HostDescriptionConstSharedPtr host_;
};
class TestActiveTcpClient : public ActiveTcpClient {
public:
using ActiveTcpClient::ActiveTcpClient;
~TestActiveTcpClient() override { parent().onConnDestroyed(); }
void clearCallbacks() override {
if (state() == Envoy::ConnectionPool::ActiveClient::State::BUSY ||
state() == Envoy::ConnectionPool::ActiveClient::State::DRAINING) {
parent().onConnReleased(*this);
}
ActiveTcpClient::clearCallbacks();
}
Envoy::Tcp::ConnPoolImpl& parent() { return *static_cast<ConnPoolImpl*>(&parent_); }
};
/**
* A wrapper around a ConnectionPoolImpl which tracks when the bridge between
* the pool and the consumer of the connection is released and destroyed.
*/
class ConnPoolBase : public Tcp::ConnectionPool::Instance {
public:
ConnPoolBase(Event::MockDispatcher& dispatcher, Upstream::HostSharedPtr host,
NiceMock<Event::MockSchedulableCallback>* upstream_ready_cb,
Network::ConnectionSocket::OptionsSharedPtr options,
Network::TransportSocketOptionsSharedPtr transport_socket_options,
bool test_new_connection_pool);
void addDrainedCallback(DrainedCb cb) override { conn_pool_->addDrainedCallback(cb); }
void drainConnections() override { conn_pool_->drainConnections(); }
void closeConnections() override { conn_pool_->closeConnections(); }
ConnectionPool::Cancellable* newConnection(Tcp::ConnectionPool::Callbacks& callbacks) override {
return conn_pool_->newConnection(callbacks);
}
Upstream::HostDescriptionConstSharedPtr host() const override { return conn_pool_->host(); }
MOCK_METHOD(void, onConnReleasedForTest, ());
MOCK_METHOD(void, onConnDestroyedForTest, ());
bool maybePreconnect(float ratio) override {
if (!test_new_connection_pool_) {
return false;
}
ASSERT(dynamic_cast<ConnPoolImplForTest*>(conn_pool_.get()) != nullptr);
return dynamic_cast<ConnPoolImplForTest*>(conn_pool_.get())->maybePreconnect(ratio);
}
struct TestConnection {
Network::MockClientConnection* connection_;
Event::MockTimer* connect_timer_;
Network::ReadFilterSharedPtr filter_;
};
void expectConnCreate() {
test_conns_.emplace_back();
TestConnection& test_conn = test_conns_.back();
test_conn.connection_ = new NiceMock<Network::MockClientConnection>();
test_conn.connect_timer_ = new NiceMock<Event::MockTimer>(&mock_dispatcher_);
EXPECT_CALL(mock_dispatcher_, createClientConnection_(_, _, _, options_))
.WillOnce(Return(test_conn.connection_));
EXPECT_CALL(*test_conn.connection_, addReadFilter(_))
.WillOnce(Invoke(
[&](Network::ReadFilterSharedPtr filter) -> void { test_conn.filter_ = filter; }));
EXPECT_CALL(*test_conn.connection_, connect());
EXPECT_CALL(*test_conn.connect_timer_, enableTimer(_, _));
ON_CALL(*test_conn.connection_, close(Network::ConnectionCloseType::NoFlush))
.WillByDefault(InvokeWithoutArgs([test_conn]() -> void {
test_conn.connection_->raiseEvent(Network::ConnectionEvent::LocalClose);
}));
}
void expectEnableUpstreamReady(bool run);
std::unique_ptr<Tcp::ConnectionPool::Instance> conn_pool_;
Event::MockDispatcher& mock_dispatcher_;
NiceMock<Event::MockSchedulableCallback>* mock_upstream_ready_cb_;
std::vector<TestConnection> test_conns_;
Network::ConnectionCallbacks* callbacks_ = nullptr;
bool test_new_connection_pool_;
Network::ConnectionSocket::OptionsSharedPtr options_;
Network::TransportSocketOptionsSharedPtr transport_socket_options_;
protected:
class ConnPoolImplForTest : public ConnPoolImpl {
public:
ConnPoolImplForTest(Event::MockDispatcher& dispatcher, Upstream::HostSharedPtr host,
Network::ConnectionSocket::OptionsSharedPtr options,
Network::TransportSocketOptionsSharedPtr transport_socket_options,
ConnPoolBase& parent)
: ConnPoolImpl(dispatcher, host, Upstream::ResourcePriority::Default, options,
transport_socket_options, state_),
parent_(parent) {}
void onConnReleased(Envoy::ConnectionPool::ActiveClient& client) override {
ConnPoolImpl::onConnReleased(client);
parent_.onConnReleasedForTest();
}
Envoy::ConnectionPool::ActiveClientPtr instantiateActiveClient() override {
return std::make_unique<TestActiveTcpClient>(
*this, Envoy::ConnectionPool::ConnPoolImplBase::host(), 1);
}
void onConnDestroyed() override { parent_.onConnDestroyedForTest(); }
Upstream::ClusterConnectivityState state_;
Event::PostCb post_cb_;
ConnPoolBase& parent_;
};
class OriginalConnPoolImplForTest : public OriginalConnPoolImpl {
public:
OriginalConnPoolImplForTest(Event::MockDispatcher& dispatcher, Upstream::HostSharedPtr host,
Network::ConnectionSocket::OptionsSharedPtr options,
Network::TransportSocketOptionsSharedPtr transport_socket_options,
ConnPoolBase& parent)
: OriginalConnPoolImpl(dispatcher, host, Upstream::ResourcePriority::Default, options,
transport_socket_options),
parent_(parent) {}
~OriginalConnPoolImplForTest() override {
EXPECT_EQ(0U, ready_conns_.size());
EXPECT_EQ(0U, busy_conns_.size());
EXPECT_EQ(0U, pending_requests_.size());
}
void onConnReleased(OriginalConnPoolImpl::ActiveConn& conn) override {
parent_.onConnReleasedForTest();
OriginalConnPoolImpl::onConnReleased(conn);
}
void onConnDestroyed(OriginalConnPoolImpl::ActiveConn& conn) override {
parent_.onConnDestroyedForTest();
OriginalConnPoolImpl::onConnDestroyed(conn);
}
void expectEnableUpstreamReady(bool run) {
if (!run) {
EXPECT_FALSE(upstream_ready_enabled_);
EXPECT_CALL(*parent_.mock_upstream_ready_cb_, scheduleCallbackCurrentIteration())
.Times(1)
.RetiresOnSaturation();
} else {
EXPECT_TRUE(upstream_ready_enabled_);
parent_.mock_upstream_ready_cb_->invokeCallback();
EXPECT_FALSE(upstream_ready_enabled_);
}
}
ConnPoolBase& parent_;
};
};
ConnPoolBase::ConnPoolBase(Event::MockDispatcher& dispatcher, Upstream::HostSharedPtr host,
NiceMock<Event::MockSchedulableCallback>* upstream_ready_cb,
Network::ConnectionSocket::OptionsSharedPtr options,
Network::TransportSocketOptionsSharedPtr transport_socket_options,
bool test_new_connection_pool)
: mock_dispatcher_(dispatcher), mock_upstream_ready_cb_(upstream_ready_cb),
test_new_connection_pool_(test_new_connection_pool), options_(options),
transport_socket_options_(transport_socket_options) {
if (test_new_connection_pool_) {
conn_pool_ = std::make_unique<ConnPoolImplForTest>(dispatcher, host, options,
transport_socket_options, *this);
} else {
conn_pool_ = std::make_unique<OriginalConnPoolImplForTest>(dispatcher, host, options,
transport_socket_options, *this);
}
}
void ConnPoolBase::expectEnableUpstreamReady(bool run) {
if (!test_new_connection_pool_) {
dynamic_cast<OriginalConnPoolImplForTest*>(conn_pool_.get())->expectEnableUpstreamReady(run);
} else {
if (run) {
mock_upstream_ready_cb_->invokeCallback();
} else {
EXPECT_CALL(*mock_upstream_ready_cb_, scheduleCallbackCurrentIteration())
.Times(1)
.RetiresOnSaturation();
}
}
}
/**
* Test fixture for connection pool tests.
*/
class TcpConnPoolImplTest : public Event::TestUsingSimulatedTime,
public testing::TestWithParam<bool> {
public:
TcpConnPoolImplTest()
: test_new_connection_pool_(GetParam()),
upstream_ready_cb_(new NiceMock<Event::MockSchedulableCallback>(&dispatcher_)),
host_(Upstream::makeTestHost(cluster_, "tcp://127.0.0.1:9000", simTime())) {}
~TcpConnPoolImplTest() override {
EXPECT_TRUE(TestUtility::gaugesZeroed(cluster_->stats_store_.gauges()))
<< TestUtility::nonZeroedGauges(cluster_->stats_store_.gauges());
}
void initialize() {
conn_pool_ =
std::make_unique<ConnPoolBase>(dispatcher_, host_, upstream_ready_cb_, options_,
transport_socket_options_, test_new_connection_pool_);
}
bool test_new_connection_pool_;
NiceMock<Event::MockDispatcher> dispatcher_;
std::shared_ptr<Upstream::MockClusterInfo> cluster_{new NiceMock<Upstream::MockClusterInfo>()};
NiceMock<Event::MockSchedulableCallback>* upstream_ready_cb_;
Upstream::HostSharedPtr host_;
Network::ConnectionSocket::OptionsSharedPtr options_;
Network::TransportSocketOptionsSharedPtr transport_socket_options_;
std::unique_ptr<ConnPoolBase> conn_pool_;
NiceMock<Runtime::MockLoader> runtime_;
};
/**
* Test fixture for connection pool destructor tests.
*/
class TcpConnPoolImplDestructorTest : public Event::TestUsingSimulatedTime,
public testing::TestWithParam<bool> {
public:
TcpConnPoolImplDestructorTest()
: test_new_connection_pool_(GetParam()),
upstream_ready_cb_(new NiceMock<Event::MockSchedulableCallback>(&dispatcher_)) {
host_ = Upstream::makeTestHost(cluster_, "tcp://127.0.0.1:9000", simTime());
if (test_new_connection_pool_) {
conn_pool_ = std::make_unique<ConnPoolImpl>(
dispatcher_, host_, Upstream::ResourcePriority::Default, nullptr, nullptr, state_);
} else {
conn_pool_ = std::make_unique<OriginalConnPoolImpl>(
dispatcher_, host_, Upstream::ResourcePriority::Default, nullptr, nullptr);
}
ssl_ = std::make_shared<NiceMock<Envoy::Ssl::MockConnectionInfo>>();
}
~TcpConnPoolImplDestructorTest() override = default;
void prepareConn() {
connection_ = new StrictMock<Network::MockClientConnection>();
EXPECT_CALL(*connection_, setBufferLimits(0));
EXPECT_CALL(*connection_, detectEarlyCloseWhenReadDisabled(false));
EXPECT_CALL(*connection_, addConnectionCallbacks(_));
EXPECT_CALL(*connection_, addReadFilter(_));
EXPECT_CALL(*connection_, connect());
EXPECT_CALL(*connection_, setConnectionStats(_));
EXPECT_CALL(*connection_, noDelay(true));
EXPECT_CALL(*connection_, streamInfo()).Times(2);
EXPECT_CALL(*connection_, id()).Times(AnyNumber());
EXPECT_CALL(*connection_, readDisable(_)).Times(AnyNumber());
connect_timer_ = new NiceMock<Event::MockTimer>(&dispatcher_);
EXPECT_CALL(dispatcher_, createClientConnection_(_, _, _, _)).WillOnce(Return(connection_));
EXPECT_CALL(*connect_timer_, enableTimer(_, _));
callbacks_ = std::make_unique<ConnPoolCallbacks>();
ConnectionPool::Cancellable* handle = conn_pool_->newConnection(*callbacks_);
EXPECT_NE(nullptr, handle);
EXPECT_CALL(*connect_timer_, disableTimer());
EXPECT_CALL(callbacks_->pool_ready_, ready());
EXPECT_CALL(*connection_, ssl()).WillOnce(Return(ssl_));
connection_->raiseEvent(Network::ConnectionEvent::Connected);
EXPECT_EQ(connection_->streamInfo().downstreamSslConnection(), ssl_);
}
bool test_new_connection_pool_;
Upstream::ClusterConnectivityState state_;
Upstream::HostConstSharedPtr host_;
NiceMock<Event::MockDispatcher> dispatcher_;
std::shared_ptr<NiceMock<Envoy::Ssl::MockConnectionInfo>> ssl_;
std::shared_ptr<Upstream::MockClusterInfo> cluster_{new NiceMock<Upstream::MockClusterInfo>()};
NiceMock<Event::MockSchedulableCallback>* upstream_ready_cb_;
NiceMock<Event::MockTimer>* connect_timer_;
Network::MockClientConnection* connection_;
std::unique_ptr<Tcp::ConnectionPool::Instance> conn_pool_;
std::unique_ptr<ConnPoolCallbacks> callbacks_;
};
/**
* Helper for dealing with an active test connection.
*/
struct ActiveTestConn {
enum class Type {
Pending, // pending request, waiting for free connection
InProgress, // connection created, no callback
CreateConnection, // connection callback occurs after newConnection
Immediate, // connection callback occurs during newConnection
};
ActiveTestConn(TcpConnPoolImplTest& parent, size_t conn_index, Type type)
: parent_(parent), conn_index_(conn_index) {
if (type == Type::CreateConnection || type == Type::InProgress) {
parent.conn_pool_->expectConnCreate();
}
if (type == Type::Immediate) {
expectNewConn();
}
handle_ = parent.conn_pool_->newConnection(callbacks_);
if (type == Type::Immediate) {
EXPECT_EQ(nullptr, handle_);
verifyConn();
} else {
EXPECT_NE(nullptr, handle_);
}
if (type == Type::CreateConnection) {
completeConnection();
}
}
void completeConnection() {
ASSERT_FALSE(completed_);
EXPECT_CALL(*parent_.conn_pool_->test_conns_[conn_index_].connect_timer_, disableTimer());
expectNewConn();
parent_.conn_pool_->test_conns_[conn_index_].connection_->raiseEvent(
Network::ConnectionEvent::Connected);
verifyConn();
completed_ = true;
}
void expectNewConn() { EXPECT_CALL(callbacks_.pool_ready_, ready()); }
void releaseConn() { callbacks_.conn_data_.reset(); }
void verifyConn() {
EXPECT_EQ(&callbacks_.conn_data_->connection(),
parent_.conn_pool_->test_conns_[conn_index_].connection_);
}
TcpConnPoolImplTest& parent_;
size_t conn_index_;
Tcp::ConnectionPool::Cancellable* handle_{};
ConnPoolCallbacks callbacks_;
bool completed_{};
};
TEST_P(TcpConnPoolImplTest, Accessors) {
initialize();
EXPECT_EQ(conn_pool_->host(), host_);
}
/**
* Verify that connections are drained when requested.
*/
TEST_P(TcpConnPoolImplTest, DrainConnections) {
initialize();
cluster_->resetResourceManager(3, 1024, 1024, 1, 1);
ActiveTestConn c1(*this, 0, ActiveTestConn::Type::CreateConnection);
ActiveTestConn c2(*this, 1, ActiveTestConn::Type::CreateConnection);
ActiveTestConn c3(*this, 2, ActiveTestConn::Type::InProgress);
EXPECT_CALL(*conn_pool_, onConnReleasedForTest());
c1.releaseConn();
{
// This will destroy the ready connection and set requests remaining to 1 on the busy and
// pending connections.
EXPECT_CALL(*conn_pool_, onConnDestroyedForTest());
conn_pool_->drainConnections();
dispatcher_.clearDeferredDeleteList();
}
{
// This will destroy the busy connection when the response finishes.
EXPECT_CALL(*conn_pool_, onConnReleasedForTest());
EXPECT_CALL(*conn_pool_, onConnDestroyedForTest());
c2.releaseConn();
dispatcher_.clearDeferredDeleteList();
}
{
// This will destroy the pending connection when the response finishes.
c3.completeConnection();
EXPECT_CALL(*conn_pool_, onConnReleasedForTest());
EXPECT_CALL(*conn_pool_, onConnDestroyedForTest());
c3.releaseConn();
dispatcher_.clearDeferredDeleteList();
}
}
/**
* Test all timing stats are set.
*/
TEST_P(TcpConnPoolImplTest, VerifyTimingStats) {
initialize();
EXPECT_CALL(cluster_->stats_store_,
deliverHistogramToSinks(Property(&Stats::Metric::name, "upstream_cx_connect_ms"), _));
EXPECT_CALL(cluster_->stats_store_,
deliverHistogramToSinks(Property(&Stats::Metric::name, "upstream_cx_length_ms"), _));
ActiveTestConn c1(*this, 0, ActiveTestConn::Type::CreateConnection);
EXPECT_CALL(*conn_pool_, onConnReleasedForTest());
c1.releaseConn();
conn_pool_->test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
EXPECT_CALL(*conn_pool_, onConnDestroyedForTest());
dispatcher_.clearDeferredDeleteList();
}
/**
* Test that buffer limits and options are respected.
*/
TEST_P(TcpConnPoolImplTest, VerifyBufferLimitsAndOptions) {
options_ = std::make_shared<Network::Socket::Options>();
transport_socket_options_ = std::make_shared<const Network::TransportSocketOptionsImpl>();
initialize();
ConnPoolCallbacks callbacks;
conn_pool_->expectConnCreate();
EXPECT_CALL(*cluster_, perConnectionBufferLimitBytes()).WillOnce(Return(8192));
EXPECT_CALL(*conn_pool_->test_conns_.back().connection_, setBufferLimits(8192));
EXPECT_CALL(callbacks.pool_failure_, ready());
Tcp::ConnectionPool::Cancellable* handle = conn_pool_->newConnection(callbacks);
EXPECT_NE(nullptr, handle);
EXPECT_CALL(*conn_pool_, onConnDestroyedForTest());
conn_pool_->test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
}
/**
* Test that upstream callback fire for assigned connections.
*/
TEST_P(TcpConnPoolImplTest, UpstreamCallbacks) {
initialize();
Buffer::OwnedImpl buffer;
// Create connection, UpstreamCallbacks set automatically
ActiveTestConn c1(*this, 0, ActiveTestConn::Type::CreateConnection);
// Expect invocation when connection's ReadFilter::onData is invoked
EXPECT_CALL(c1.callbacks_.callbacks_, onUpstreamData(_, _));
EXPECT_EQ(Network::FilterStatus::StopIteration,
conn_pool_->test_conns_[0].filter_->onData(buffer, false));
EXPECT_CALL(c1.callbacks_.callbacks_, onAboveWriteBufferHighWatermark());
for (auto* cb : conn_pool_->test_conns_[0].connection_->callbacks_) {
cb->onAboveWriteBufferHighWatermark();
}
EXPECT_CALL(c1.callbacks_.callbacks_, onBelowWriteBufferLowWatermark());
for (auto* cb : conn_pool_->test_conns_[0].connection_->callbacks_) {
cb->onBelowWriteBufferLowWatermark();
}
// Shutdown normally.
EXPECT_CALL(*conn_pool_, onConnReleasedForTest());
c1.releaseConn();
EXPECT_CALL(*conn_pool_, onConnDestroyedForTest());
conn_pool_->test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
}
/**
* Tests a request that generates a new connection, completes, and then a second request that uses
* the same connection.
*/
TEST_P(TcpConnPoolImplTest, MultipleRequestAndResponse) {
initialize();
// Request 1 should kick off a new connection.
ActiveTestConn c1(*this, 0, ActiveTestConn::Type::CreateConnection);
EXPECT_CALL(*conn_pool_, onConnReleasedForTest());
c1.releaseConn();
// Request 2 should not.
ActiveTestConn c2(*this, 0, ActiveTestConn::Type::Immediate);
EXPECT_CALL(*conn_pool_, onConnReleasedForTest());
c2.releaseConn();
// Cause the connection to go away.
EXPECT_CALL(*conn_pool_, onConnDestroyedForTest());
conn_pool_->test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
}
/**
* Tests ConnectionState assignment, lookup and destruction.
*/
TEST_P(TcpConnPoolImplTest, ConnectionStateLifecycle) {
initialize();
bool state_destroyed = false;
// Request 1 should kick off a new connection.
ActiveTestConn c1(*this, 0, ActiveTestConn::Type::CreateConnection);
auto* state = new TestConnectionState(1, [&]() -> void { state_destroyed = true; });
c1.callbacks_.conn_data_->setConnectionState(std::unique_ptr<TestConnectionState>(state));
EXPECT_EQ(state, c1.callbacks_.conn_data_->connectionStateTyped<TestConnectionState>());
EXPECT_CALL(*conn_pool_, onConnReleasedForTest());
c1.releaseConn();
EXPECT_FALSE(state_destroyed);
// Request 2 should not.
ActiveTestConn c2(*this, 0, ActiveTestConn::Type::Immediate);
EXPECT_EQ(state, c2.callbacks_.conn_data_->connectionStateTyped<TestConnectionState>());
EXPECT_CALL(*conn_pool_, onConnReleasedForTest());
c2.releaseConn();
EXPECT_FALSE(state_destroyed);
// Cause the connection to go away.
EXPECT_CALL(*conn_pool_, onConnDestroyedForTest());
conn_pool_->test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
EXPECT_TRUE(state_destroyed);
}
/**
* Test when we overflow max pending requests.
*/
TEST_P(TcpConnPoolImplTest, MaxPendingRequests) {
initialize();
cluster_->resetResourceManager(1, 1, 1024, 1, 1);
ConnPoolCallbacks callbacks;
conn_pool_->expectConnCreate();
Tcp::ConnectionPool::Cancellable* handle = conn_pool_->newConnection(callbacks);
EXPECT_NE(nullptr, handle);
ConnPoolCallbacks callbacks2;
EXPECT_CALL(callbacks2.pool_failure_, ready());
Tcp::ConnectionPool::Cancellable* handle2 = conn_pool_->newConnection(callbacks2);
EXPECT_EQ(nullptr, handle2);
handle->cancel(ConnectionPool::CancelPolicy::Default);
EXPECT_CALL(*conn_pool_, onConnDestroyedForTest());
conn_pool_->test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
EXPECT_EQ(ConnectionPool::PoolFailureReason::Overflow, callbacks2.reason_);
EXPECT_EQ(1U, cluster_->stats_.upstream_rq_pending_overflow_.value());
}
/**
* Tests a connection failure before a request is bound which should result in the pending request
* getting purged.
*/
TEST_P(TcpConnPoolImplTest, RemoteConnectFailure) {
initialize();
// Request 1 should kick off a new connection.
ConnPoolCallbacks callbacks;
conn_pool_->expectConnCreate();
Tcp::ConnectionPool::Cancellable* handle = conn_pool_->newConnection(callbacks);
EXPECT_NE(nullptr, handle);
EXPECT_CALL(callbacks.pool_failure_, ready());
EXPECT_CALL(*conn_pool_->test_conns_[0].connect_timer_, disableTimer());
EXPECT_CALL(*conn_pool_, onConnDestroyedForTest());
conn_pool_->test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
EXPECT_EQ(ConnectionPool::PoolFailureReason::RemoteConnectionFailure, callbacks.reason_);
EXPECT_EQ(1U, cluster_->stats_.upstream_cx_connect_fail_.value());
EXPECT_EQ(1U, cluster_->stats_.upstream_rq_pending_failure_eject_.value());
}
/**
* Tests a connection failure before a request is bound which should result in the pending request
* getting purged.
*/
TEST_P(TcpConnPoolImplTest, LocalConnectFailure) {
initialize();
// Request 1 should kick off a new connection.
ConnPoolCallbacks callbacks;
conn_pool_->expectConnCreate();
Tcp::ConnectionPool::Cancellable* handle = conn_pool_->newConnection(callbacks);
EXPECT_NE(nullptr, handle);
EXPECT_CALL(callbacks.pool_failure_, ready());
EXPECT_CALL(*conn_pool_->test_conns_[0].connect_timer_, disableTimer());
EXPECT_CALL(*conn_pool_, onConnDestroyedForTest());
conn_pool_->test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::LocalClose);
dispatcher_.clearDeferredDeleteList();
EXPECT_EQ(ConnectionPool::PoolFailureReason::LocalConnectionFailure, callbacks.reason_);
EXPECT_EQ(1U, cluster_->stats_.upstream_cx_connect_fail_.value());
EXPECT_EQ(1U, cluster_->stats_.upstream_rq_pending_failure_eject_.value());
}
/**
* Tests a connect timeout. Also test that we can add a new request during ejection processing.
*/
TEST_P(TcpConnPoolImplTest, ConnectTimeout) {
initialize();
// Request 1 should kick off a new connection.
ConnPoolCallbacks callbacks1;
conn_pool_->expectConnCreate();
EXPECT_NE(nullptr, conn_pool_->newConnection(callbacks1));
ConnPoolCallbacks callbacks2;
EXPECT_CALL(callbacks1.pool_failure_, ready()).WillOnce(Invoke([&]() -> void {
conn_pool_->expectConnCreate();
EXPECT_NE(nullptr, conn_pool_->newConnection(callbacks2));
}));
conn_pool_->test_conns_[0].connect_timer_->invokeCallback();
EXPECT_CALL(callbacks2.pool_failure_, ready());
conn_pool_->test_conns_[1].connect_timer_->invokeCallback();
EXPECT_CALL(*conn_pool_, onConnDestroyedForTest()).Times(2);
dispatcher_.clearDeferredDeleteList();
EXPECT_EQ(ConnectionPool::PoolFailureReason::Timeout, callbacks1.reason_);
EXPECT_EQ(ConnectionPool::PoolFailureReason::Timeout, callbacks2.reason_);
EXPECT_EQ(2U, cluster_->stats_.upstream_cx_connect_fail_.value());
EXPECT_EQ(2U, cluster_->stats_.upstream_cx_connect_timeout_.value());
}
/**
* Test cancelling before the request is bound to a connection.
*/
TEST_P(TcpConnPoolImplTest, CancelBeforeBound) {
initialize();
// Request 1 should kick off a new connection.
ConnPoolCallbacks callbacks;
conn_pool_->expectConnCreate();
Tcp::ConnectionPool::Cancellable* handle = conn_pool_->newConnection(callbacks);
EXPECT_NE(nullptr, handle);
handle->cancel(ConnectionPool::CancelPolicy::Default);
conn_pool_->test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::Connected);
// Cause the connection to go away.
EXPECT_CALL(*conn_pool_, onConnDestroyedForTest());
conn_pool_->test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
}
/**
* Test cancelling before the request is bound to a connection, with connection close.
*/
TEST_P(TcpConnPoolImplTest, CancelAndCloseBeforeBound) {
initialize();
// Request 1 should kick off a new connection.
ConnPoolCallbacks callbacks;
conn_pool_->expectConnCreate();
Tcp::ConnectionPool::Cancellable* handle = conn_pool_->newConnection(callbacks);
EXPECT_NE(nullptr, handle);
// Expect the connection is closed.
EXPECT_CALL(*conn_pool_, onConnDestroyedForTest());
handle->cancel(ConnectionPool::CancelPolicy::CloseExcess);
dispatcher_.clearDeferredDeleteList();
}
/**
* Test an upstream disconnection while there is a bound request.
*/
TEST_P(TcpConnPoolImplTest, DisconnectWhileBound) {
initialize();
// Request 1 should kick off a new connection.
ConnPoolCallbacks callbacks;
conn_pool_->expectConnCreate();
Tcp::ConnectionPool::Cancellable* handle = conn_pool_->newConnection(callbacks);
EXPECT_NE(nullptr, handle);
EXPECT_CALL(callbacks.pool_ready_, ready());
EXPECT_CALL(callbacks.callbacks_, onEvent(_));
conn_pool_->test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::Connected);
// Kill the connection while it has an active request.
EXPECT_CALL(*conn_pool_, onConnDestroyedForTest());
conn_pool_->test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
}
/**
* Test upstream disconnection of one request while another is pending.
*/
TEST_P(TcpConnPoolImplTest, DisconnectWhilePending) {
initialize();
cluster_->resetResourceManager(1, 1024, 1024, 1, 1);
// First request connected.
ConnPoolCallbacks callbacks;
conn_pool_->expectConnCreate();
ConnectionPool::Cancellable* handle = conn_pool_->newConnection(callbacks);
EXPECT_NE(nullptr, handle);
EXPECT_CALL(*conn_pool_->test_conns_[0].connect_timer_, disableTimer());
EXPECT_CALL(callbacks.pool_ready_, ready());
EXPECT_CALL(callbacks.callbacks_, onEvent(_));
conn_pool_->test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::Connected);
// Second request pending.
ConnPoolCallbacks callbacks2;
ConnectionPool::Cancellable* handle2 = conn_pool_->newConnection(callbacks2);
EXPECT_NE(nullptr, handle2);
// Connection closed, triggering new connection for pending request.
conn_pool_->expectConnCreate();
conn_pool_->test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::LocalClose);
EXPECT_CALL(*conn_pool_, onConnDestroyedForTest());
dispatcher_.clearDeferredDeleteList();
// test_conns_[1] is the new connection
EXPECT_CALL(*conn_pool_->test_conns_[1].connect_timer_, disableTimer());
EXPECT_CALL(callbacks2.pool_ready_, ready());
conn_pool_->test_conns_[1].connection_->raiseEvent(Network::ConnectionEvent::Connected);
EXPECT_CALL(*conn_pool_, onConnReleasedForTest());
callbacks2.conn_data_.reset();
// Disconnect
EXPECT_CALL(*conn_pool_, onConnDestroyedForTest());
conn_pool_->test_conns_[1].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
}
/**
* Test that we correctly handle reaching max connections.
*/
TEST_P(TcpConnPoolImplTest, MaxConnections) {
initialize();
// Request 1 should kick off a new connection.
ConnPoolCallbacks callbacks;
conn_pool_->expectConnCreate();
Tcp::ConnectionPool::Cancellable* handle = conn_pool_->newConnection(callbacks);
EXPECT_NE(nullptr, handle);
// Request 2 should not kick off a new connection.
ConnPoolCallbacks callbacks2;
handle = conn_pool_->newConnection(callbacks2);
EXPECT_EQ(1U, cluster_->stats_.upstream_cx_overflow_.value());
EXPECT_NE(nullptr, handle);
// Connect event will bind to request 1.
EXPECT_CALL(callbacks.pool_ready_, ready());
conn_pool_->test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::Connected);
// Finishing request 1 will immediately bind to request 2.
EXPECT_CALL(*conn_pool_, onConnReleasedForTest());
conn_pool_->expectEnableUpstreamReady(false);
EXPECT_CALL(callbacks2.pool_ready_, ready());
callbacks.conn_data_.reset();
conn_pool_->expectEnableUpstreamReady(true);
EXPECT_CALL(*conn_pool_, onConnReleasedForTest());
callbacks2.conn_data_.reset();
// Cause the connection to go away.
EXPECT_CALL(*conn_pool_, onConnDestroyedForTest());
conn_pool_->test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
}
/**
* Test when we reach max requests per connection.
*/
TEST_P(TcpConnPoolImplTest, MaxRequestsPerConnection) {
initialize();
cluster_->max_requests_per_connection_ = 1;
// Request 1 should kick off a new connection.
ConnPoolCallbacks callbacks;
conn_pool_->expectConnCreate();
Tcp::ConnectionPool::Cancellable* handle = conn_pool_->newConnection(callbacks);
EXPECT_NE(nullptr, handle);
EXPECT_CALL(callbacks.pool_ready_, ready());
conn_pool_->test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::Connected);
EXPECT_CALL(*conn_pool_, onConnReleasedForTest());
EXPECT_CALL(*conn_pool_, onConnDestroyedForTest());
callbacks.conn_data_.reset();
dispatcher_.clearDeferredDeleteList();
EXPECT_EQ(0U, cluster_->stats_.upstream_cx_destroy_with_active_rq_.value());
EXPECT_EQ(1U, cluster_->stats_.upstream_cx_max_requests_.value());
}
/*
* Test that multiple connections can be assigned at once.
*/
TEST_P(TcpConnPoolImplTest, ConcurrentConnections) {
initialize();
cluster_->resetResourceManager(2, 1024, 1024, 1, 1);
ActiveTestConn c1(*this, 0, ActiveTestConn::Type::CreateConnection);
ActiveTestConn c2(*this, 1, ActiveTestConn::Type::CreateConnection);
ActiveTestConn c3(*this, 0, ActiveTestConn::Type::Pending);
// Finish c1, which gets c3 going.
EXPECT_CALL(*conn_pool_, onConnReleasedForTest());
conn_pool_->expectEnableUpstreamReady(false);
c3.expectNewConn();
c1.releaseConn();
conn_pool_->expectEnableUpstreamReady(true);
EXPECT_CALL(*conn_pool_, onConnReleasedForTest()).Times(2);
c2.releaseConn();
c3.releaseConn();
// Disconnect both connections.
EXPECT_CALL(*conn_pool_, onConnDestroyedForTest()).Times(2);
conn_pool_->test_conns_[1].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
conn_pool_->test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
}
/**
* Tests ConnectionState lifecycle with multiple concurrent connections.
*/
TEST_P(TcpConnPoolImplTest, ConnectionStateWithConcurrentConnections) {
initialize();
int state_destroyed = 0;
auto* s1 = new TestConnectionState(1, [&]() -> void { state_destroyed |= 1; });
auto* s2 = new TestConnectionState(2, [&]() -> void { state_destroyed |= 2; });
auto* s3 = new TestConnectionState(2, [&]() -> void { state_destroyed |= 4; });
cluster_->resetResourceManager(2, 1024, 1024, 1, 1);
ActiveTestConn c1(*this, 0, ActiveTestConn::Type::CreateConnection);
c1.callbacks_.conn_data_->setConnectionState(std::unique_ptr<TestConnectionState>(s1));
ActiveTestConn c2(*this, 1, ActiveTestConn::Type::CreateConnection);
c2.callbacks_.conn_data_->setConnectionState(std::unique_ptr<TestConnectionState>(s2));
ActiveTestConn c3(*this, 0, ActiveTestConn::Type::Pending);
EXPECT_EQ(0, state_destroyed);
// Finish c1, which gets c3 going.
EXPECT_CALL(*conn_pool_, onConnReleasedForTest());
conn_pool_->expectEnableUpstreamReady(false);
c3.expectNewConn();
c1.releaseConn();
conn_pool_->expectEnableUpstreamReady(true);
// c3 now has the state set by c1.
EXPECT_EQ(s1, c3.callbacks_.conn_data_->connectionStateTyped<TestConnectionState>());
EXPECT_EQ(s2, c2.callbacks_.conn_data_->connectionStateTyped<TestConnectionState>());
// replace c3's state
c3.callbacks_.conn_data_->setConnectionState(std::unique_ptr<TestConnectionState>(s3));
EXPECT_EQ(1, state_destroyed);
EXPECT_CALL(*conn_pool_, onConnReleasedForTest()).Times(2);
c2.releaseConn();
c3.releaseConn();
EXPECT_EQ(1, state_destroyed);
// Disconnect both connections.
EXPECT_CALL(*conn_pool_, onConnDestroyedForTest()).Times(2);
conn_pool_->test_conns_[1].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
conn_pool_->test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
EXPECT_EQ(7, state_destroyed);
}
/**
* Tests that the DrainCallback is invoked when the number of connections goes to zero.
*/
TEST_P(TcpConnPoolImplTest, DrainCallback) {
initialize();
ReadyWatcher drained;
EXPECT_CALL(drained, ready());
conn_pool_->addDrainedCallback([&]() -> void { drained.ready(); });
ActiveTestConn c1(*this, 0, ActiveTestConn::Type::CreateConnection);
ActiveTestConn c2(*this, 0, ActiveTestConn::Type::Pending);
c2.handle_->cancel(ConnectionPool::CancelPolicy::Default);
EXPECT_CALL(*conn_pool_, onConnReleasedForTest());
EXPECT_CALL(drained, ready());
c1.releaseConn();
EXPECT_CALL(*conn_pool_, onConnDestroyedForTest());
conn_pool_->test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
}
/**
* Test draining a connection pool that has a pending connection.
*/
TEST_P(TcpConnPoolImplTest, DrainWhileConnecting) {
initialize();
ReadyWatcher drained;
ConnPoolCallbacks callbacks;
conn_pool_->expectConnCreate();
Tcp::ConnectionPool::Cancellable* handle = conn_pool_->newConnection(callbacks);
EXPECT_NE(nullptr, handle);