-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
cluster_manager_impl_test.cc
6833 lines (6043 loc) · 274 KB
/
cluster_manager_impl_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 "envoy/admin/v3/config_dump.pb.h"
#include "envoy/config/bootstrap/v3/bootstrap.pb.h"
#include "envoy/config/cluster/v3/cluster.pb.h"
#include "envoy/config/cluster/v3/cluster.pb.validate.h"
#include "envoy/config/core/v3/base.pb.h"
#include "source/common/config/xds_resource.h"
#include "source/common/network/raw_buffer_socket.h"
#include "source/common/network/resolver_impl.h"
#include "source/common/router/context_impl.h"
#include "source/common/upstream/load_balancer_factory_base.h"
#include "source/extensions/load_balancing_policies/subset/subset_lb.h"
#include "source/extensions/transport_sockets/raw_buffer/config.h"
#include "test/common/upstream/test_cluster_manager.h"
#include "test/config/v2_link_hacks.h"
#include "test/mocks/config/mocks.h"
#include "test/mocks/http/conn_pool.h"
#include "test/mocks/matcher/mocks.h"
#include "test/mocks/protobuf/mocks.h"
#include "test/mocks/server/instance.h"
#include "test/mocks/upstream/cds_api.h"
#include "test/mocks/upstream/cluster_priority_set.h"
#include "test/mocks/upstream/cluster_real_priority_set.h"
#include "test/mocks/upstream/cluster_update_callbacks.h"
#include "test/mocks/upstream/health_checker.h"
#include "test/mocks/upstream/load_balancer_context.h"
#include "test/mocks/upstream/od_cds_api.h"
#include "test/mocks/upstream/thread_aware_load_balancer.h"
#include "test/test_common/test_runtime.h"
#include "test/test_common/utility.h"
namespace Envoy {
namespace Upstream {
class HttpPoolDataPeer {
public:
static Http::ConnectionPool::MockInstance* getPool(absl::optional<HttpPoolData> data) {
ASSERT(data.has_value());
return dynamic_cast<Http::ConnectionPool::MockInstance*>(data.value().pool_);
}
};
class TcpPoolDataPeer {
public:
static Tcp::ConnectionPool::MockInstance* getPool(absl::optional<TcpPoolData> data) {
ASSERT(data.has_value());
return dynamic_cast<Tcp::ConnectionPool::MockInstance*>(data.value().pool_);
}
};
namespace {
using ::envoy::config::bootstrap::v3::Bootstrap;
using ::testing::_;
using ::testing::DoAll;
using ::testing::InSequence;
using ::testing::Invoke;
using ::testing::InvokeWithoutArgs;
using ::testing::Mock;
using ::testing::NiceMock;
using ::testing::Return;
using ::testing::ReturnNew;
using ::testing::ReturnRef;
using ::testing::SaveArg;
using namespace std::chrono_literals;
Bootstrap parseBootstrapFromV3Yaml(const std::string& yaml) {
Bootstrap bootstrap;
TestUtility::loadFromYaml(yaml, bootstrap);
return bootstrap;
}
std::string clustersJson(const std::vector<std::string>& clusters) {
return fmt::sprintf("\"clusters\": [%s]", absl::StrJoin(clusters, ","));
}
void verifyCaresDnsConfigAndUnpack(
const envoy::config::core::v3::TypedExtensionConfig& typed_dns_resolver_config,
envoy::extensions::network::dns_resolver::cares::v3::CaresDnsResolverConfig& cares) {
// Verify typed DNS resolver config is c-ares.
EXPECT_EQ(typed_dns_resolver_config.name(), std::string(Network::CaresDnsResolver));
EXPECT_EQ(
typed_dns_resolver_config.typed_config().type_url(),
"type.googleapis.com/envoy.extensions.network.dns_resolver.cares.v3.CaresDnsResolverConfig");
typed_dns_resolver_config.typed_config().UnpackTo(&cares);
}
// Helper to intercept calls to postThreadLocalClusterUpdate.
class MockLocalClusterUpdate {
public:
MOCK_METHOD(void, post,
(uint32_t priority, const HostVector& hosts_added, const HostVector& hosts_removed));
};
class MockLocalHostsRemoved {
public:
MOCK_METHOD(void, post, (const HostVector&));
};
// Override postThreadLocalClusterUpdate so we can test that merged updates calls
// it with the right values at the right times.
class MockedUpdatedClusterManagerImpl : public TestClusterManagerImpl {
public:
using TestClusterManagerImpl::TestClusterManagerImpl;
MockedUpdatedClusterManagerImpl(
const envoy::config::bootstrap::v3::Bootstrap& bootstrap, ClusterManagerFactory& factory,
Server::Configuration::CommonFactoryContext& factory_context, Stats::Store& stats,
ThreadLocal::Instance& tls, Runtime::Loader& runtime, const LocalInfo::LocalInfo& local_info,
AccessLog::AccessLogManager& log_manager, Event::Dispatcher& main_thread_dispatcher,
Server::Admin& admin, ProtobufMessage::ValidationContext& validation_context, Api::Api& api,
MockLocalClusterUpdate& local_cluster_update, MockLocalHostsRemoved& local_hosts_removed,
Http::Context& http_context, Grpc::Context& grpc_context, Router::Context& router_context,
Server::Instance& server)
: TestClusterManagerImpl(bootstrap, factory, factory_context, stats, tls, runtime, local_info,
log_manager, main_thread_dispatcher, admin, validation_context, api,
http_context, grpc_context, router_context, server),
local_cluster_update_(local_cluster_update), local_hosts_removed_(local_hosts_removed) {}
protected:
void postThreadLocalClusterUpdate(ClusterManagerCluster&,
ThreadLocalClusterUpdateParams&& params) override {
for (const auto& per_priority : params.per_priority_update_params_) {
local_cluster_update_.post(per_priority.priority_, per_priority.hosts_added_,
per_priority.hosts_removed_);
}
}
void postThreadLocalRemoveHosts(const Cluster&, const HostVector& hosts_removed) override {
local_hosts_removed_.post(hosts_removed);
}
MockLocalClusterUpdate& local_cluster_update_;
MockLocalHostsRemoved& local_hosts_removed_;
};
// A gRPC MuxFactory that returns a MockGrpcMux instance when trying to instantiate a mux for the
// `envoy.config_mux.grpc_mux_factory` type. This enables testing call expectations on the ADS gRPC
// mux.
class MockGrpcMuxFactory : public Config::MuxFactory {
public:
std::string name() const override { return "envoy.config_mux.grpc_mux_factory"; }
void shutdownAll() override {}
std::shared_ptr<Config::GrpcMux>
create(std::unique_ptr<Grpc::RawAsyncClient>&&, std::unique_ptr<Grpc::RawAsyncClient>&&,
Event::Dispatcher&, Random::RandomGenerator&, Stats::Scope&,
const envoy::config::core::v3::ApiConfigSource&, const LocalInfo::LocalInfo&,
std::unique_ptr<Config::CustomConfigValidators>&&, BackOffStrategyPtr&&,
OptRef<Config::XdsConfigTracker>, OptRef<Config::XdsResourcesDelegate>, bool) override {
return std::make_shared<NiceMock<Config::MockGrpcMux>>();
}
};
// A ClusterManagerImpl that overrides postThreadLocalClusterUpdate set up call expectations on the
// ADS gRPC mux. The ADS mux should not be started until the ADS cluster has been initialized. This
// solves the problem outlined in https://github.com/envoyproxy/envoy/issues/27702.
class UpdateOverrideClusterManagerImpl : public TestClusterManagerImpl {
public:
UpdateOverrideClusterManagerImpl(const Bootstrap& bootstrap, ClusterManagerFactory& factory,
Server::Configuration::CommonFactoryContext& factory_context,
Stats::Store& stats, ThreadLocal::Instance& tls,
Runtime::Loader& runtime, const LocalInfo::LocalInfo& local_info,
AccessLog::AccessLogManager& log_manager,
Event::Dispatcher& main_thread_dispatcher, Server::Admin& admin,
ProtobufMessage::ValidationContext& validation_context,
Api::Api& api, Http::Context& http_context,
Grpc::Context& grpc_context, Router::Context& router_context,
Server::Instance& server)
: TestClusterManagerImpl(bootstrap, factory, factory_context, stats, tls, runtime, local_info,
log_manager, main_thread_dispatcher, admin, validation_context, api,
http_context, grpc_context, router_context, server) {}
protected:
void postThreadLocalClusterUpdate(ClusterManagerCluster& cluster,
ThreadLocalClusterUpdateParams&& params) override {
int expected_start_call_count = 0;
if (cluster.cluster().info()->name() == "ads_cluster") {
// For the ADS cluster, we expect that the postThreadLocalClusterUpdate call below will
// invoke the ADS mux's start() method. Subsequent calls to postThreadLocalClusterUpdate()
// should not invoke the ADS mux's start() method.
if (!post_tls_update_for_ads_cluster_called_) {
expected_start_call_count = 1;
}
post_tls_update_for_ads_cluster_called_ = true;
}
EXPECT_CALL(dynamic_cast<Config::MockGrpcMux&>(*adsMux()), start())
.Times(expected_start_call_count);
// The ClusterManagerImpl::postThreadLocalClusterUpdate method calls ads_mux_->start() if the
// cluster is used in ADS for EnvoyGrpc.
TestClusterManagerImpl::postThreadLocalClusterUpdate(cluster, std::move(params));
}
private:
bool post_tls_update_for_ads_cluster_called_ = false;
};
class ClusterManagerImplTest : public testing::Test {
public:
ClusterManagerImplTest()
: http_context_(factory_.stats_.symbolTable()), grpc_context_(factory_.stats_.symbolTable()),
router_context_(factory_.stats_.symbolTable()),
registered_dns_factory_(dns_resolver_factory_) {}
virtual void create(const Bootstrap& bootstrap) {
cluster_manager_ = TestClusterManagerImpl::createAndInit(
bootstrap, factory_, factory_.server_context_, factory_.stats_, factory_.tls_,
factory_.runtime_, factory_.local_info_, log_manager_, factory_.dispatcher_, admin_,
validation_context_, *factory_.api_, http_context_, grpc_context_, router_context_,
server_);
cluster_manager_->setPrimaryClustersInitializedCb([this, bootstrap]() {
THROW_IF_NOT_OK(cluster_manager_->initializeSecondaryClusters(bootstrap));
});
}
void createWithBasicStaticCluster() {
const std::string yaml = R"EOF(
static_resources:
clusters:
- name: cluster_1
connect_timeout: 0.250s
lb_policy: ROUND_ROBIN
type: STATIC
load_assignment:
cluster_name: cluster_1
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address:
address: 127.0.0.1
port_value: 11001
)EOF";
create(parseBootstrapFromV3Yaml(yaml));
}
void createWithLocalClusterUpdate(const bool enable_merge_window = true) {
std::string yaml = R"EOF(
static_resources:
clusters:
- name: cluster_1
connect_timeout: 0.250s
type: STATIC
lb_policy: ROUND_ROBIN
load_assignment:
cluster_name: cluster_1
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address:
address: 127.0.0.1
port_value: 11001
- endpoint:
address:
socket_address:
address: 127.0.0.1
port_value: 11002
)EOF";
const std::string merge_window_enabled = R"EOF(
common_lb_config:
update_merge_window: 3s
)EOF";
const std::string merge_window_disabled = R"EOF(
common_lb_config:
update_merge_window: 0s
)EOF";
yaml += enable_merge_window ? merge_window_enabled : merge_window_disabled;
const auto& bootstrap = parseBootstrapFromV3Yaml(yaml);
cluster_manager_ = std::make_unique<MockedUpdatedClusterManagerImpl>(
bootstrap, factory_, factory_.server_context_, factory_.stats_, factory_.tls_,
factory_.runtime_, factory_.local_info_, log_manager_, factory_.dispatcher_, admin_,
validation_context_, *factory_.api_, local_cluster_update_, local_hosts_removed_,
http_context_, grpc_context_, router_context_, server_);
THROW_IF_NOT_OK(cluster_manager_->initialize(bootstrap));
}
void createWithUpdateOverrideClusterManager(const Bootstrap& bootstrap) {
cluster_manager_ = std::make_unique<UpdateOverrideClusterManagerImpl>(
bootstrap, factory_, factory_.server_context_, factory_.stats_, factory_.tls_,
factory_.runtime_, factory_.local_info_, log_manager_, factory_.dispatcher_, admin_,
validation_context_, *factory_.api_, http_context_, grpc_context_, router_context_,
server_);
THROW_IF_NOT_OK(cluster_manager_->initialize(bootstrap));
}
void checkStats(uint64_t added, uint64_t modified, uint64_t removed, uint64_t active,
uint64_t warming) {
EXPECT_EQ(added, factory_.stats_.counter("cluster_manager.cluster_added").value());
EXPECT_EQ(modified, factory_.stats_.counter("cluster_manager.cluster_modified").value());
EXPECT_EQ(removed, factory_.stats_.counter("cluster_manager.cluster_removed").value());
EXPECT_EQ(active,
factory_.stats_
.gauge("cluster_manager.active_clusters", Stats::Gauge::ImportMode::NeverImport)
.value());
EXPECT_EQ(warming,
factory_.stats_
.gauge("cluster_manager.warming_clusters", Stats::Gauge::ImportMode::NeverImport)
.value());
}
void checkConfigDump(
const std::string& expected_dump_yaml,
const Matchers::StringMatcher& name_matcher = Matchers::UniversalStringMatcher()) {
auto message_ptr = admin_.config_tracker_.config_tracker_callbacks_["clusters"](name_matcher);
const auto& clusters_config_dump =
dynamic_cast<const envoy::admin::v3::ClustersConfigDump&>(*message_ptr);
envoy::admin::v3::ClustersConfigDump expected_clusters_config_dump;
TestUtility::loadFromYaml(expected_dump_yaml, expected_clusters_config_dump);
EXPECT_EQ(expected_clusters_config_dump.DebugString(), clusters_config_dump.DebugString());
}
MetadataConstSharedPtr buildMetadata(const std::string& version) const {
envoy::config::core::v3::Metadata metadata;
if (!version.empty()) {
Envoy::Config::Metadata::mutableMetadataValue(
metadata, Config::MetadataFilters::get().ENVOY_LB, "version")
.set_string_value(version);
}
return std::make_shared<const envoy::config::core::v3::Metadata>(metadata);
}
Event::SimulatedTimeSystem time_system_;
NiceMock<TestClusterManagerFactory> factory_;
NiceMock<ProtobufMessage::MockValidationContext> validation_context_;
std::unique_ptr<TestClusterManagerImpl> cluster_manager_;
AccessLog::MockAccessLogManager log_manager_;
NiceMock<Server::MockAdmin> admin_;
MockLocalClusterUpdate local_cluster_update_;
MockLocalHostsRemoved local_hosts_removed_;
Http::ContextImpl http_context_;
Grpc::ContextImpl grpc_context_;
Router::ContextImpl router_context_;
NiceMock<Server::MockInstance> server_;
NiceMock<Network::MockDnsResolverFactory> dns_resolver_factory_;
Registry::InjectFactory<Network::DnsResolverFactory> registered_dns_factory_;
};
Bootstrap defaultConfig() {
const std::string yaml = R"EOF(
static_resources:
clusters: []
)EOF";
return parseBootstrapFromV3Yaml(yaml);
}
class ODCDTest : public ClusterManagerImplTest {
public:
void SetUp() override {
create(defaultConfig());
odcds_ = MockOdCdsApi::create();
odcds_handle_ = cluster_manager_->createOdCdsApiHandle(odcds_);
}
void TearDown() override {
odcds_.reset();
odcds_handle_.reset();
factory_.tls_.shutdownThread();
}
ClusterDiscoveryCallbackPtr createCallback() {
return std::make_unique<ClusterDiscoveryCallback>(
[this](ClusterDiscoveryStatus cluster_status) {
UNREFERENCED_PARAMETER(cluster_status);
++callback_call_count_;
});
}
ClusterDiscoveryCallbackPtr createCallback(ClusterDiscoveryStatus expected_cluster_status) {
return std::make_unique<ClusterDiscoveryCallback>(
[this, expected_cluster_status](ClusterDiscoveryStatus cluster_status) {
EXPECT_EQ(expected_cluster_status, cluster_status);
++callback_call_count_;
});
}
MockOdCdsApiSharedPtr odcds_;
OdCdsApiHandlePtr odcds_handle_;
std::chrono::milliseconds timeout_ = std::chrono::milliseconds(5000);
unsigned callback_call_count_ = 0u;
};
// Check that we create a valid handle for valid config source and null resource locator.
TEST_F(ODCDTest, TestAllocate) {
envoy::config::core::v3::ConfigSource config;
OptRef<xds::core::v3::ResourceLocator> locator;
ProtobufMessage::MockValidationVisitor mock_visitor;
config.mutable_api_config_source()->set_api_type(
envoy::config::core::v3::ApiConfigSource::DELTA_GRPC);
config.mutable_api_config_source()->set_transport_api_version(envoy::config::core::v3::V3);
config.mutable_api_config_source()->mutable_refresh_delay()->set_seconds(1);
config.mutable_api_config_source()->add_grpc_services()->mutable_envoy_grpc()->set_cluster_name(
"static_cluster");
auto handle = cluster_manager_->allocateOdCdsApi(config, locator, mock_visitor);
EXPECT_NE(handle, nullptr);
}
// Check that we create a valid handle for valid config source and resource locator.
TEST_F(ODCDTest, TestAllocateWithLocator) {
envoy::config::core::v3::ConfigSource config;
ProtobufMessage::MockValidationVisitor mock_visitor;
config.mutable_api_config_source()->set_api_type(
envoy::config::core::v3::ApiConfigSource::DELTA_GRPC);
config.mutable_api_config_source()->set_transport_api_version(envoy::config::core::v3::V3);
config.mutable_api_config_source()->mutable_refresh_delay()->set_seconds(1);
config.mutable_api_config_source()->add_grpc_services()->mutable_envoy_grpc()->set_cluster_name(
"static_cluster");
auto locator =
Config::XdsResourceIdentifier::decodeUrl("xdstp://foo/envoy.config.cluster.v3.Cluster/bar")
.value();
auto handle = cluster_manager_->allocateOdCdsApi(config, locator, mock_visitor);
EXPECT_NE(handle, nullptr);
}
// Check if requesting for an unknown cluster calls into ODCDS instead of invoking the callback.
TEST_F(ODCDTest, TestRequest) {
auto cb = createCallback();
EXPECT_CALL(*odcds_, updateOnDemand("cluster_foo"));
auto handle =
odcds_handle_->requestOnDemandClusterDiscovery("cluster_foo", std::move(cb), timeout_);
EXPECT_EQ(callback_call_count_, 0);
}
// Check if repeatedly requesting for an unknown cluster calls only once into ODCDS instead of
// invoking the callbacks.
TEST_F(ODCDTest, TestRequestRepeated) {
auto cb1 = createCallback();
auto cb2 = createCallback();
EXPECT_CALL(*odcds_, updateOnDemand("cluster_foo"));
auto handle1 =
odcds_handle_->requestOnDemandClusterDiscovery("cluster_foo", std::move(cb1), timeout_);
auto handle2 =
odcds_handle_->requestOnDemandClusterDiscovery("cluster_foo", std::move(cb2), timeout_);
EXPECT_EQ(callback_call_count_, 0);
}
// Check if requesting an unknown cluster calls into ODCDS, even after the successful discovery of
// the cluster and its following expiration (removal). Also make sure that the callback is called on
// the successful discovery.
TEST_F(ODCDTest, TestClusterRediscovered) {
auto cb = createCallback(ClusterDiscoveryStatus::Available);
EXPECT_CALL(*odcds_, updateOnDemand("cluster_foo")).Times(2);
auto handle =
odcds_handle_->requestOnDemandClusterDiscovery("cluster_foo", std::move(cb), timeout_);
cluster_manager_->addOrUpdateCluster(defaultStaticCluster("cluster_foo"), "version1");
EXPECT_EQ(callback_call_count_, 1);
handle.reset();
cluster_manager_->removeCluster("cluster_foo");
cb = createCallback();
handle = odcds_handle_->requestOnDemandClusterDiscovery("cluster_foo", std::move(cb), timeout_);
EXPECT_EQ(callback_call_count_, 1);
}
// Check if requesting an unknown cluster calls into ODCDS, even after the expired discovery of the
// cluster. Also make sure that the callback is called on the expired discovery.
TEST_F(ODCDTest, TestClusterRediscoveredAfterExpiration) {
auto cb = createCallback(ClusterDiscoveryStatus::Timeout);
EXPECT_CALL(*odcds_, updateOnDemand("cluster_foo")).Times(2);
auto handle =
odcds_handle_->requestOnDemandClusterDiscovery("cluster_foo", std::move(cb), timeout_);
cluster_manager_->notifyExpiredDiscovery("cluster_foo");
EXPECT_EQ(callback_call_count_, 1);
handle.reset();
cb = createCallback();
handle = odcds_handle_->requestOnDemandClusterDiscovery("cluster_foo", std::move(cb), timeout_);
EXPECT_EQ(callback_call_count_, 1);
}
// Check if requesting an unknown cluster calls into ODCDS, even after
// the discovery found out that the cluster is missing in the
// management server. Also make sure that the callback is called on
// the failed discovery.
TEST_F(ODCDTest, TestClusterRediscoveredAfterMissing) {
auto cb = createCallback(ClusterDiscoveryStatus::Missing);
EXPECT_CALL(*odcds_, updateOnDemand("cluster_foo")).Times(2);
auto handle =
odcds_handle_->requestOnDemandClusterDiscovery("cluster_foo", std::move(cb), timeout_);
cluster_manager_->notifyMissingCluster("cluster_foo");
EXPECT_EQ(callback_call_count_, 1);
handle.reset();
cb = createCallback();
handle = odcds_handle_->requestOnDemandClusterDiscovery("cluster_foo", std::move(cb), timeout_);
EXPECT_EQ(callback_call_count_, 1);
}
// Check that we do nothing if we get a notification about irrelevant
// missing cluster.
TEST_F(ODCDTest, TestIrrelevantNotifyMissingCluster) {
auto cb = createCallback(ClusterDiscoveryStatus::Timeout);
EXPECT_CALL(*odcds_, updateOnDemand("cluster_foo"));
auto handle =
odcds_handle_->requestOnDemandClusterDiscovery("cluster_foo", std::move(cb), timeout_);
cluster_manager_->notifyMissingCluster("cluster_bar");
EXPECT_EQ(callback_call_count_, 0);
}
// Check that the callback is not called when some other cluster is added.
TEST_F(ODCDTest, TestDiscoveryManagerIgnoresIrrelevantClusters) {
auto cb = std::make_unique<ClusterDiscoveryCallback>([](ClusterDiscoveryStatus) {
ADD_FAILURE() << "The callback should not be called for irrelevant clusters";
});
EXPECT_CALL(*odcds_, updateOnDemand("cluster_foo"));
auto handle =
odcds_handle_->requestOnDemandClusterDiscovery("cluster_foo", std::move(cb), timeout_);
cluster_manager_->addOrUpdateCluster(defaultStaticCluster("cluster_irrelevant"), "version1");
}
// Start a couple of discoveries and drop the discovery handles in different order, make sure no
// callbacks are invoked when discoveries are done.
TEST_F(ODCDTest, TestDroppingHandles) {
auto cb1 = std::make_unique<ClusterDiscoveryCallback>(
[](ClusterDiscoveryStatus) { ADD_FAILURE() << "The callback 1 should not be called"; });
auto cb2 = std::make_unique<ClusterDiscoveryCallback>(
[](ClusterDiscoveryStatus) { ADD_FAILURE() << "The callback 2 should not be called"; });
auto cb3 = std::make_unique<ClusterDiscoveryCallback>(
[](ClusterDiscoveryStatus) { ADD_FAILURE() << "The callback 3 should not be called"; });
auto cb4 = std::make_unique<ClusterDiscoveryCallback>(
[](ClusterDiscoveryStatus) { ADD_FAILURE() << "The callback 4 should not be called"; });
EXPECT_CALL(*odcds_, updateOnDemand("cluster_foo1"));
EXPECT_CALL(*odcds_, updateOnDemand("cluster_foo2"));
EXPECT_CALL(*odcds_, updateOnDemand("cluster_foo3"));
EXPECT_CALL(*odcds_, updateOnDemand("cluster_foo4"));
auto handle1 =
odcds_handle_->requestOnDemandClusterDiscovery("cluster_foo1", std::move(cb1), timeout_);
auto handle2 =
odcds_handle_->requestOnDemandClusterDiscovery("cluster_foo2", std::move(cb2), timeout_);
auto handle3 =
odcds_handle_->requestOnDemandClusterDiscovery("cluster_foo3", std::move(cb3), timeout_);
auto handle4 =
odcds_handle_->requestOnDemandClusterDiscovery("cluster_foo4", std::move(cb4), timeout_);
handle2.reset();
handle3.reset();
handle1.reset();
handle4.reset();
cluster_manager_->addOrUpdateCluster(defaultStaticCluster("cluster_foo1"), "version1");
cluster_manager_->addOrUpdateCluster(defaultStaticCluster("cluster_foo2"), "version1");
cluster_manager_->addOrUpdateCluster(defaultStaticCluster("cluster_foo3"), "version1");
cluster_manager_->addOrUpdateCluster(defaultStaticCluster("cluster_foo4"), "version1");
}
// Checks that dropping discovery handles will result in callbacks not being invoked.
TEST_F(ODCDTest, TestHandles) {
auto cb1 = createCallback(ClusterDiscoveryStatus::Available);
auto cb2 = std::make_unique<ClusterDiscoveryCallback>(
[](ClusterDiscoveryStatus) { ADD_FAILURE() << "The callback 2 should not be called"; });
auto cb3 = std::make_unique<ClusterDiscoveryCallback>(
[](ClusterDiscoveryStatus) { ADD_FAILURE() << "The callback 3 should not be called"; });
auto cb4 = createCallback(ClusterDiscoveryStatus::Available);
EXPECT_CALL(*odcds_, updateOnDemand("cluster_foo"));
auto handle1 =
odcds_handle_->requestOnDemandClusterDiscovery("cluster_foo", std::move(cb1), timeout_);
auto handle2 =
odcds_handle_->requestOnDemandClusterDiscovery("cluster_foo", std::move(cb2), timeout_);
auto handle3 =
odcds_handle_->requestOnDemandClusterDiscovery("cluster_foo", std::move(cb3), timeout_);
auto handle4 =
odcds_handle_->requestOnDemandClusterDiscovery("cluster_foo", std::move(cb4), timeout_);
// handle1 and handle4 are left intact, so their respective callbacks will be invoked.
handle2.reset();
handle3.reset();
cluster_manager_->addOrUpdateCluster(defaultStaticCluster("cluster_foo"), "version1");
EXPECT_EQ(callback_call_count_, 2);
}
// Check if callback is invoked when trying to discover a cluster we already know about. It should
// not call into ODCDS in such case.
TEST_F(ODCDTest, TestCallbackWithExistingCluster) {
auto cb = createCallback(ClusterDiscoveryStatus::Available);
cluster_manager_->addOrUpdateCluster(defaultStaticCluster("cluster_foo"), "version1");
EXPECT_CALL(*odcds_, updateOnDemand("cluster_foo")).Times(0);
auto handle =
odcds_handle_->requestOnDemandClusterDiscovery("cluster_foo", std::move(cb), timeout_);
EXPECT_EQ(callback_call_count_, 1);
}
// Checks that the cluster manager detects that a thread has requested a cluster that some other
// thread already did earlier, so it does not start another discovery process.
TEST_F(ODCDTest, TestMainThreadDiscoveryInProgressDetection) {
EXPECT_CALL(*odcds_, updateOnDemand("cluster_foo"));
auto cb1 = createCallback();
auto cb2 = createCallback();
auto handle1 =
odcds_handle_->requestOnDemandClusterDiscovery("cluster_foo", std::move(cb1), timeout_);
auto cdm = cluster_manager_->createAndSwapClusterDiscoveryManager("another_fake_thread");
auto handle2 =
odcds_handle_->requestOnDemandClusterDiscovery("cluster_foo", std::move(cb2), timeout_);
}
class AlpnSocketFactory : public Network::RawBufferSocketFactory {
public:
bool supportsAlpn() const override { return true; }
};
class AlpnTestConfigFactory
: public Envoy::Extensions::TransportSockets::RawBuffer::UpstreamRawBufferSocketFactory {
public:
std::string name() const override { return "envoy.transport_sockets.alpn"; }
absl::StatusOr<Network::UpstreamTransportSocketFactoryPtr>
createTransportSocketFactory(const Protobuf::Message&,
Server::Configuration::TransportSocketFactoryContext&) override {
return std::make_unique<AlpnSocketFactory>();
}
ProtobufTypes::MessagePtr createEmptyConfigProto() override {
return std::make_unique<ProtobufWkt::Struct>();
}
};
TEST_F(ClusterManagerImplTest, MultipleProtocolClusterAlpn) {
AlpnTestConfigFactory alpn_factory;
Registry::InjectFactory<Server::Configuration::UpstreamTransportSocketConfigFactory>
registered_factory(alpn_factory);
const std::string yaml = R"EOF(
static_resources:
clusters:
- name: http12_cluster
connect_timeout: 0.250s
lb_policy: ROUND_ROBIN
typed_extension_protocol_options:
envoy.extensions.upstreams.http.v3.HttpProtocolOptions:
"@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions
auto_config:
http2_protocol_options: {}
http_protocol_options: {}
transport_socket:
name: envoy.transport_sockets.alpn
typed_config:
"@type": type.googleapis.com/google.protobuf.Struct
)EOF";
create(parseBootstrapFromV3Yaml(yaml));
}
TEST_F(ClusterManagerImplTest, MultipleHealthCheckFail) {
const std::string yaml = R"EOF(
static_resources:
clusters:
- name: service_google
connect_timeout: 0.25s
health_checks:
- timeout: 1s
interval: 1s
http_health_check:
path: "/blah"
- timeout: 1s
interval: 1s
http_health_check:
path: "/"
)EOF";
EXPECT_THROW_WITH_MESSAGE(create(parseBootstrapFromV3Yaml(yaml)), EnvoyException,
"Multiple health checks not supported");
}
TEST_F(ClusterManagerImplTest, MultipleProtocolCluster) {
time_system_.setSystemTime(std::chrono::milliseconds(1234567891234));
const std::string yaml = R"EOF(
static_resources:
clusters:
- name: http12_cluster
connect_timeout: 0.250s
lb_policy: ROUND_ROBIN
http2_protocol_options: {}
http_protocol_options: {}
protocol_selection: USE_DOWNSTREAM_PROTOCOL
)EOF";
create(parseBootstrapFromV3Yaml(yaml));
auto info =
cluster_manager_->clusters().active_clusters_.find("http12_cluster")->second.get().info();
EXPECT_NE(0, info->features() & Upstream::ClusterInfo::Features::USE_DOWNSTREAM_PROTOCOL);
checkConfigDump(R"EOF(
static_clusters:
- cluster:
"@type": type.googleapis.com/envoy.config.cluster.v3.Cluster
name: http12_cluster
connect_timeout: 0.250s
lb_policy: ROUND_ROBIN
http2_protocol_options: {}
http_protocol_options: {}
protocol_selection: USE_DOWNSTREAM_PROTOCOL
last_updated:
seconds: 1234567891
nanos: 234000000
dynamic_active_clusters:
dynamic_warming_clusters:
)EOF");
Matchers::MockStringMatcher mock_matcher;
EXPECT_CALL(mock_matcher, match("http12_cluster")).WillOnce(Return(false));
checkConfigDump(R"EOF(
static_clusters:
dynamic_active_clusters:
dynamic_warming_clusters:
)EOF",
mock_matcher);
}
TEST_F(ClusterManagerImplTest, OutlierEventLog) {
const std::string json = R"EOF(
{
"cluster_manager": {
"outlier_detection": {
"event_log_path": "foo"
}
},
"static_resources": {
"clusters": []
}
}
)EOF";
EXPECT_CALL(log_manager_, createAccessLog(Filesystem::FilePathAndType{
Filesystem::DestinationType::File, "foo"}));
create(parseBootstrapFromV3Json(json));
}
TEST_F(ClusterManagerImplTest, AdsCluster) {
MockGrpcMuxFactory factory;
Registry::InjectFactory<Config::MuxFactory> registry(factory);
const std::string yaml = R"EOF(
dynamic_resources:
ads_config:
api_type: GRPC
set_node_on_first_message_only: true
grpc_services:
envoy_grpc:
cluster_name: ads_cluster
static_resources:
clusters:
- name: ads_cluster
connect_timeout: 0.250s
type: static
lb_policy: round_robin
load_assignment:
cluster_name: ads_cluster
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address:
address: 127.0.0.1
port_value: 11001
)EOF";
createWithUpdateOverrideClusterManager(parseBootstrapFromV3Yaml(yaml));
}
TEST_F(ClusterManagerImplTest, AdsClusterStartsMuxOnlyOnce) {
MockGrpcMuxFactory factory;
Registry::InjectFactory<Config::MuxFactory> registry(factory);
const std::string yaml = R"EOF(
dynamic_resources:
ads_config:
api_type: GRPC
set_node_on_first_message_only: true
grpc_services:
envoy_grpc:
cluster_name: ads_cluster
static_resources:
clusters:
- name: ads_cluster
connect_timeout: 0.250s
type: static
lb_policy: round_robin
load_assignment:
cluster_name: ads_cluster
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address:
address: 127.0.0.1
port_value: 11001
)EOF";
createWithUpdateOverrideClusterManager(parseBootstrapFromV3Yaml(yaml));
const std::string update_static_ads_cluster_yaml = R"EOF(
name: ads_cluster
connect_timeout: 0.250s
type: static
lb_policy: round_robin
load_assignment:
cluster_name: ads_cluster
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address:
address: 127.0.0.1
port_value: 12001
)EOF";
// The static ads_cluster should not be updated by the ClusterManager (only dynamic clusters can
// be added or updated outside of the Bootstrap config).
EXPECT_FALSE(cluster_manager_->addOrUpdateCluster(
parseClusterFromV3Yaml(update_static_ads_cluster_yaml), "version2"));
EXPECT_EQ(0, factory_.stats_.counter("cluster_manager.cluster_updated").value());
EXPECT_EQ(1, factory_.stats_
.gauge("cluster_manager.active_clusters", Stats::Gauge::ImportMode::NeverImport)
.value());
EXPECT_EQ(0, factory_.stats_.counter("cluster_manager.cluster_modified").value());
const std::string new_cluster_yaml = R"EOF(
name: new_cluster
connect_timeout: 0.250s
type: static
lb_policy: round_robin
load_assignment:
cluster_name: new_cluster
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address:
address: 127.0.0.1
port_value: 12001
)EOF";
EXPECT_TRUE(
cluster_manager_->addOrUpdateCluster(parseClusterFromV3Yaml(new_cluster_yaml), "version1"));
EXPECT_EQ(0, factory_.stats_.counter("cluster_manager.cluster_updated").value());
EXPECT_EQ(2, factory_.stats_
.gauge("cluster_manager.active_clusters", Stats::Gauge::ImportMode::NeverImport)
.value());
EXPECT_EQ(0, factory_.stats_.counter("cluster_manager.cluster_modified").value());
}
TEST_F(ClusterManagerImplTest, NoSdsConfig) {
const std::string yaml = R"EOF(
static_resources:
clusters:
- name: cluster_1
connect_timeout: 0.250s
type: eds
lb_policy: round_robin
)EOF";
EXPECT_THROW_WITH_MESSAGE(create(parseBootstrapFromV3Yaml(yaml)), EnvoyException,
"cannot create an EDS cluster without an EDS config");
}
TEST_F(ClusterManagerImplTest, UnknownClusterType) {
const std::string json = R"EOF(
{
"static_resources": {
"clusters": [
{
"name": "cluster_1",
"connect_timeout": "0.250s",
"type": "foo",
"lb_policy": "round_robin"
}]
}
}
)EOF";
EXPECT_THROW_WITH_REGEX(create(parseBootstrapFromV3Json(json)), EnvoyException, "foo");
}
TEST_F(ClusterManagerImplTest, LocalClusterNotDefined) {
const std::string json = fmt::sprintf(
R"EOF(
{
"cluster_manager": {
"local_cluster_name": "new_cluster",
},
"static_resources": {
%s
}
}
)EOF",
clustersJson({defaultStaticClusterJson("cluster_1"), defaultStaticClusterJson("cluster_2")}));
EXPECT_THROW(create(parseBootstrapFromV3Json(json)), EnvoyException);
}
TEST_F(ClusterManagerImplTest, BadClusterManagerConfig) {
const std::string json = R"EOF(
{
"cluster_manager": {
"outlier_detection": {
"event_log_path": "foo"
},
"fake_property" : "fake_property"
},
"static_resources": {
"clusters": []
}
}
)EOF";
EXPECT_THROW_WITH_REGEX(create(parseBootstrapFromV3Json(json)), EnvoyException, "fake_property");
}
TEST_F(ClusterManagerImplTest, LocalClusterDefined) {
const std::string json = fmt::sprintf(
R"EOF(
{
"cluster_manager": {
"local_cluster_name": "new_cluster",
},
"static_resources": {
%s
}
}
)EOF",
clustersJson({defaultStaticClusterJson("cluster_1"), defaultStaticClusterJson("cluster_2"),
defaultStaticClusterJson("new_cluster")}));
create(parseBootstrapFromV3Json(json));
checkStats(3 /*added*/, 0 /*modified*/, 0 /*removed*/, 3 /*active*/, 0 /*warming*/);
factory_.tls_.shutdownThread();
}
TEST_F(ClusterManagerImplTest, DuplicateCluster) {
const std::string json = fmt::sprintf(
"{\"static_resources\":{%s}}",
clustersJson({defaultStaticClusterJson("cluster_1"), defaultStaticClusterJson("cluster_1")}));
const auto config = parseBootstrapFromV3Json(json);
EXPECT_THROW(create(config), EnvoyException);
}
TEST_F(ClusterManagerImplTest, ValidClusterName) {
const std::string yaml = R"EOF(
static_resources:
clusters:
- name: cluster:name
connect_timeout: 0.250s
type: static
lb_policy: round_robin
load_assignment:
cluster_name: foo
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address:
address: 127.0.0.1
port_value: 11001
)EOF";
create(parseBootstrapFromV3Yaml(yaml));
cluster_manager_->clusters()
.active_clusters_.find("cluster:name")
->second.get()
.info()
->statsScope()
.counterFromString("foo")
.inc();
EXPECT_EQ(1UL, factory_.stats_.counter("cluster.cluster_name.foo").value());
}
// Validate that the primary clusters are derived from the bootstrap and don't
// include EDS.
TEST_F(ClusterManagerImplTest, PrimaryClusters) {
const std::string yaml = R"EOF(
static_resources:
clusters:
- name: static_cluster
connect_timeout: 0.250s
type: static
- name: logical_dns_cluster
connect_timeout: 0.250s
type: logical_dns
load_assignment:
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address:
address: foo.com
port_value: 11001
- name: strict_dns_cluster
connect_timeout: 0.250s
type: strict_dns
load_assignment:
endpoints: