forked from envoyproxy/envoy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection_handler_test.cc
2677 lines (2358 loc) · 132 KB
/
connection_handler_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 <chrono>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "envoy/api/io_error.h"
#include "envoy/config/core/v3/base.pb.h"
#include "envoy/config/listener/v3/udp_listener_config.pb.h"
#include "envoy/network/exception.h"
#include "envoy/network/filter.h"
#include "envoy/stats/scope.h"
#include "source/common/common/utility.h"
#include "source/common/config/utility.h"
#include "source/common/listener_manager/active_raw_udp_listener_config.h"
#include "source/common/listener_manager/connection_handler_impl.h"
#include "source/common/network/address_impl.h"
#include "source/common/network/connection_balancer_impl.h"
#include "source/common/network/io_socket_handle_impl.h"
#include "source/common/network/raw_buffer_socket.h"
#include "source/common/network/udp_listener_impl.h"
#include "source/common/network/udp_packet_writer_handler_impl.h"
#include "source/common/network/utility.h"
#include "test/mocks/access_log/mocks.h"
#include "test/mocks/api/mocks.h"
#include "test/mocks/common.h"
#include "test/mocks/network/mocks.h"
#include "test/test_common/network_utility.h"
#include "test/test_common/test_runtime.h"
#include "test/test_common/threadsafe_singleton_injector.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using testing::_;
using testing::ByMove;
using testing::InSequence;
using testing::Invoke;
using testing::MockFunction;
using testing::NiceMock;
using testing::Return;
using testing::ReturnPointee;
using testing::ReturnRef;
using testing::ReturnRefOfCopy;
using testing::SaveArg;
namespace Envoy {
namespace Server {
namespace {
class MockConnectionHandlerImpl : public ConnectionHandlerImpl {
public:
using ConnectionHandlerImpl::ConnectionHandlerImpl;
MOCK_METHOD(Network::ListenerPtr, createListener,
(Network::SocketSharedPtr && socket, Network::TcpListenerCallbacks& cb,
Runtime::Loader& runtime, Random::RandomGenerator& random,
const Network::ListenerConfig& listener_config,
Server::ThreadLocalOverloadStateOptRef overload_state));
};
class ConnectionHandlerTest : public testing::Test,
protected Logger::Loggable<Logger::Id::main>,
public Event::TestUsingSimulatedTime {
public:
ConnectionHandlerTest()
: handler_(new MockConnectionHandlerImpl(dispatcher_, 0)),
filter_chain_(std::make_shared<NiceMock<Network::MockFilterChain>>()),
listener_filter_matcher_(std::make_shared<NiceMock<Network::MockListenerFilterMatcher>>()),
access_log_(std::make_shared<AccessLog::MockInstance>()) {
ON_CALL(*filter_chain_, transportSocketFactory)
.WillByDefault(ReturnPointee(std::shared_ptr<Network::DownstreamTransportSocketFactory>{
Network::Test::createRawBufferDownstreamSocketFactory()}));
ON_CALL(*filter_chain_, networkFilterFactories)
.WillByDefault(ReturnPointee(std::make_shared<Filter::NetworkFilterFactoriesList>()));
ON_CALL(*listener_filter_matcher_, matches(_)).WillByDefault(Return(false));
}
class TestListenerBase : public Network::ListenerConfig {
public:
TestListenerBase(
ConnectionHandlerTest& parent, uint64_t tag, bool bind_to_port,
bool hand_off_restored_destination_connections, const std::string& name,
Network::Socket::Type socket_type, std::chrono::milliseconds listener_filters_timeout,
bool continue_on_listener_filters_timeout,
std::shared_ptr<AccessLog::MockInstance> access_log,
std::shared_ptr<NiceMock<Network::MockFilterChainManager>> filter_chain_manager = nullptr,
uint32_t tcp_backlog_size = ENVOY_TCP_BACKLOG_SIZE, bool ignore_global_conn_limit = false,
int num_of_socket_factories = 1)
: parent_(parent), tag_(tag), bind_to_port_(bind_to_port),
tcp_backlog_size_(tcp_backlog_size),
hand_off_restored_destination_connections_(hand_off_restored_destination_connections),
name_(name), listener_filters_timeout_(listener_filters_timeout),
continue_on_listener_filters_timeout_(continue_on_listener_filters_timeout),
access_logs_({access_log}), inline_filter_chain_manager_(filter_chain_manager),
init_manager_(nullptr), ignore_global_conn_limit_(ignore_global_conn_limit),
listener_info_(std::make_shared<NiceMock<Network::MockListenerInfo>>()) {
for (int i = 0; i < num_of_socket_factories; i++) {
socket_factories_.emplace_back(std::make_unique<Network::MockListenSocketFactory>());
sockets_.emplace_back(std::make_shared<NiceMock<Network::MockListenSocket>>());
ON_CALL(*sockets_.back().get(), socketType()).WillByDefault(Return(socket_type));
}
envoy::config::listener::v3::UdpListenerConfig udp_config;
udp_listener_config_ = std::make_unique<UdpListenerConfigImpl>(udp_config);
udp_listener_config_->listener_factory_ =
std::make_unique<Server::ActiveRawUdpListenerFactory>(1);
udp_listener_config_->writer_factory_ = std::make_unique<Network::UdpDefaultWriterFactory>();
ON_CALL(*static_cast<Network::MockListenerInfo*>(
const_cast<Network::ListenerInfo*>(listener_info_.get())),
direction())
.WillByDefault(Return(direction_));
}
struct UdpListenerConfigImpl : public Network::UdpListenerConfig {
UdpListenerConfigImpl(const envoy::config::listener::v3::UdpListenerConfig& config)
: config_(config) {}
// Network::UdpListenerConfig
Network::ActiveUdpListenerFactory& listenerFactory() override { return *listener_factory_; }
Network::UdpPacketWriterFactory& packetWriterFactory() override { return *writer_factory_; }
Network::UdpListenerWorkerRouter&
listenerWorkerRouter(const Network::Address::Instance& address) override {
auto iter = listener_worker_router_map_.find(address.asString());
EXPECT_NE(iter, listener_worker_router_map_.end());
return *iter->second;
}
const envoy::config::listener::v3::UdpListenerConfig& config() override { return config_; }
const envoy::config::listener::v3::UdpListenerConfig config_;
std::unique_ptr<Network::ActiveUdpListenerFactory> listener_factory_;
std::unique_ptr<Network::UdpPacketWriterFactory> writer_factory_;
absl::flat_hash_map<std::string, Network::UdpListenerWorkerRouterPtr>
listener_worker_router_map_;
};
// A helper to get the reference of listen socket factory.
Network::MockListenSocketFactory& socketFactory(int index = 0) {
return *static_cast<Network::MockListenSocketFactory*>(socket_factories_[index].get());
}
// Network::ListenerConfig
Network::FilterChainManager& filterChainManager() override {
return inline_filter_chain_manager_ == nullptr ? parent_.manager_
: *inline_filter_chain_manager_;
}
Network::FilterChainFactory& filterChainFactory() override { return parent_.factory_; }
std::vector<Network::ListenSocketFactoryPtr>& listenSocketFactories() override {
return socket_factories_;
}
bool bindToPort() const override { return bind_to_port_; }
bool handOffRestoredDestinationConnections() const override {
return hand_off_restored_destination_connections_;
}
uint32_t perConnectionBufferLimitBytes() const override { return 0; }
std::chrono::milliseconds listenerFiltersTimeout() const override {
return listener_filters_timeout_;
}
bool continueOnListenerFiltersTimeout() const override {
return continue_on_listener_filters_timeout_;
}
Stats::Scope& listenerScope() override { return *parent_.stats_store_.rootScope(); }
uint64_t listenerTag() const override { return tag_; }
const std::string& name() const override { return name_; }
Network::UdpListenerConfigOptRef udpListenerConfig() override { return *udp_listener_config_; }
Network::InternalListenerConfigOptRef internalListenerConfig() override { return {}; }
const Network::ListenerInfoConstSharedPtr& listenerInfo() const override {
return listener_info_;
}
void setDirection(envoy::config::core::v3::TrafficDirection direction) {
direction_ = direction;
}
const std::vector<AccessLog::InstanceSharedPtr>& accessLogs() const override {
return access_logs_;
}
ResourceLimit& openConnections() override { return open_connections_; }
uint32_t tcpBacklogSize() const override { return tcp_backlog_size_; }
uint32_t maxConnectionsToAcceptPerSocketEvent() const override {
return Network::DefaultMaxConnectionsToAcceptPerSocketEvent;
}
Init::Manager& initManager() override { return *init_manager_; }
bool ignoreGlobalConnLimit() const override { return ignore_global_conn_limit_; }
void setMaxConnections(const uint32_t num_connections) {
open_connections_.setMax(num_connections);
}
void clearMaxConnections() { open_connections_.resetMax(); }
ConnectionHandlerTest& parent_;
std::vector<std::shared_ptr<NiceMock<Network::MockListenSocket>>> sockets_;
std::vector<Network::ListenSocketFactoryPtr> socket_factories_;
uint64_t tag_;
bool bind_to_port_;
const uint32_t tcp_backlog_size_;
const bool hand_off_restored_destination_connections_;
const std::string name_;
const std::chrono::milliseconds listener_filters_timeout_;
const bool continue_on_listener_filters_timeout_;
std::unique_ptr<UdpListenerConfigImpl> udp_listener_config_;
BasicResourceLimitImpl open_connections_;
const std::vector<AccessLog::InstanceSharedPtr> access_logs_;
std::shared_ptr<NiceMock<Network::MockFilterChainManager>> inline_filter_chain_manager_;
std::unique_ptr<Init::Manager> init_manager_;
const bool ignore_global_conn_limit_;
envoy::config::core::v3::TrafficDirection direction_;
absl::flat_hash_map<std::string, Network::UdpListenerCallbacks*> udp_listener_callback_map_{};
Network::ListenerInfoConstSharedPtr listener_info_;
};
class TestListener : public TestListenerBase {
public:
TestListener(
ConnectionHandlerTest& parent, uint64_t tag, bool bind_to_port,
bool hand_off_restored_destination_connections, const std::string& name,
Network::Socket::Type socket_type, std::chrono::milliseconds listener_filters_timeout,
bool continue_on_listener_filters_timeout,
std::shared_ptr<AccessLog::MockInstance> access_log,
std::shared_ptr<NiceMock<Network::MockFilterChainManager>> filter_chain_manager = nullptr,
uint32_t tcp_backlog_size = ENVOY_TCP_BACKLOG_SIZE,
Network::ConnectionBalancerSharedPtr connection_balancer = nullptr,
bool ignore_global_conn_limit = false, int num_of_socket_factories = 1)
: TestListenerBase(parent, tag, bind_to_port, hand_off_restored_destination_connections,
name, socket_type, listener_filters_timeout,
continue_on_listener_filters_timeout, access_log, filter_chain_manager,
tcp_backlog_size, ignore_global_conn_limit, num_of_socket_factories),
connection_balancer_(connection_balancer == nullptr
? std::make_shared<Network::NopConnectionBalancerImpl>()
: connection_balancer) {}
Network::ConnectionBalancer& connectionBalancer(const Network::Address::Instance&) override {
return *connection_balancer_;
}
Network::ConnectionBalancerSharedPtr connection_balancer_;
};
class TestMultiAddressesListener : public TestListenerBase {
public:
TestMultiAddressesListener(
ConnectionHandlerTest& parent, uint64_t tag, bool bind_to_port,
bool hand_off_restored_destination_connections, const std::string& name,
Network::Socket::Type socket_type, std::chrono::milliseconds listener_filters_timeout,
bool continue_on_listener_filters_timeout,
std::shared_ptr<AccessLog::MockInstance> access_log,
absl::flat_hash_map<std::string, Network::ConnectionBalancerSharedPtr>&
connection_balancers,
std::shared_ptr<NiceMock<Network::MockFilterChainManager>> filter_chain_manager = nullptr,
uint32_t tcp_backlog_size = ENVOY_TCP_BACKLOG_SIZE, bool ignore_global_conn_limit = false,
int num_of_socket_factories = 1)
: TestListenerBase(parent, tag, bind_to_port, hand_off_restored_destination_connections,
name, socket_type, listener_filters_timeout,
continue_on_listener_filters_timeout, access_log, filter_chain_manager,
tcp_backlog_size, ignore_global_conn_limit, num_of_socket_factories),
connection_balancers_(connection_balancers) {}
Network::ConnectionBalancer&
connectionBalancer(const Network::Address::Instance& address) override {
auto iter = connection_balancers_.find(address.asString());
EXPECT_NE(iter, connection_balancers_.end());
return *iter->second;
}
absl::flat_hash_map<std::string, Network::ConnectionBalancerSharedPtr> connection_balancers_;
};
using TestListenerPtr = std::unique_ptr<TestListenerBase>;
class MockUpstreamUdpFilter : public Network::UdpListenerReadFilter {
public:
MockUpstreamUdpFilter(ConnectionHandlerTest& parent, Network::UdpReadFilterCallbacks& callbacks)
: UdpListenerReadFilter(callbacks), parent_(parent) {}
~MockUpstreamUdpFilter() override {
parent_.deleted_before_listener_ = !parent_.udp_listener_deleted_;
}
MOCK_METHOD(Network::FilterStatus, onData, (Network::UdpRecvData&), (override));
MOCK_METHOD(Network::FilterStatus, onReceiveError, (Api::IoError::IoErrorCode), (override));
private:
ConnectionHandlerTest& parent_;
};
class MockUpstreamUdpListener : public Network::UdpListener {
public:
explicit MockUpstreamUdpListener(ConnectionHandlerTest& parent) : parent_(parent) {
ON_CALL(*this, dispatcher()).WillByDefault(ReturnRef(dispatcher_));
}
~MockUpstreamUdpListener() override { parent_.udp_listener_deleted_ = true; }
MOCK_METHOD(void, enable, (), (override));
MOCK_METHOD(void, disable, (), (override));
MOCK_METHOD(void, setRejectFraction, (UnitFloat));
MOCK_METHOD(void, configureLoadShedPoints, (Server::LoadShedPointProvider&));
MOCK_METHOD(Event::Dispatcher&, dispatcher, (), (override));
MOCK_METHOD(Network::Address::InstanceConstSharedPtr&, localAddress, (), (const, override));
MOCK_METHOD(Api::IoCallUint64Result, send, (const Network::UdpSendData&), (override));
MOCK_METHOD(Api::IoCallUint64Result, flush, (), (override));
MOCK_METHOD(void, activateRead, (), (override));
private:
ConnectionHandlerTest& parent_;
Event::MockDispatcher dispatcher_;
};
TestListener* addListener(
uint64_t tag, bool bind_to_port, bool hand_off_restored_destination_connections,
const std::string& name, Network::Listener* listener,
Network::TcpListenerCallbacks** listener_callbacks = nullptr,
Network::Address::InstanceConstSharedPtr address = nullptr,
std::shared_ptr<Network::MockConnectionBalancer> connection_balancer = nullptr,
Network::BalancedConnectionHandler** balanced_connection_handler = nullptr,
Network::Socket::Type socket_type = Network::Socket::Type::Stream,
std::chrono::milliseconds listener_filters_timeout = std::chrono::milliseconds(15000),
bool continue_on_listener_filters_timeout = false,
std::shared_ptr<NiceMock<Network::MockFilterChainManager>> overridden_filter_chain_manager =
nullptr,
uint32_t tcp_backlog_size = ENVOY_TCP_BACKLOG_SIZE, bool ignore_global_conn_limit = false) {
auto test_listener = std::make_unique<TestListener>(
*this, tag, bind_to_port, hand_off_restored_destination_connections, name, socket_type,
listener_filters_timeout, continue_on_listener_filters_timeout, access_log_,
overridden_filter_chain_manager, tcp_backlog_size, connection_balancer,
ignore_global_conn_limit);
TestListener* test_listener_raw_ptr = test_listener.get();
listeners_.emplace_back(std::move(test_listener));
if (listener == nullptr) {
// Expecting listener config in place update.
// If so, dispatcher would not create new network listener.
return test_listener_raw_ptr;
}
EXPECT_CALL(listeners_.back()->socketFactory(), socketType()).WillOnce(Return(socket_type));
if (address == nullptr) {
EXPECT_CALL(listeners_.back()->socketFactory(), localAddress())
.WillRepeatedly(ReturnRef(local_address_));
listeners_.back()->sockets_[0]->connection_info_provider_->setLocalAddress(local_address_);
} else {
EXPECT_CALL(listeners_.back()->socketFactory(), localAddress())
.WillRepeatedly(ReturnRefOfCopy(address));
listeners_.back()->sockets_[0]->connection_info_provider_->setLocalAddress(address);
}
EXPECT_CALL(listeners_.back()->socketFactory(), getListenSocket(_))
.WillOnce(Return(listeners_.back()->sockets_[0]));
if (socket_type == Network::Socket::Type::Stream) {
EXPECT_CALL(*handler_, createListener(_, _, _, _, _, _))
.WillOnce(
Invoke([listener, listener_callbacks](
Network::SocketSharedPtr&&, Network::TcpListenerCallbacks& cb,
Runtime::Loader&, Random::RandomGenerator&, const Network::ListenerConfig&,
Server::ThreadLocalOverloadStateOptRef) -> Network::ListenerPtr {
if (listener_callbacks != nullptr) {
*listener_callbacks = &cb;
}
return std::unique_ptr<Network::Listener>(listener);
}));
} else {
delete listener;
if (address == nullptr) {
listeners_.back()->udp_listener_config_->listener_worker_router_map_.emplace(
local_address_->asString(),
std::make_unique<NiceMock<Network::MockUdpListenerWorkerRouter>>());
} else {
listeners_.back()->udp_listener_config_->listener_worker_router_map_.emplace(
address->asString(),
std::make_unique<NiceMock<Network::MockUdpListenerWorkerRouter>>());
}
}
if (balanced_connection_handler != nullptr) {
EXPECT_CALL(*connection_balancer, registerHandler(_))
.WillOnce(SaveArgAddress(balanced_connection_handler));
}
return test_listener_raw_ptr;
}
TestMultiAddressesListener* addMultiAddrsListener(
uint64_t tag, bool bind_to_port, bool hand_off_restored_destination_connections,
const std::string& name, std::vector<Network::Listener*>& mock_listeners,
std::vector<Network::Address::InstanceConstSharedPtr>& addresses,
absl::flat_hash_map<std::string, Network::ConnectionBalancerSharedPtr>& connection_balancers,
absl::flat_hash_map<std::string, Network::TcpListenerCallbacks**>& listener_callbacks_map,
bool disable_listener = false,
Network::Socket::Type socket_type = Network::Socket::Type::Stream) {
if (connection_balancers.empty() && socket_type == Network::Socket::Type::Stream) {
for (auto& address : addresses) {
connection_balancers.emplace(address->asString(),
std::make_shared<Network::NopConnectionBalancerImpl>());
}
}
auto test_listener = std::make_unique<TestMultiAddressesListener>(
*this, tag, bind_to_port, hand_off_restored_destination_connections, name, socket_type,
std::chrono::milliseconds(15000), false, access_log_, connection_balancers, nullptr,
ENVOY_TCP_BACKLOG_SIZE, false, mock_listeners.size());
TestMultiAddressesListener* test_listener_raw_ptr = test_listener.get();
listeners_.emplace_back(std::move(test_listener));
EXPECT_CALL(listeners_.back()->socketFactory(0), socketType()).WillOnce(Return(socket_type));
for (std::vector<Network::Listener*>::size_type i = 0; i < mock_listeners.size(); i++) {
EXPECT_CALL(listeners_.back()->socketFactory(i), localAddress())
.WillRepeatedly(ReturnRef(addresses[i]));
EXPECT_CALL(listeners_.back()->socketFactory(i), getListenSocket(_))
.WillOnce(Return(listeners_.back()->sockets_[i]));
test_listener_raw_ptr->sockets_[i]->connection_info_provider_->setLocalAddress(addresses[i]);
if (socket_type == Network::Socket::Type::Stream) {
EXPECT_CALL(*handler_, createListener(_, _, _, _, _, _))
.WillOnce(Invoke([i, &mock_listeners, &listener_callbacks_map](
Network::SocketSharedPtr&& socket,
Network::TcpListenerCallbacks& cb, Runtime::Loader&,
Random::RandomGenerator&, const Network::ListenerConfig&,
Server::ThreadLocalOverloadStateOptRef) -> Network::ListenerPtr {
auto listener_callbacks_iter = listener_callbacks_map.find(
socket->connectionInfoProvider().localAddress()->asString());
EXPECT_NE(listener_callbacks_iter, listener_callbacks_map.end());
*listener_callbacks_iter->second = &cb;
return std::unique_ptr<Network::Listener>(mock_listeners[i]);
}))
.RetiresOnSaturation();
} else {
listeners_.back()->udp_listener_config_->listener_worker_router_map_.emplace(
addresses[i]->asString(),
std::make_unique<NiceMock<Network::MockUdpListenerWorkerRouter>>());
}
if (disable_listener) {
EXPECT_CALL(*static_cast<Network::MockListener*>(mock_listeners[i]), disable());
}
}
return test_listener_raw_ptr;
}
void validateOriginalDst(Network::TcpListenerCallbacks** listener_callbacks,
TestListener* test_listener, Network::MockListener* listener) {
Network::Address::InstanceConstSharedPtr normal_address(
new Network::Address::Ipv4Instance("127.0.0.1", 80));
// Original dst address nor port number match that of the listener's address.
Network::Address::InstanceConstSharedPtr original_dst_address(
new Network::Address::Ipv4Instance("127.0.0.2", 8080));
Network::Address::InstanceConstSharedPtr any_address = Network::Utility::getAddressWithPort(
*Network::Utility::getIpv4AnyAddress(), normal_address->ip()->port());
EXPECT_CALL(test_listener->socketFactory(), localAddress())
.WillRepeatedly(ReturnRef(any_address));
handler_->addListener(absl::nullopt, *test_listener, runtime_, random_);
Network::MockListenerFilter* test_filter = new Network::MockListenerFilter();
Network::MockConnectionSocket* accepted_socket = new NiceMock<Network::MockConnectionSocket>();
EXPECT_CALL(factory_, createListenerFilterChain(_))
.WillRepeatedly(Invoke([&](Network::ListenerFilterManager& manager) -> bool {
// Insert the Mock filter.
manager.addAcceptFilter(listener_filter_matcher_,
Network::ListenerFilterPtr{test_filter});
return true;
}));
EXPECT_CALL(*test_filter, onAccept(_))
.WillOnce(Invoke([&](Network::ListenerFilterCallbacks& cb) -> Network::FilterStatus {
cb.socket().connectionInfoProvider().restoreLocalAddress(original_dst_address);
return Network::FilterStatus::Continue;
}));
EXPECT_CALL(*test_filter, destroy_());
EXPECT_CALL(manager_, findFilterChain(_, _)).WillOnce(Return(filter_chain_.get()));
auto* connection = new NiceMock<Network::MockServerConnection>();
EXPECT_CALL(dispatcher_, createServerConnection_()).WillOnce(Return(connection));
EXPECT_CALL(factory_, createNetworkFilterChain(_, _)).WillOnce(Return(true));
(*listener_callbacks)->onAccept(Network::ConnectionSocketPtr{accepted_socket});
EXPECT_EQ(1UL, handler_->numConnections());
EXPECT_CALL(*listener, onDestroy());
EXPECT_CALL(*access_log_, log(_, _));
}
Stats::TestUtil::TestStore stats_store_;
Network::Address::InstanceConstSharedPtr local_address_{
new Network::Address::Ipv4Instance("127.0.0.1", 10001)};
NiceMock<Event::MockDispatcher> dispatcher_{"test"};
std::list<TestListenerPtr> listeners_;
std::unique_ptr<MockConnectionHandlerImpl> handler_;
NiceMock<Network::MockFilterChainManager> manager_;
NiceMock<Network::MockFilterChainFactory> factory_;
const std::shared_ptr<Network::MockFilterChain> filter_chain_;
NiceMock<Api::MockOsSysCalls> os_sys_calls_;
TestThreadsafeSingletonInjector<Api::OsSysCallsImpl> os_calls_{&os_sys_calls_};
std::shared_ptr<NiceMock<Network::MockListenerFilterMatcher>> listener_filter_matcher_;
bool udp_listener_deleted_ = false;
bool deleted_before_listener_ = false;
std::shared_ptr<AccessLog::MockInstance> access_log_;
TestScopedRuntime scoped_runtime_;
Runtime::Loader& runtime_{scoped_runtime_.loader()};
testing::NiceMock<Random::MockRandomGenerator> random_;
};
// Verify that if a listener is removed while a rebalanced connection is in flight, we correctly
// destroy the connection.
TEST_F(ConnectionHandlerTest, RemoveListenerDuringRebalance) {
InSequence s;
// For reasons I did not investigate, the death test below requires this, likely due to
// forking.
// So we just leak the FDs for this test.
ON_CALL(os_sys_calls_, close(_)).WillByDefault(Return(Api::SysCallIntResult{0, 0}));
Network::TcpListenerCallbacks* listener_callbacks;
auto listener = new NiceMock<Network::MockListener>();
auto connection_balancer = std::make_shared<Network::MockConnectionBalancer>();
Network::BalancedConnectionHandler* current_handler;
TestListener* test_listener =
addListener(1, true, false, "test_listener", listener, &listener_callbacks, nullptr,
connection_balancer, ¤t_handler);
handler_->addListener(absl::nullopt, *test_listener, runtime_, random_);
// Fake a balancer posting a connection to us.
Event::PostCb post_cb;
EXPECT_CALL(dispatcher_, post(_)).WillOnce([&post_cb](Event::PostCb cb) {
post_cb = std::move(cb);
});
Network::MockConnectionSocket* connection = new NiceMock<Network::MockConnectionSocket>();
current_handler->incNumConnections();
#ifndef NDEBUG
EXPECT_CALL(*access_log_, log(_, _));
#endif
current_handler->post(Network::ConnectionSocketPtr{connection});
EXPECT_CALL(*connection_balancer, unregisterHandler(_));
// This also tests the assert in ConnectionHandlerImpl::ActiveTcpListener::~ActiveTcpListener.
// See the long comment at the end of that function.
#ifndef NDEBUG
// On debug builds this should crash.
EXPECT_DEATH(handler_->removeListeners(1), ".*num_listener_connections_ == 0.*");
// The original test continues without the previous line being run. To avoid the same assert
// firing during teardown, run the posted callback now.
post_cb();
ASSERT(post_cb != nullptr);
EXPECT_CALL(*listener, onDestroy());
#else
// On release builds this should be fine.
EXPECT_CALL(*listener, onDestroy());
handler_->removeListeners(1);
post_cb();
#endif
}
TEST_F(ConnectionHandlerTest, ListenerConnectionLimitEnforced) {
Network::TcpListenerCallbacks* listener_callbacks1;
auto listener1 = new NiceMock<Network::MockListener>();
Network::Address::InstanceConstSharedPtr normal_address(
new Network::Address::Ipv4Instance("127.0.0.1", 10001));
TestListener* test_listener1 = addListener(1, false, false, "test_listener1", listener1,
&listener_callbacks1, normal_address);
// Only allow a single connection on this listener.
test_listener1->setMaxConnections(1);
handler_->addListener(absl::nullopt, *test_listener1, runtime_, random_);
auto listener2 = new NiceMock<Network::MockListener>();
Network::TcpListenerCallbacks* listener_callbacks2;
Network::Address::InstanceConstSharedPtr alt_address(
new Network::Address::Ipv4Instance("127.0.0.2", 20002));
TestListener* test_listener2 =
addListener(2, false, false, "test_listener2", listener2, &listener_callbacks2, alt_address);
// Do not allow any connections on this listener.
test_listener2->setMaxConnections(0);
handler_->addListener(absl::nullopt, *test_listener2, runtime_, random_);
EXPECT_CALL(manager_, findFilterChain(_, _)).WillRepeatedly(Return(filter_chain_.get()));
EXPECT_CALL(factory_, createNetworkFilterChain(_, _)).WillRepeatedly(Return(true));
Network::MockListenerFilter* test_filter = new Network::MockListenerFilter();
EXPECT_CALL(*test_filter, destroy_());
EXPECT_CALL(factory_, createListenerFilterChain(_))
.WillRepeatedly(Invoke([&](Network::ListenerFilterManager& manager) -> bool {
manager.addAcceptFilter(listener_filter_matcher_, Network::ListenerFilterPtr{test_filter});
return true;
}));
EXPECT_CALL(*test_filter, onAccept(_))
.WillRepeatedly(Invoke([&](Network::ListenerFilterCallbacks&) -> Network::FilterStatus {
return Network::FilterStatus::Continue;
}));
// For listener 2, verify its connection limit is independent of listener 1.
// We expect that listener 2 accepts the connection, so there will be a call to
// createServerConnection and active cx should increase, while cx overflow remains the same.
EXPECT_CALL(*access_log_, log(_, _));
listener_callbacks2->onAccept(
Network::ConnectionSocketPtr{new NiceMock<Network::MockConnectionSocket>()});
EXPECT_EQ(0, handler_->numConnections());
EXPECT_EQ(0, TestUtility::findCounter(stats_store_, "downstream_cx_total")->value());
EXPECT_EQ(0, TestUtility::findGauge(stats_store_, "downstream_cx_active")->value());
EXPECT_EQ(1, TestUtility::findCounter(stats_store_, "downstream_cx_overflow")->value());
// For listener 1, verify connections are limited after one goes active.
// First connection attempt should result in an active connection being created.
auto conn1 = new NiceMock<Network::MockServerConnection>();
EXPECT_CALL(dispatcher_, createServerConnection_()).WillOnce(Return(conn1));
listener_callbacks1->onAccept(
Network::ConnectionSocketPtr{new NiceMock<Network::MockConnectionSocket>()});
EXPECT_EQ(1, handler_->numConnections());
// Note that these stats are not the per-worker stats, but the per-listener stats.
EXPECT_EQ(1, TestUtility::findCounter(stats_store_, "downstream_cx_total")->value());
EXPECT_EQ(1, TestUtility::findGauge(stats_store_, "downstream_cx_active")->value());
EXPECT_EQ(1, TestUtility::findCounter(stats_store_, "downstream_cx_overflow")->value());
// Don't expect server connection to be created, should be instantly closed and increment
// overflow stat.
listener_callbacks1->onAccept(
Network::ConnectionSocketPtr{new NiceMock<Network::MockConnectionSocket>()});
EXPECT_EQ(1, handler_->numConnections());
EXPECT_EQ(1, TestUtility::findCounter(stats_store_, "downstream_cx_total")->value());
EXPECT_EQ(1, TestUtility::findGauge(stats_store_, "downstream_cx_active")->value());
EXPECT_EQ(2, TestUtility::findCounter(stats_store_, "downstream_cx_overflow")->value());
// Check behavior again for good measure.
listener_callbacks1->onAccept(
Network::ConnectionSocketPtr{new NiceMock<Network::MockConnectionSocket>()});
EXPECT_EQ(1, handler_->numConnections());
EXPECT_EQ(1, TestUtility::findCounter(stats_store_, "downstream_cx_total")->value());
EXPECT_EQ(1, TestUtility::findGauge(stats_store_, "downstream_cx_active")->value());
EXPECT_EQ(3, TestUtility::findCounter(stats_store_, "downstream_cx_overflow")->value());
EXPECT_CALL(*listener1, onDestroy());
EXPECT_CALL(*listener2, onDestroy());
}
TEST_F(ConnectionHandlerTest, RemoveListener) {
InSequence s;
Network::TcpListenerCallbacks* listener_callbacks;
auto listener = new NiceMock<Network::MockListener>();
TestListener* test_listener =
addListener(1, true, false, "test_listener", listener, &listener_callbacks);
handler_->addListener(absl::nullopt, *test_listener, runtime_, random_);
Network::MockConnectionSocket* connection = new NiceMock<Network::MockConnectionSocket>();
EXPECT_CALL(*access_log_, log(_, _));
listener_callbacks->onAccept(Network::ConnectionSocketPtr{connection});
EXPECT_EQ(0UL, handler_->numConnections());
// Test stop/remove of not existent listener.
handler_->stopListeners(0, {});
handler_->removeListeners(0);
EXPECT_CALL(*listener, onDestroy());
handler_->stopListeners(1, {});
EXPECT_CALL(dispatcher_, clearDeferredDeleteList());
handler_->removeListeners(1);
EXPECT_EQ(0UL, handler_->numConnections());
// Test stop/remove of not existent listener.
handler_->stopListeners(0, {});
handler_->removeListeners(0);
}
TEST_F(ConnectionHandlerTest, RemoveListenerWithMultiAddrs) {
InSequence s;
auto listener1 = new NiceMock<Network::MockListener>();
auto listener2 = new NiceMock<Network::MockListener>();
std::vector<Network::Listener*> mock_listeners;
mock_listeners.emplace_back(listener1);
mock_listeners.emplace_back(listener2);
Network::Address::InstanceConstSharedPtr address1(
new Network::Address::Ipv4Instance("127.0.0.1", 80, nullptr));
Network::Address::InstanceConstSharedPtr address2(
new Network::Address::Ipv4Instance("127.0.0.2", 80, nullptr));
std::vector<Network::Address::InstanceConstSharedPtr> addresses;
addresses.emplace_back(address1);
addresses.emplace_back(address2);
Network::TcpListenerCallbacks* listener_callbacks1;
Network::TcpListenerCallbacks* listener_callbacks2;
absl::flat_hash_map<std::string, Network::TcpListenerCallbacks**> listener_callbacks_map;
listener_callbacks_map.emplace(address1->asString(), &listener_callbacks1);
listener_callbacks_map.emplace(address2->asString(), &listener_callbacks2);
absl::flat_hash_map<std::string, Network::ConnectionBalancerSharedPtr> connection_balancers;
TestMultiAddressesListener* test_listener =
addMultiAddrsListener(1, true, false, "test_listener", mock_listeners, addresses,
connection_balancers, listener_callbacks_map);
handler_->addListener(absl::nullopt, *test_listener, runtime_, random_);
Network::MockConnectionSocket* connection = new NiceMock<Network::MockConnectionSocket>();
EXPECT_CALL(*access_log_, log(_, _));
listener_callbacks1->onAccept(Network::ConnectionSocketPtr{connection});
EXPECT_EQ(0UL, handler_->numConnections());
// Test stop/remove of not existent listener.
handler_->stopListeners(0, {});
handler_->removeListeners(0);
EXPECT_CALL(*listener1, onDestroy());
EXPECT_CALL(*listener2, onDestroy());
handler_->stopListeners(1, {});
EXPECT_CALL(dispatcher_, clearDeferredDeleteList()).Times(2);
handler_->removeListeners(1);
EXPECT_EQ(0UL, handler_->numConnections());
// Test stop/remove of not existent listener.
handler_->stopListeners(0, {});
handler_->removeListeners(0);
}
TEST_F(ConnectionHandlerTest, DisableListener) {
InSequence s;
Network::TcpListenerCallbacks* listener_callbacks;
auto listener = new NiceMock<Network::MockListener>();
TestListener* test_listener =
addListener(1, false, false, "test_listener", listener, &listener_callbacks);
handler_->addListener(absl::nullopt, *test_listener, runtime_, random_);
EXPECT_CALL(*listener, disable());
EXPECT_CALL(*listener, onDestroy());
handler_->disableListeners();
}
TEST_F(ConnectionHandlerTest, DisableListenerWithMultiAddrs) {
auto listener1 = new NiceMock<Network::MockListener>();
auto listener2 = new NiceMock<Network::MockListener>();
std::vector<Network::Listener*> mock_listeners;
mock_listeners.emplace_back(listener1);
mock_listeners.emplace_back(listener2);
Network::Address::InstanceConstSharedPtr address1(
new Network::Address::Ipv4Instance("127.0.0.1", 80, nullptr));
Network::Address::InstanceConstSharedPtr address2(
new Network::Address::Ipv4Instance("127.0.0.2", 80, nullptr));
std::vector<Network::Address::InstanceConstSharedPtr> addresses;
addresses.emplace_back(address1);
addresses.emplace_back(address2);
Network::TcpListenerCallbacks* listener_callbacks1;
Network::TcpListenerCallbacks* listener_callbacks2;
absl::flat_hash_map<std::string, Network::TcpListenerCallbacks**> listener_callbacks_map;
listener_callbacks_map.emplace(address1->asString(), &listener_callbacks1);
listener_callbacks_map.emplace(address2->asString(), &listener_callbacks2);
absl::flat_hash_map<std::string, Network::ConnectionBalancerSharedPtr> connection_balancers;
TestMultiAddressesListener* test_listener =
addMultiAddrsListener(1, false, false, "test_listener", mock_listeners, addresses,
connection_balancers, listener_callbacks_map);
handler_->addListener(absl::nullopt, *test_listener, runtime_, random_);
EXPECT_CALL(*listener1, disable());
EXPECT_CALL(*listener2, disable());
EXPECT_CALL(*listener1, onDestroy());
EXPECT_CALL(*listener2, onDestroy());
handler_->disableListeners();
}
TEST_F(ConnectionHandlerTest, RebalanceWithMultiAddressListener) {
auto listener1 = new NiceMock<Network::MockListener>();
auto listener2 = new NiceMock<Network::MockListener>();
std::vector<Network::Listener*> mock_listeners;
mock_listeners.emplace_back(listener1);
mock_listeners.emplace_back(listener2);
Network::Address::InstanceConstSharedPtr address1(
new Network::Address::Ipv4Instance("127.0.0.1", 80, nullptr));
Network::Address::InstanceConstSharedPtr address2(
new Network::Address::Ipv4Instance("127.0.0.2", 80, nullptr));
std::vector<Network::Address::InstanceConstSharedPtr> addresses;
addresses.emplace_back(address1);
addresses.emplace_back(address2);
Network::TcpListenerCallbacks* listener_callbacks1;
Network::TcpListenerCallbacks* listener_callbacks2;
absl::flat_hash_map<std::string, Network::TcpListenerCallbacks**> listener_callbacks_map;
listener_callbacks_map.emplace(address1->asString(), &listener_callbacks1);
listener_callbacks_map.emplace(address2->asString(), &listener_callbacks2);
absl::flat_hash_map<std::string, Network::ConnectionBalancerSharedPtr> connection_balancers;
auto mock_connection_balancer1 = std::make_shared<Network::MockConnectionBalancer>();
auto mock_connection_balancer2 = std::make_shared<Network::MockConnectionBalancer>();
connection_balancers.emplace(address1->asString(), mock_connection_balancer1);
connection_balancers.emplace(address2->asString(), mock_connection_balancer2);
Network::BalancedConnectionHandler* current_handler1;
Network::BalancedConnectionHandler* current_handler2;
EXPECT_CALL(*mock_connection_balancer1, registerHandler(_))
.WillOnce(SaveArgAddress(¤t_handler1));
EXPECT_CALL(*mock_connection_balancer2, registerHandler(_))
.WillOnce(SaveArgAddress(¤t_handler2));
TestMultiAddressesListener* test_listener =
addMultiAddrsListener(1, false, false, "test_listener", mock_listeners, addresses,
connection_balancers, listener_callbacks_map);
handler_->addListener(absl::nullopt, *test_listener, runtime_, random_);
// Send connection to the first listener, expect mock_connection_balancer1 will be called.
// then mock_connection_balancer1 will balance the connection to the same listener.
EXPECT_CALL(*mock_connection_balancer1, pickTargetHandler(_))
.WillOnce(ReturnRef(*current_handler1));
EXPECT_CALL(*access_log_, log(_, _));
EXPECT_CALL(manager_, findFilterChain(_, _)).WillOnce(Return(nullptr));
current_handler1->incNumConnections();
listener_callbacks1->onAccept(std::make_unique<NiceMock<Network::MockConnectionSocket>>());
// Send connection to the second listener, expect mock_connection_balancer2 will be called.
// then mock_connection_balancer2 will balance the connection to the same listener.
EXPECT_CALL(*mock_connection_balancer2, pickTargetHandler(_))
.WillOnce(ReturnRef(*current_handler2));
EXPECT_CALL(*access_log_, log(_, _));
EXPECT_CALL(manager_, findFilterChain(_, _)).WillOnce(Return(nullptr));
current_handler2->incNumConnections();
listener_callbacks2->onAccept(std::make_unique<NiceMock<Network::MockConnectionSocket>>());
EXPECT_CALL(*mock_connection_balancer1, unregisterHandler(_));
EXPECT_CALL(*mock_connection_balancer2, unregisterHandler(_));
EXPECT_CALL(*listener1, onDestroy());
EXPECT_CALL(*listener2, onDestroy());
}
// Envoy doesn't have such case yet, just ensure the code won't break with it.
TEST_F(ConnectionHandlerTest, StopAndDisableStoppedListener) {
InSequence s;
Network::TcpListenerCallbacks* listener_callbacks;
auto listener = new NiceMock<Network::MockListener>();
TestListener* test_listener =
addListener(1, false, false, "test_listener", listener, &listener_callbacks);
handler_->addListener(absl::nullopt, *test_listener, runtime_, random_);
EXPECT_CALL(*listener, onDestroy());
handler_->stopListeners(1, {});
// Test stop a stopped listener.
handler_->stopListeners(1, {});
// Test disable a stopped listener.
handler_->disableListeners();
}
TEST_F(ConnectionHandlerTest, AddDisabledListener) {
InSequence s;
Network::TcpListenerCallbacks* listener_callbacks;
auto listener = new NiceMock<Network::MockListener>();
TestListener* test_listener =
addListener(1, false, false, "test_listener", listener, &listener_callbacks);
EXPECT_CALL(*listener, disable());
EXPECT_CALL(*listener, onDestroy());
handler_->disableListeners();
handler_->addListener(absl::nullopt, *test_listener, runtime_, random_);
}
TEST_F(ConnectionHandlerTest, AddDisabledListenerWithMultiAddrs) {
auto listener1 = new NiceMock<Network::MockListener>();
auto listener2 = new NiceMock<Network::MockListener>();
std::vector<Network::Listener*> mock_listeners;
mock_listeners.emplace_back(listener1);
mock_listeners.emplace_back(listener2);
Network::Address::InstanceConstSharedPtr address1(
new Network::Address::Ipv4Instance("127.0.0.1", 80, nullptr));
Network::Address::InstanceConstSharedPtr address2(
new Network::Address::Ipv4Instance("127.0.0.2", 80, nullptr));
std::vector<Network::Address::InstanceConstSharedPtr> addresses;
addresses.emplace_back(address1);
addresses.emplace_back(address2);
Network::TcpListenerCallbacks* listener_callbacks1;
Network::TcpListenerCallbacks* listener_callbacks2;
absl::flat_hash_map<std::string, Network::TcpListenerCallbacks**> listener_callbacks_map;
listener_callbacks_map.emplace(address1->asString(), &listener_callbacks1);
listener_callbacks_map.emplace(address2->asString(), &listener_callbacks2);
absl::flat_hash_map<std::string, Network::ConnectionBalancerSharedPtr> connection_balancers;
TestMultiAddressesListener* test_listener =
addMultiAddrsListener(1, false, false, "test_listener", mock_listeners, addresses,
connection_balancers, listener_callbacks_map, true);
EXPECT_CALL(*listener1, onDestroy());
EXPECT_CALL(*listener2, onDestroy());
handler_->disableListeners();
handler_->addListener(absl::nullopt, *test_listener, runtime_, random_);
}
TEST_F(ConnectionHandlerTest, SetListenerRejectFraction) {
InSequence s;
Network::TcpListenerCallbacks* listener_callbacks;
auto listener = new NiceMock<Network::MockListener>();
TestListener* test_listener =
addListener(1, false, false, "test_listener", listener, &listener_callbacks);
handler_->addListener(absl::nullopt, *test_listener, runtime_, random_);
EXPECT_CALL(*listener, setRejectFraction(UnitFloat(0.1234f)));
EXPECT_CALL(*listener, onDestroy());
handler_->setListenerRejectFraction(UnitFloat(0.1234f));
}
TEST_F(ConnectionHandlerTest, AddListenerSetRejectFraction) {
InSequence s;
Network::TcpListenerCallbacks* listener_callbacks;
auto listener = new NiceMock<Network::MockListener>();
TestListener* test_listener =
addListener(1, false, false, "test_listener", listener, &listener_callbacks);
EXPECT_CALL(*listener, setRejectFraction(UnitFloat(0.12345f)));
EXPECT_CALL(*listener, onDestroy());
handler_->setListenerRejectFraction(UnitFloat(0.12345f));
handler_->addListener(absl::nullopt, *test_listener, runtime_, random_);
}
TEST_F(ConnectionHandlerTest, SetsTransportSocketConnectTimeout) {
InSequence s;
Network::TcpListenerCallbacks* listener_callbacks;
auto listener = new NiceMock<Network::MockListener>();
TestListener* test_listener =
addListener(1, false, false, "test_listener", listener, &listener_callbacks);
handler_->addListener(absl::nullopt, *test_listener, runtime_, random_);
auto server_connection = new NiceMock<Network::MockServerConnection>();
EXPECT_CALL(manager_, findFilterChain(_, _)).WillOnce(Return(filter_chain_.get()));
EXPECT_CALL(dispatcher_, createServerConnection_()).WillOnce(Return(server_connection));
EXPECT_CALL(*filter_chain_, transportSocketConnectTimeout)
.WillOnce(Return(std::chrono::seconds(5)));
EXPECT_CALL(*server_connection,
setTransportSocketConnectTimeout(std::chrono::milliseconds(5 * 1000), _));
EXPECT_CALL(*access_log_, log(_, _));
listener_callbacks->onAccept(std::make_unique<NiceMock<Network::MockConnectionSocket>>());
EXPECT_CALL(*listener, onDestroy());
}
TEST_F(ConnectionHandlerTest, DestroyCloseConnections) {
InSequence s;
Network::TcpListenerCallbacks* listener_callbacks;
auto listener = new NiceMock<Network::MockListener>();
TestListener* test_listener =
addListener(1, true, false, "test_listener", listener, &listener_callbacks);
handler_->addListener(absl::nullopt, *test_listener, runtime_, random_);
Network::MockConnectionSocket* connection = new NiceMock<Network::MockConnectionSocket>();
EXPECT_CALL(*access_log_, log(_, _));
listener_callbacks->onAccept(Network::ConnectionSocketPtr{connection});
EXPECT_EQ(0UL, handler_->numConnections());
EXPECT_CALL(dispatcher_, clearDeferredDeleteList());
EXPECT_CALL(*listener, onDestroy());
handler_.reset();
}
TEST_F(ConnectionHandlerTest, CloseDuringFilterChainCreate) {
InSequence s;
Network::TcpListenerCallbacks* listener_callbacks;
auto listener = new NiceMock<Network::MockListener>();
TestListener* test_listener =
addListener(1, true, false, "test_listener", listener, &listener_callbacks);
handler_->addListener(absl::nullopt, *test_listener, runtime_, random_);
EXPECT_CALL(manager_, findFilterChain(_, _)).WillOnce(Return(filter_chain_.get()));
auto* connection = new NiceMock<Network::MockServerConnection>();
EXPECT_CALL(dispatcher_, createServerConnection_()).WillOnce(Return(connection));
EXPECT_CALL(factory_, createNetworkFilterChain(_, _)).WillOnce(Return(true));
EXPECT_CALL(*connection, state()).WillOnce(Return(Network::Connection::State::Closed));
EXPECT_CALL(*connection, addConnectionCallbacks(_)).Times(0);
EXPECT_CALL(*access_log_, log(_, _));
Network::MockConnectionSocket* accepted_socket = new NiceMock<Network::MockConnectionSocket>();
listener_callbacks->onAccept(Network::ConnectionSocketPtr{accepted_socket});
EXPECT_EQ(0UL, handler_->numConnections());
EXPECT_CALL(*listener, onDestroy());
}
TEST_F(ConnectionHandlerTest, CloseConnectionOnEmptyFilterChain) {
InSequence s;
Network::TcpListenerCallbacks* listener_callbacks;
auto listener = new NiceMock<Network::MockListener>();
TestListener* test_listener =
addListener(1, true, false, "test_listener", listener, &listener_callbacks);
handler_->addListener(absl::nullopt, *test_listener, runtime_, random_);
EXPECT_CALL(manager_, findFilterChain(_, _)).WillOnce(Return(filter_chain_.get()));
auto* connection = new NiceMock<Network::MockServerConnection>();
EXPECT_CALL(dispatcher_, createServerConnection_()).WillOnce(Return(connection));
EXPECT_CALL(factory_, createNetworkFilterChain(_, _)).WillOnce(Return(false));
EXPECT_CALL(*connection, close(Network::ConnectionCloseType::NoFlush, _));
EXPECT_CALL(*connection, addConnectionCallbacks(_)).Times(0);
EXPECT_CALL(*access_log_, log(_, _));
Network::MockConnectionSocket* accepted_socket = new NiceMock<Network::MockConnectionSocket>();
listener_callbacks->onAccept(Network::ConnectionSocketPtr{accepted_socket});
EXPECT_EQ(0UL, handler_->numConnections());
EXPECT_CALL(*listener, onDestroy());
}
TEST_F(ConnectionHandlerTest, NormalRedirect) {
Network::TcpListenerCallbacks* listener_callbacks1;
auto listener1 = new NiceMock<Network::MockListener>();
Network::Address::InstanceConstSharedPtr normal_address(
new Network::Address::Ipv4Instance("127.0.0.1", 10001));
TestListener* test_listener1 =
addListener(1, true, true, "test_listener1", listener1, &listener_callbacks1, normal_address);
handler_->addListener(absl::nullopt, *test_listener1, runtime_, random_);