-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathcluster_manager_impl.cc
2463 lines (2223 loc) · 116 KB
/
cluster_manager_impl.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "source/common/upstream/cluster_manager_impl.h"
#include <chrono>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <vector>
#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/core/v3/config_source.pb.h"
#include "envoy/config/core/v3/protocol.pb.h"
#include "envoy/event/dispatcher.h"
#include "envoy/network/dns.h"
#include "envoy/runtime/runtime.h"
#include "envoy/stats/scope.h"
#include "envoy/tcp/async_tcp_client.h"
#include "envoy/upstream/load_balancer.h"
#include "envoy/upstream/upstream.h"
#include "source/common/common/assert.h"
#include "source/common/common/enum_to_int.h"
#include "source/common/common/fmt.h"
#include "source/common/common/utility.h"
#include "source/common/config/custom_config_validators_impl.h"
#include "source/common/config/null_grpc_mux_impl.h"
#include "source/common/config/utility.h"
#include "source/common/config/xds_resource.h"
#include "source/common/grpc/async_client_manager_impl.h"
#include "source/common/http/async_client_impl.h"
#include "source/common/http/http1/conn_pool.h"
#include "source/common/http/http2/conn_pool.h"
#include "source/common/http/mixed_conn_pool.h"
#include "source/common/network/utility.h"
#include "source/common/protobuf/utility.h"
#include "source/common/router/shadow_writer_impl.h"
#include "source/common/runtime/runtime_features.h"
#include "source/common/tcp/conn_pool.h"
#include "source/common/upstream/cds_api_impl.h"
#include "source/common/upstream/cluster_factory_impl.h"
#include "source/common/upstream/load_balancer_context_base.h"
#include "source/common/upstream/priority_conn_pool_map_impl.h"
#ifdef ENVOY_ENABLE_QUIC
#include "source/common/http/conn_pool_grid.h"
#include "source/common/http/http3/conn_pool.h"
#include "source/common/quic/client_connection_factory_impl.h"
#endif
namespace Envoy {
namespace Upstream {
namespace {
void addOptionsIfNotNull(Network::Socket::OptionsSharedPtr& options,
const Network::Socket::OptionsSharedPtr& to_add) {
if (to_add != nullptr) {
Network::Socket::appendOptions(options, to_add);
}
}
// Helper function to make sure each protocol in expected_protocols is present
// in protocols (only used for an ASSERT in debug builds)
bool contains(const std::vector<Http::Protocol>& protocols,
const std::vector<Http::Protocol>& expected_protocols) {
for (auto protocol : expected_protocols) {
if (std::find(protocols.begin(), protocols.end(), protocol) == protocols.end()) {
return false;
}
}
return true;
}
absl::optional<Http::HttpServerPropertiesCache::Origin>
getOrigin(const Network::TransportSocketOptionsConstSharedPtr& options, HostConstSharedPtr host) {
std::string sni = std::string(host->transportSocketFactory().defaultServerNameIndication());
if (options && options->serverNameOverride().has_value()) {
sni = options->serverNameOverride().value();
}
if (sni.empty() || !host->address() || !host->address()->ip()) {
return absl::nullopt;
}
return {{"https", sni, host->address()->ip()->port()}};
}
bool isBlockingAdsCluster(const envoy::config::bootstrap::v3::Bootstrap& bootstrap,
absl::string_view cluster_name) {
bool blocking_ads_cluster = false;
if (bootstrap.dynamic_resources().has_ads_config()) {
const auto& ads_config_source = bootstrap.dynamic_resources().ads_config();
// We only care about EnvoyGrpc, not GoogleGrpc, because we only need to delay ADS mux
// initialization if it uses an Envoy cluster that needs to be initialized first. We don't
// depend on the same cluster initialization when opening a gRPC stream for GoogleGrpc.
blocking_ads_cluster =
(ads_config_source.grpc_services_size() > 0 &&
ads_config_source.grpc_services(0).has_envoy_grpc() &&
ads_config_source.grpc_services(0).envoy_grpc().cluster_name() == cluster_name);
if (Runtime::runtimeFeatureEnabled("envoy.restart_features.xds_failover_support")) {
// Validate the failover server if there is one.
blocking_ads_cluster |=
(ads_config_source.grpc_services_size() == 2 &&
ads_config_source.grpc_services(1).has_envoy_grpc() &&
ads_config_source.grpc_services(1).envoy_grpc().cluster_name() == cluster_name);
}
}
return blocking_ads_cluster;
}
absl::Status createClients(Grpc::AsyncClientFactoryPtr& primary_factory,
Grpc::AsyncClientFactoryPtr& failover_factory,
Grpc::RawAsyncClientPtr& primary_client,
Grpc::RawAsyncClientPtr& failover_client) {
absl::StatusOr<Grpc::RawAsyncClientPtr> success = primary_factory->createUncachedRawAsyncClient();
RETURN_IF_NOT_OK_REF(success.status());
primary_client = std::move(*success);
if (failover_factory) {
success = failover_factory->createUncachedRawAsyncClient();
RETURN_IF_NOT_OK_REF(success.status());
failover_client = std::move(*success);
}
return absl::OkStatus();
}
} // namespace
void ClusterManagerInitHelper::addCluster(ClusterManagerCluster& cm_cluster) {
// See comments in ClusterManagerImpl::addOrUpdateCluster() for why this is only called during
// server initialization.
ASSERT(state_ != State::AllClustersInitialized);
const auto initialize_cb = [&cm_cluster, this] {
RETURN_IF_NOT_OK(onClusterInit(cm_cluster));
cm_cluster.cluster().info()->configUpdateStats().warming_state_.set(0);
return absl::OkStatus();
};
Cluster& cluster = cm_cluster.cluster();
cluster.info()->configUpdateStats().warming_state_.set(1);
if (cluster.initializePhase() == Cluster::InitializePhase::Primary) {
// Remove the previous cluster before the cluster object is destroyed.
primary_init_clusters_.insert_or_assign(cm_cluster.cluster().info()->name(), &cm_cluster);
cluster.initialize(initialize_cb);
} else {
ASSERT(cluster.initializePhase() == Cluster::InitializePhase::Secondary);
// Remove the previous cluster before the cluster object is destroyed.
secondary_init_clusters_.insert_or_assign(cm_cluster.cluster().info()->name(), &cm_cluster);
if (started_secondary_initialize_) {
// This can happen if we get a second CDS update that adds new clusters after we have
// already started secondary init. In this case, just immediately initialize.
cluster.initialize(initialize_cb);
}
}
ENVOY_LOG(debug, "cm init: adding: cluster={} primary={} secondary={}", cluster.info()->name(),
primary_init_clusters_.size(), secondary_init_clusters_.size());
}
absl::Status ClusterManagerInitHelper::onClusterInit(ClusterManagerCluster& cluster) {
ASSERT(state_ != State::AllClustersInitialized);
RETURN_IF_NOT_OK(per_cluster_init_callback_(cluster));
removeCluster(cluster);
return absl::OkStatus();
}
void ClusterManagerInitHelper::removeCluster(ClusterManagerCluster& cluster) {
if (state_ == State::AllClustersInitialized) {
return;
}
// There is a remote edge case where we can remove a cluster via CDS that has not yet been
// initialized. When called via the remove cluster API this code catches that case.
absl::flat_hash_map<std::string, ClusterManagerCluster*>* cluster_map;
if (cluster.cluster().initializePhase() == Cluster::InitializePhase::Primary) {
cluster_map = &primary_init_clusters_;
} else {
ASSERT(cluster.cluster().initializePhase() == Cluster::InitializePhase::Secondary);
cluster_map = &secondary_init_clusters_;
}
// It is possible that the cluster we are removing has already been initialized, and is not
// present in the initializer map. If so, this is fine as a CDS update may happen for a
// cluster with the same name. See the case "UpdateAlreadyInitialized" of the
// target //test/common/upstream:cluster_manager_impl_test.
auto iter = cluster_map->find(cluster.cluster().info()->name());
if (iter != cluster_map->end() && iter->second == &cluster) {
cluster_map->erase(iter);
}
ENVOY_LOG(debug, "cm init: init complete: cluster={} primary={} secondary={}",
cluster.cluster().info()->name(), primary_init_clusters_.size(),
secondary_init_clusters_.size());
maybeFinishInitialize();
}
void ClusterManagerInitHelper::initializeSecondaryClusters() {
started_secondary_initialize_ = true;
// Cluster::initialize() method can modify the map of secondary_init_clusters_ to remove
// the item currently being initialized, so we eschew range-based-for and do this complicated
// dance to increment the iterator before calling initialize.
for (auto iter = secondary_init_clusters_.begin(); iter != secondary_init_clusters_.end();) {
ClusterManagerCluster* cluster = iter->second;
ENVOY_LOG(debug, "initializing secondary cluster {}", iter->first);
++iter;
cluster->cluster().initialize([cluster, this] { return onClusterInit(*cluster); });
}
}
void ClusterManagerInitHelper::maybeFinishInitialize() {
// Do not do anything if we are still doing the initial static load or if we are waiting for
// CDS initialize.
ENVOY_LOG(debug, "maybe finish initialize state: {}", enumToInt(state_));
if (state_ == State::Loading || state_ == State::WaitingToStartCdsInitialization) {
return;
}
ASSERT(state_ == State::WaitingToStartSecondaryInitialization ||
state_ == State::CdsInitialized ||
state_ == State::WaitingForPrimaryInitializationToComplete);
ENVOY_LOG(debug, "maybe finish initialize primary init clusters empty: {}",
primary_init_clusters_.empty());
// If we are still waiting for primary clusters to initialize, do nothing.
if (!primary_init_clusters_.empty()) {
return;
} else if (state_ == State::WaitingForPrimaryInitializationToComplete) {
state_ = State::WaitingToStartSecondaryInitialization;
if (primary_clusters_initialized_callback_) {
primary_clusters_initialized_callback_();
}
return;
}
// If we are still waiting for secondary clusters to initialize, see if we need to first call
// initialize on them. This is only done once.
ENVOY_LOG(debug, "maybe finish initialize secondary init clusters empty: {}",
secondary_init_clusters_.empty());
if (!secondary_init_clusters_.empty()) {
if (!started_secondary_initialize_) {
ENVOY_LOG(info, "cm init: initializing secondary clusters");
// If the first CDS response doesn't have any primary cluster, ClusterLoadAssignment
// should be already paused by CdsApiImpl::onConfigUpdate(). Need to check that to
// avoid double pause ClusterLoadAssignment.
Config::ScopedResume maybe_resume_eds_leds_sds;
if (cm_.adsMux()) {
const std::vector<std::string> paused_xds_types{
Config::getTypeUrl<envoy::config::endpoint::v3::ClusterLoadAssignment>(),
Config::getTypeUrl<envoy::config::endpoint::v3::LbEndpoint>(),
Config::getTypeUrl<envoy::extensions::transport_sockets::tls::v3::Secret>()};
maybe_resume_eds_leds_sds = cm_.adsMux()->pause(paused_xds_types);
}
initializeSecondaryClusters();
}
return;
}
// At this point, if we are doing static init, and we have CDS, start CDS init. Otherwise, move
// directly to initialized.
started_secondary_initialize_ = false;
ENVOY_LOG(debug, "maybe finish initialize cds api ready: {}", cds_ != nullptr);
if (state_ == State::WaitingToStartSecondaryInitialization && cds_) {
ENVOY_LOG(info, "cm init: initializing cds");
state_ = State::WaitingToStartCdsInitialization;
cds_->initialize();
} else {
ENVOY_LOG(info, "cm init: all clusters initialized");
state_ = State::AllClustersInitialized;
if (initialized_callback_) {
initialized_callback_();
}
}
}
void ClusterManagerInitHelper::onStaticLoadComplete() {
ASSERT(state_ == State::Loading);
// After initialization of primary clusters has completed, transition to
// waiting for signal to initialize secondary clusters and then CDS.
state_ = State::WaitingForPrimaryInitializationToComplete;
maybeFinishInitialize();
}
void ClusterManagerInitHelper::startInitializingSecondaryClusters() {
ASSERT(state_ == State::WaitingToStartSecondaryInitialization);
ENVOY_LOG(debug, "continue initializing secondary clusters");
maybeFinishInitialize();
}
void ClusterManagerInitHelper::setCds(CdsApi* cds) {
ASSERT(state_ == State::Loading);
cds_ = cds;
if (cds_) {
cds_->setInitializedCb([this]() -> void {
ASSERT(state_ == State::WaitingToStartCdsInitialization);
state_ = State::CdsInitialized;
maybeFinishInitialize();
});
}
}
void ClusterManagerInitHelper::setInitializedCb(
ClusterManager::InitializationCompleteCallback callback) {
if (state_ == State::AllClustersInitialized) {
callback();
} else {
initialized_callback_ = callback;
}
}
void ClusterManagerInitHelper::setPrimaryClustersInitializedCb(
ClusterManager::PrimaryClustersReadyCallback callback) {
// The callback must be set before or at the `WaitingToStartSecondaryInitialization` state.
ASSERT(state_ == State::WaitingToStartSecondaryInitialization ||
state_ == State::WaitingForPrimaryInitializationToComplete || state_ == State::Loading);
if (state_ == State::WaitingToStartSecondaryInitialization) {
// This is the case where all clusters are STATIC and without health checking.
callback();
} else {
primary_clusters_initialized_callback_ = callback;
}
}
ClusterManagerImpl::ClusterManagerImpl(
const envoy::config::bootstrap::v3::Bootstrap& bootstrap, ClusterManagerFactory& factory,
Server::Configuration::CommonFactoryContext& context, Stats::Store& stats,
ThreadLocal::Instance& tls, Runtime::Loader& runtime, const LocalInfo::LocalInfo& local_info,
AccessLog::AccessLogManager& log_manager, Event::Dispatcher& main_thread_dispatcher,
OptRef<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, Config::XdsManager& xds_manager,
absl::Status& creation_status)
: server_(server), factory_(factory), runtime_(runtime), stats_(stats), tls_(tls),
xds_manager_(xds_manager), random_(api.randomGenerator()),
deferred_cluster_creation_(bootstrap.cluster_manager().enable_deferred_cluster_creation()),
bind_config_(bootstrap.cluster_manager().has_upstream_bind_config()
? absl::make_optional(bootstrap.cluster_manager().upstream_bind_config())
: absl::nullopt),
local_info_(local_info), cm_stats_(generateStats(*stats.rootScope())),
init_helper_(*this,
[this](ClusterManagerCluster& cluster) { return onClusterInit(cluster); }),
time_source_(main_thread_dispatcher.timeSource()), dispatcher_(main_thread_dispatcher),
http_context_(http_context), validation_context_(validation_context),
router_context_(router_context), cluster_stat_names_(stats.symbolTable()),
cluster_config_update_stat_names_(stats.symbolTable()),
cluster_lb_stat_names_(stats.symbolTable()),
cluster_endpoint_stat_names_(stats.symbolTable()),
cluster_load_report_stat_names_(stats.symbolTable()),
cluster_circuit_breakers_stat_names_(stats.symbolTable()),
cluster_request_response_size_stat_names_(stats.symbolTable()),
cluster_timeout_budget_stat_names_(stats.symbolTable()),
common_lb_config_pool_(
std::make_shared<SharedPool::ObjectSharedPool<
const envoy::config::cluster::v3::Cluster::CommonLbConfig, MessageUtil, MessageUtil>>(
main_thread_dispatcher)),
shutdown_(false) {
if (admin.has_value()) {
config_tracker_entry_ = admin->getConfigTracker().add(
"clusters", [this](const Matchers::StringMatcher& name_matcher) {
return dumpClusterConfigs(name_matcher);
});
}
async_client_manager_ = std::make_unique<Grpc::AsyncClientManagerImpl>(
*this, tls, context, grpc_context.statNames(), bootstrap.grpc_async_client_manager_config());
const auto& cm_config = bootstrap.cluster_manager();
if (cm_config.has_outlier_detection()) {
const std::string event_log_file_path = cm_config.outlier_detection().event_log_path();
if (!event_log_file_path.empty()) {
auto outlier_or_error =
Outlier::EventLoggerImpl::create(log_manager, event_log_file_path, time_source_);
SET_AND_RETURN_IF_NOT_OK(outlier_or_error.status(), creation_status);
outlier_event_logger_ = std::move(*outlier_or_error);
}
}
// We need to know whether we're zone aware early on, so make sure we do this lookup
// before we load any clusters.
if (!cm_config.local_cluster_name().empty()) {
local_cluster_name_ = cm_config.local_cluster_name();
}
// Now that the async-client manager is set, the xDS-Manager can be initialized.
absl::Status status = xds_manager_.initialize(bootstrap, this);
SET_AND_RETURN_IF_NOT_OK(status, creation_status);
// TODO(adisuissa): refactor and move the following data members to the
// xDS-manager class.
subscription_factory_ = std::make_unique<Config::SubscriptionFactoryImpl>(
local_info, main_thread_dispatcher, *this, validation_context.dynamicValidationVisitor(), api,
server, xds_manager_.xdsResourcesDelegate(), xds_manager_.xdsConfigTracker());
}
absl::Status
ClusterManagerImpl::initialize(const envoy::config::bootstrap::v3::Bootstrap& bootstrap) {
ASSERT(!initialized_);
initialized_ = true;
// Cluster loading happens in two phases: first all the primary clusters are loaded, and then all
// the secondary clusters are loaded. As it currently stands all non-EDS clusters and EDS which
// load endpoint definition from file are primary and
// (REST,GRPC,DELTA_GRPC) EDS clusters are secondary. This two phase
// loading is done because in v2 configuration each EDS cluster individually sets up a
// subscription. When this subscription is an API source the cluster will depend on a non-EDS
// cluster, so the non-EDS clusters must be loaded first.
auto is_primary_cluster = [](const envoy::config::cluster::v3::Cluster& cluster) -> bool {
return cluster.type() != envoy::config::cluster::v3::Cluster::EDS ||
(cluster.type() == envoy::config::cluster::v3::Cluster::EDS &&
Config::SubscriptionFactory::isPathBasedConfigSource(
cluster.eds_cluster_config().eds_config().config_source_specifier_case()));
};
// Build book-keeping for which clusters are primary. This is useful when we
// invoke loadCluster() below and it needs the complete set of primaries.
for (const auto& cluster : bootstrap.static_resources().clusters()) {
if (is_primary_cluster(cluster)) {
primary_clusters_.insert(cluster.name());
}
}
bool has_ads_cluster = false;
// Load all the primary clusters.
for (const auto& cluster : bootstrap.static_resources().clusters()) {
if (is_primary_cluster(cluster)) {
const bool required_for_ads = isBlockingAdsCluster(bootstrap, cluster.name());
has_ads_cluster |= required_for_ads;
// TODO(abeyad): Consider passing a lambda for a "post-cluster-init" callback, which would
// include a conditional ads_mux_->start() call, if other uses cases for "post-cluster-init"
// functionality pops up.
auto status_or_cluster =
loadCluster(cluster, MessageUtil::hash(cluster), "", /*added_via_api=*/false,
required_for_ads, active_clusters_);
RETURN_IF_NOT_OK_REF(status_or_cluster.status());
}
}
const auto& dyn_resources = bootstrap.dynamic_resources();
// Now setup ADS if needed, this might rely on a primary cluster.
// This is the only point where distinction between delta ADS and state-of-the-world ADS is made.
// After here, we just have a GrpcMux interface held in ads_mux_, which hides
// whether the backing implementation is delta or SotW.
if (dyn_resources.has_ads_config()) {
Config::CustomConfigValidatorsPtr custom_config_validators =
std::make_unique<Config::CustomConfigValidatorsImpl>(
validation_context_.dynamicValidationVisitor(), server_,
dyn_resources.ads_config().config_validators());
auto strategy_or_error = Config::Utility::prepareJitteredExponentialBackOffStrategy(
dyn_resources.ads_config(), random_,
Envoy::Config::SubscriptionFactory::RetryInitialDelayMs,
Envoy::Config::SubscriptionFactory::RetryMaxDelayMs);
RETURN_IF_NOT_OK_REF(strategy_or_error.status());
JitteredExponentialBackOffStrategyPtr backoff_strategy = std::move(strategy_or_error.value());
const bool use_eds_cache =
Runtime::runtimeFeatureEnabled("envoy.restart_features.use_eds_cache_for_ads");
if (dyn_resources.ads_config().api_type() ==
envoy::config::core::v3::ApiConfigSource::DELTA_GRPC) {
absl::Status status = Config::Utility::checkTransportVersion(dyn_resources.ads_config());
RETURN_IF_NOT_OK(status);
std::string name;
if (Runtime::runtimeFeatureEnabled("envoy.reloadable_features.unified_mux")) {
name = "envoy.config_mux.delta_grpc_mux_factory";
} else {
name = "envoy.config_mux.new_grpc_mux_factory";
}
auto* factory = Config::Utility::getFactoryByName<Config::MuxFactory>(name);
if (!factory) {
return absl::InvalidArgumentError(fmt::format("{} not found", name));
}
auto factory_primary_or_error = Config::Utility::factoryForGrpcApiConfigSource(
*async_client_manager_, dyn_resources.ads_config(), *stats_.rootScope(), false, 0);
RETURN_IF_NOT_OK_REF(factory_primary_or_error.status());
Grpc::AsyncClientFactoryPtr factory_failover = nullptr;
if (Runtime::runtimeFeatureEnabled("envoy.restart_features.xds_failover_support")) {
auto factory_failover_or_error = Config::Utility::factoryForGrpcApiConfigSource(
*async_client_manager_, dyn_resources.ads_config(), *stats_.rootScope(), false, 1);
RETURN_IF_NOT_OK_REF(factory_failover_or_error.status());
factory_failover = std::move(factory_failover_or_error.value());
}
Grpc::RawAsyncClientPtr primary_client;
Grpc::RawAsyncClientPtr failover_client;
RETURN_IF_NOT_OK(createClients(factory_primary_or_error.value(), factory_failover,
primary_client, failover_client));
ads_mux_ =
factory->create(std::move(primary_client), std::move(failover_client), dispatcher_,
random_, *stats_.rootScope(), dyn_resources.ads_config(), local_info_,
std::move(custom_config_validators), std::move(backoff_strategy),
xds_manager_.xdsConfigTracker(), {}, use_eds_cache);
} else {
absl::Status status = Config::Utility::checkTransportVersion(dyn_resources.ads_config());
RETURN_IF_NOT_OK(status);
std::string name;
if (Runtime::runtimeFeatureEnabled("envoy.reloadable_features.unified_mux")) {
name = "envoy.config_mux.sotw_grpc_mux_factory";
} else {
name = "envoy.config_mux.grpc_mux_factory";
}
auto* factory = Config::Utility::getFactoryByName<Config::MuxFactory>(name);
if (!factory) {
return absl::InvalidArgumentError(fmt::format("{} not found", name));
}
auto factory_primary_or_error = Config::Utility::factoryForGrpcApiConfigSource(
*async_client_manager_, dyn_resources.ads_config(), *stats_.rootScope(), false, 0);
RETURN_IF_NOT_OK_REF(factory_primary_or_error.status());
Grpc::AsyncClientFactoryPtr factory_failover = nullptr;
if (Runtime::runtimeFeatureEnabled("envoy.restart_features.xds_failover_support")) {
auto factory_failover_or_error = Config::Utility::factoryForGrpcApiConfigSource(
*async_client_manager_, dyn_resources.ads_config(), *stats_.rootScope(), false, 1);
RETURN_IF_NOT_OK_REF(factory_failover_or_error.status());
factory_failover = std::move(factory_failover_or_error.value());
}
Grpc::RawAsyncClientPtr primary_client;
Grpc::RawAsyncClientPtr failover_client;
RETURN_IF_NOT_OK(createClients(factory_primary_or_error.value(), factory_failover,
primary_client, failover_client));
ads_mux_ = factory->create(std::move(primary_client), std::move(failover_client), dispatcher_,
random_, *stats_.rootScope(), dyn_resources.ads_config(),
local_info_, std::move(custom_config_validators),
std::move(backoff_strategy), xds_manager_.xdsConfigTracker(),
xds_manager_.xdsResourcesDelegate(), use_eds_cache);
}
} else {
ads_mux_ = std::make_unique<Config::NullGrpcMuxImpl>();
}
// After ADS is initialized, load EDS static clusters as EDS config may potentially need ADS.
for (const auto& cluster : bootstrap.static_resources().clusters()) {
// Now load all the secondary clusters.
if (cluster.type() == envoy::config::cluster::v3::Cluster::EDS &&
!Config::SubscriptionFactory::isPathBasedConfigSource(
cluster.eds_cluster_config().eds_config().config_source_specifier_case())) {
ASSERT(!isBlockingAdsCluster(bootstrap, cluster.name()));
// Passing "false" for required_for_ads because an ADS cluster cannot be
// defined using EDS (or non-primary cluster).
auto status_or_cluster =
loadCluster(cluster, MessageUtil::hash(cluster), "", /*added_via_api=*/false,
/*required_for_ads=*/false, active_clusters_);
if (!status_or_cluster.status().ok()) {
return status_or_cluster.status();
}
}
}
cm_stats_.cluster_added_.add(bootstrap.static_resources().clusters().size());
updateClusterCounts();
absl::optional<ThreadLocalClusterManagerImpl::LocalClusterParams> local_cluster_params;
if (local_cluster_name_) {
auto local_cluster = active_clusters_.find(local_cluster_name_.value());
if (local_cluster == active_clusters_.end()) {
return absl::InvalidArgumentError(
fmt::format("local cluster '{}' must be defined", local_cluster_name_.value()));
}
local_cluster_params.emplace();
local_cluster_params->info_ = local_cluster->second->cluster().info();
local_cluster_params->load_balancer_factory_ = local_cluster->second->loadBalancerFactory();
local_cluster->second->setAddedOrUpdated();
}
// Once the initial set of static bootstrap clusters are created (including the local cluster),
// we can instantiate the thread local cluster manager.
tls_.set([this, local_cluster_params](Event::Dispatcher& dispatcher) {
return std::make_shared<ThreadLocalClusterManagerImpl>(*this, dispatcher, local_cluster_params);
});
// We can now potentially create the CDS API once the backing cluster exists.
if (dyn_resources.has_cds_config() || !dyn_resources.cds_resources_locator().empty()) {
std::unique_ptr<xds::core::v3::ResourceLocator> cds_resources_locator;
if (!dyn_resources.cds_resources_locator().empty()) {
auto url_or_error =
Config::XdsResourceIdentifier::decodeUrl(dyn_resources.cds_resources_locator());
RETURN_IF_NOT_OK_REF(url_or_error.status());
cds_resources_locator =
std::make_unique<xds::core::v3::ResourceLocator>(std::move(url_or_error.value()));
}
auto cds_or_error =
factory_.createCds(dyn_resources.cds_config(), cds_resources_locator.get(), *this);
RETURN_IF_NOT_OK_REF(cds_or_error.status())
cds_api_ = std::move(*cds_or_error);
init_helper_.setCds(cds_api_.get());
} else {
init_helper_.setCds(nullptr);
}
// Proceed to add all static bootstrap clusters to the init manager. This will immediately
// initialize any primary clusters. Post-init processing further initializes any thread
// aware load balancer and sets up the per-worker host set updates.
for (auto& cluster : active_clusters_) {
init_helper_.addCluster(*cluster.second);
}
// Potentially move to secondary initialization on the static bootstrap clusters if all primary
// clusters have already initialized. (E.g., if all static).
init_helper_.onStaticLoadComplete();
if (!has_ads_cluster) {
// There is no ADS cluster, so we won't be starting the ADS mux after a cluster has finished
// initializing, so we must start ADS here.
ads_mux_->start();
}
return absl::OkStatus();
}
absl::Status
ClusterManagerImpl::replaceAdsMux(const envoy::config::core::v3::ApiConfigSource& ads_config) {
// If there was no ADS defined, reject replacement.
const auto& bootstrap = server_.bootstrap();
if (!bootstrap.has_dynamic_resources() || !bootstrap.dynamic_resources().has_ads_config()) {
return absl::InternalError(
"Cannot replace an ADS config when one wasn't previously configured in the bootstrap");
}
const auto& bootstrap_ads_config = server_.bootstrap().dynamic_resources().ads_config();
// There is no support for switching between different ADS types.
if (ads_config.api_type() != bootstrap_ads_config.api_type()) {
return absl::InternalError(fmt::format(
"Cannot replace an ADS config with a different api_type (expected: {})",
envoy::config::core::v3::ApiConfigSource::ApiType_Name(bootstrap_ads_config.api_type())));
}
// There is no support for using a different config validator. Note that if
// this is mainly because the validator could be stateful and if the delta-xDS
// protocol is used, then the new validator will not have the context of the
// previous one.
if (bootstrap_ads_config.config_validators_size() != ads_config.config_validators_size()) {
return absl::InternalError(fmt::format(
"Cannot replace config_validators in ADS config (different size) - Previous: {}, New: {}",
bootstrap_ads_config.config_validators_size(), ads_config.config_validators_size()));
} else if (bootstrap_ads_config.config_validators_size() > 0) {
const bool equal_config_validators = std::equal(
bootstrap_ads_config.config_validators().begin(),
bootstrap_ads_config.config_validators().end(), ads_config.config_validators().begin(),
[](const envoy::config::core::v3::TypedExtensionConfig& a,
const envoy::config::core::v3::TypedExtensionConfig& b) {
return Protobuf::util::MessageDifferencer::Equivalent(a, b);
});
if (!equal_config_validators) {
return absl::InternalError(fmt::format("Cannot replace config_validators in ADS config "
"(different contents)\nPrevious: {}\nNew: {}",
bootstrap_ads_config.DebugString(),
ads_config.DebugString()));
}
}
ENVOY_LOG_MISC(trace, "Replacing ADS config with:\n{}", ads_config.DebugString());
auto strategy_or_error = Config::Utility::prepareJitteredExponentialBackOffStrategy(
ads_config, random_, Envoy::Config::SubscriptionFactory::RetryInitialDelayMs,
Envoy::Config::SubscriptionFactory::RetryMaxDelayMs);
RETURN_IF_NOT_OK_REF(strategy_or_error.status());
JitteredExponentialBackOffStrategyPtr backoff_strategy = std::move(strategy_or_error.value());
absl::Status status = Config::Utility::checkTransportVersion(ads_config);
RETURN_IF_NOT_OK(status);
auto factory_primary_or_error = Config::Utility::factoryForGrpcApiConfigSource(
*async_client_manager_, ads_config, *stats_.rootScope(), false, 0);
RETURN_IF_NOT_OK_REF(factory_primary_or_error.status());
Grpc::AsyncClientFactoryPtr factory_failover = nullptr;
if (Runtime::runtimeFeatureEnabled("envoy.restart_features.xds_failover_support")) {
auto factory_failover_or_error = Config::Utility::factoryForGrpcApiConfigSource(
*async_client_manager_, ads_config, *stats_.rootScope(), false, 1);
RETURN_IF_NOT_OK_REF(factory_failover_or_error.status());
factory_failover = std::move(factory_failover_or_error.value());
}
Grpc::RawAsyncClientPtr primary_client;
Grpc::RawAsyncClientPtr failover_client;
RETURN_IF_NOT_OK(createClients(factory_primary_or_error.value(), factory_failover, primary_client,
failover_client));
// Primary client must not be null, as the primary xDS source must be a valid one.
// The failover_client may be null (no failover defined).
ASSERT(primary_client != nullptr);
// This will cause a disconnect from the current sources, and replacement of the clients.
status = ads_mux_->updateMuxSource(std::move(primary_client), std::move(failover_client),
*stats_.rootScope(), std::move(backoff_strategy), ads_config);
return status;
}
absl::Status ClusterManagerImpl::initializeSecondaryClusters(
const envoy::config::bootstrap::v3::Bootstrap& bootstrap) {
init_helper_.startInitializingSecondaryClusters();
const auto& cm_config = bootstrap.cluster_manager();
if (cm_config.has_load_stats_config()) {
const auto& load_stats_config = cm_config.load_stats_config();
absl::Status status = Config::Utility::checkTransportVersion(load_stats_config);
RETURN_IF_NOT_OK(status);
auto factory_or_error = Config::Utility::factoryForGrpcApiConfigSource(
*async_client_manager_, load_stats_config, *stats_.rootScope(), false, 0);
RETURN_IF_NOT_OK_REF(factory_or_error.status());
absl::StatusOr<Grpc::RawAsyncClientPtr> client_or_error =
factory_or_error.value()->createUncachedRawAsyncClient();
RETURN_IF_NOT_OK_REF(client_or_error.status());
load_stats_reporter_ = std::make_unique<LoadStatsReporter>(
local_info_, *this, *stats_.rootScope(), std::move(*client_or_error), dispatcher_);
}
return absl::OkStatus();
}
ClusterManagerStats ClusterManagerImpl::generateStats(Stats::Scope& scope) {
const std::string final_prefix = "cluster_manager.";
return {ALL_CLUSTER_MANAGER_STATS(POOL_COUNTER_PREFIX(scope, final_prefix),
POOL_GAUGE_PREFIX(scope, final_prefix))};
}
ThreadLocalClusterManagerStats
ClusterManagerImpl::ThreadLocalClusterManagerImpl::generateStats(Stats::Scope& scope,
const std::string& thread_name) {
const std::string final_prefix = absl::StrCat("thread_local_cluster_manager.", thread_name);
return {ALL_THREAD_LOCAL_CLUSTER_MANAGER_STATS(POOL_GAUGE_PREFIX(scope, final_prefix))};
}
absl::Status ClusterManagerImpl::onClusterInit(ClusterManagerCluster& cm_cluster) {
// This routine is called when a cluster has finished initializing. The cluster has not yet
// been setup for cross-thread updates to avoid needless updates during initialization. The order
// of operations here is important. We start by initializing the thread aware load balancer if
// needed. This must happen first so cluster updates are heard first by the load balancer.
// Also, it assures that all of clusters which this function is called should be always active.
auto& cluster = cm_cluster.cluster();
auto cluster_data = warming_clusters_.find(cluster.info()->name());
// We have a situation that clusters will be immediately active, such as static and primary
// cluster. So we must have this prevention logic here.
if (cluster_data != warming_clusters_.end()) {
clusterWarmingToActive(cluster.info()->name());
updateClusterCounts();
}
cluster_data = active_clusters_.find(cluster.info()->name());
if (cluster_data->second->thread_aware_lb_ != nullptr) {
RETURN_IF_NOT_OK(cluster_data->second->thread_aware_lb_->initialize());
}
// Now setup for cross-thread updates.
// This is used by cluster types such as EDS clusters to drain the connection pools of removed
// hosts.
cluster_data->second->member_update_cb_ = cluster.prioritySet().addMemberUpdateCb(
[&cluster, this](const HostVector&, const HostVector& hosts_removed) -> absl::Status {
if (cluster.info()->lbConfig().close_connections_on_host_set_change()) {
for (const auto& host_set : cluster.prioritySet().hostSetsPerPriority()) {
// This will drain all tcp and http connection pools.
postThreadLocalRemoveHosts(cluster, host_set->hosts());
}
} else {
// TODO(snowp): Should this be subject to merge windows?
// Whenever hosts are removed from the cluster, we make each TLS cluster drain it's
// connection pools for the removed hosts. If `close_connections_on_host_set_change` is
// enabled, this case will be covered by first `if` statement, where all
// connection pools are drained.
if (!hosts_removed.empty()) {
postThreadLocalRemoveHosts(cluster, hosts_removed);
}
}
return absl::OkStatus();
});
// This is used by cluster types such as EDS clusters to update the cluster
// without draining the cluster.
cluster_data->second->priority_update_cb_ = cluster.prioritySet().addPriorityUpdateCb(
[&cm_cluster, this](uint32_t priority, const HostVector& hosts_added,
const HostVector& hosts_removed) {
// This fires when a cluster is about to have an updated member set. We need to send this
// out to all of the thread local configurations.
// Should we save this update and merge it with other updates?
//
// Note that we can only _safely_ merge updates that have no added/removed hosts. That is,
// only those updates that signal a change in host healthcheck state, weight or metadata.
//
// We've discussed merging updates related to hosts being added/removed, but it's really
// tricky to merge those given that downstream consumers of these updates expect to see the
// full list of updates, not a condensed one. This is because they use the broadcasted
// HostSharedPtrs within internal maps to track hosts. If we fail to broadcast the entire
// list of removals, these maps will leak those HostSharedPtrs.
//
// See https://github.com/envoyproxy/envoy/pull/3941 for more context.
bool scheduled = false;
const auto merge_timeout = PROTOBUF_GET_MS_OR_DEFAULT(
cm_cluster.cluster().info()->lbConfig(), update_merge_window, 1000);
// Remember: we only merge updates with no adds/removes — just hc/weight/metadata changes.
const bool is_mergeable = hosts_added.empty() && hosts_removed.empty();
if (merge_timeout > 0) {
// If this is not mergeable, we should cancel any scheduled updates since
// we'll deliver it immediately.
scheduled = scheduleUpdate(cm_cluster, priority, is_mergeable, merge_timeout);
}
// If an update was not scheduled for later, deliver it immediately.
if (!scheduled) {
cm_stats_.cluster_updated_.inc();
postThreadLocalClusterUpdate(
cm_cluster, ThreadLocalClusterUpdateParams(priority, hosts_added, hosts_removed));
}
return absl::OkStatus();
});
// Finally, post updates cross-thread so the per-thread load balancers are ready. First we
// populate any update information that may be available after cluster init.
ThreadLocalClusterUpdateParams params;
for (auto& host_set : cluster.prioritySet().hostSetsPerPriority()) {
if (host_set->hosts().empty()) {
continue;
}
params.per_priority_update_params_.emplace_back(host_set->priority(), host_set->hosts(),
HostVector{});
}
// NOTE: In all cases *other* than the local cluster, this is when a cluster is added/updated
// The local cluster must currently be statically defined and must exist prior to other
// clusters being added/updated. We could gate the below update on hosts being available on
// the cluster or the cluster not already existing, but the special logic is not worth it.
postThreadLocalClusterUpdate(cm_cluster, std::move(params));
return absl::OkStatus();
}
bool ClusterManagerImpl::scheduleUpdate(ClusterManagerCluster& cluster, uint32_t priority,
bool mergeable, const uint64_t timeout) {
// Find pending updates for this cluster.
auto& updates_by_prio = updates_map_[cluster.cluster().info()->name()];
if (!updates_by_prio) {
updates_by_prio = std::make_unique<PendingUpdatesByPriorityMap>();
}
// Find pending updates for this priority.
auto& updates = (*updates_by_prio)[priority];
if (!updates) {
updates = std::make_unique<PendingUpdates>();
}
// Has an update_merge_window gone by since the last update? If so, don't schedule
// the update so it can be applied immediately. Ditto if this is not a mergeable update.
const auto delta = time_source_.monotonicTime() - updates->last_updated_;
const uint64_t delta_ms = std::chrono::duration_cast<std::chrono::milliseconds>(delta).count();
const bool out_of_merge_window = delta_ms > timeout;
if (out_of_merge_window || !mergeable) {
// If there was a pending update, we cancel the pending merged update.
//
// Note: it's possible that even though we are outside of a merge window (delta_ms > timeout),
// a timer is enabled. This race condition is fine, since we'll disable the timer here and
// deliver the update immediately.
// Why wasn't the update scheduled for later delivery? We keep some stats that are helpful
// to understand why merging did not happen. There's 2 things we are tracking here:
// 1) Was this update out of a merge window?
if (mergeable && out_of_merge_window) {
cm_stats_.update_out_of_merge_window_.inc();
}
// 2) Were there previous updates that we are cancelling (and delivering immediately)?
if (updates->disableTimer()) {
cm_stats_.update_merge_cancelled_.inc();
}
updates->last_updated_ = time_source_.monotonicTime();
return false;
}
// If there's no timer, create one.
if (updates->timer_ == nullptr) {
updates->timer_ = dispatcher_.createTimer([this, &cluster, priority, &updates]() -> void {
applyUpdates(cluster, priority, *updates);
});
}
// Ensure there's a timer set to deliver these updates.
if (!updates->timer_->enabled()) {
updates->enableTimer(timeout);
}
return true;
}
void ClusterManagerImpl::applyUpdates(ClusterManagerCluster& cluster, uint32_t priority,
PendingUpdates& updates) {
// Deliver pending updates.
// Remember that these merged updates are _only_ for updates related to
// HC/weight/metadata changes. That's why added/removed are empty. All
// adds/removals were already immediately broadcasted.
static const HostVector hosts_added;
static const HostVector hosts_removed;
postThreadLocalClusterUpdate(
cluster, ThreadLocalClusterUpdateParams(priority, hosts_added, hosts_removed));
cm_stats_.cluster_updated_via_merge_.inc();
updates.last_updated_ = time_source_.monotonicTime();
}
absl::StatusOr<bool>
ClusterManagerImpl::addOrUpdateCluster(const envoy::config::cluster::v3::Cluster& cluster,
const std::string& version_info,
const bool avoid_cds_removal) {
// First we need to see if this new config is new or an update to an existing dynamic cluster.
// We don't allow updates to statically configured clusters in the main configuration. We check
// both the warming clusters and the active clusters to see if we need an update or the update
// should be blocked.
const std::string& cluster_name = cluster.name();
const auto existing_active_cluster = active_clusters_.find(cluster_name);
const auto existing_warming_cluster = warming_clusters_.find(cluster_name);
const uint64_t new_hash = MessageUtil::hash(cluster);
if (existing_warming_cluster != warming_clusters_.end()) {
// If the cluster is the same as the warming cluster of the same name, block the update.
if (existing_warming_cluster->second->blockUpdate(new_hash)) {
return false;
}
// NB: https://github.com/envoyproxy/envoy/issues/14598
// Always proceed if the cluster is different from the existing warming cluster.
} else if (existing_active_cluster != active_clusters_.end() &&
existing_active_cluster->second->blockUpdate(new_hash)) {
// If there's no warming cluster of the same name, and if the cluster is the same as the active
// cluster of the same name, block the update.
return false;
}
if (existing_active_cluster != active_clusters_.end() ||
existing_warming_cluster != warming_clusters_.end()) {
if (existing_active_cluster != active_clusters_.end()) {
// The following init manager remove call is a NOP in the case we are already initialized.
// It's just kept here to avoid additional logic.
init_helper_.removeCluster(*existing_active_cluster->second);
}
cm_stats_.cluster_modified_.inc();
} else {
cm_stats_.cluster_added_.inc();
}
// There are two discrete paths here depending on when we are adding/updating a cluster.
// 1) During initial server load we use the init manager which handles complex logic related to
// primary/secondary init, static/CDS init, warming all clusters, etc.
// 2) After initial server load, we handle warming independently for each cluster in the warming
// map.
// Note: It's likely possible that all warming logic could be centralized in the init manager, but
// a decision was made to split the logic given how complex the init manager already is. In
// the future we may decide to undergo a refactor to unify the logic but the effort/risk to
// do that right now does not seem worth it given that the logic is generally pretty clean
// and easy to understand.
const bool all_clusters_initialized =
init_helper_.state() == ClusterManagerInitHelper::State::AllClustersInitialized;
// Preserve the previous cluster data to avoid early destroy. The same cluster should be added
// before destroy to avoid early initialization complete.
auto status_or_cluster =
loadCluster(cluster, new_hash, version_info, /*added_via_api=*/true,
/*required_for_ads=*/false, warming_clusters_, avoid_cds_removal);
RETURN_IF_NOT_OK_REF(status_or_cluster.status());
const ClusterDataPtr previous_cluster = std::move(status_or_cluster.value());
auto& cluster_entry = warming_clusters_.at(cluster_name);
cluster_entry->cluster_->info()->configUpdateStats().warming_state_.set(1);
if (!all_clusters_initialized) {
ENVOY_LOG(debug, "add/update cluster {} during init", cluster_name);
init_helper_.addCluster(*cluster_entry);
} else {
ENVOY_LOG(debug, "add/update cluster {} starting warming", cluster_name);
cluster_entry->cluster_->initialize([this, cluster_name] {
ENVOY_LOG(debug, "warming cluster {} complete", cluster_name);
auto state_changed_cluster_entry = warming_clusters_.find(cluster_name);
state_changed_cluster_entry->second->cluster_->info()->configUpdateStats().warming_state_.set(
0);
return onClusterInit(*state_changed_cluster_entry->second);
});
}
return true;
}
void ClusterManagerImpl::clusterWarmingToActive(const std::string& cluster_name) {
auto warming_it = warming_clusters_.find(cluster_name);
ASSERT(warming_it != warming_clusters_.end());
// If the cluster is being updated, we need to cancel any pending merged updates.
// Otherwise, applyUpdates() will fire with a dangling cluster reference.
updates_map_.erase(cluster_name);
active_clusters_[cluster_name] = std::move(warming_it->second);
warming_clusters_.erase(warming_it);
}
bool ClusterManagerImpl::removeCluster(const std::string& cluster_name, const bool remove_ignored) {
bool removed = false;
auto existing_active_cluster = active_clusters_.find(cluster_name);
if (existing_active_cluster != active_clusters_.end() &&
existing_active_cluster->second->added_via_api_ &&
(!existing_active_cluster->second->avoid_cds_removal_ || remove_ignored)) {
removed = true;
init_helper_.removeCluster(*existing_active_cluster->second);
active_clusters_.erase(existing_active_cluster);
ENVOY_LOG(debug, "removing cluster {}", cluster_name);
tls_.runOnAllThreads([cluster_name](OptRef<ThreadLocalClusterManagerImpl> cluster_manager) {
ASSERT(cluster_manager->thread_local_clusters_.contains(cluster_name) ||
cluster_manager->thread_local_deferred_clusters_.contains(cluster_name));
ENVOY_LOG(debug, "removing TLS cluster {}", cluster_name);
for (auto cb_it = cluster_manager->update_callbacks_.begin();
cb_it != cluster_manager->update_callbacks_.end();) {
// The current callback may remove itself from the list, so a handle for
// the next item is fetched before calling the callback.
auto curr_cb_it = cb_it;
++cb_it;
(*curr_cb_it)->onClusterRemoval(cluster_name);