-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
upstream_impl.cc
1609 lines (1431 loc) · 74 KB
/
upstream_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 "common/upstream/upstream_impl.h"
#include <chrono>
#include <cstdint>
#include <limits>
#include <list>
#include <memory>
#include <string>
#include <vector>
#include "envoy/config/cluster/v3/circuit_breaker.pb.h"
#include "envoy/config/cluster/v3/cluster.pb.h"
#include "envoy/config/core/v3/address.pb.h"
#include "envoy/config/core/v3/base.pb.h"
#include "envoy/config/core/v3/health_check.pb.h"
#include "envoy/config/core/v3/protocol.pb.h"
#include "envoy/config/endpoint/v3/endpoint_components.pb.h"
#include "envoy/event/dispatcher.h"
#include "envoy/event/timer.h"
#include "envoy/network/dns.h"
#include "envoy/network/transport_socket.h"
#include "envoy/secret/secret_manager.h"
#include "envoy/server/filter_config.h"
#include "envoy/server/transport_socket_config.h"
#include "envoy/ssl/context_manager.h"
#include "envoy/stats/scope.h"
#include "envoy/upstream/health_checker.h"
#include "envoy/upstream/upstream.h"
#include "common/common/enum_to_int.h"
#include "common/common/fmt.h"
#include "common/common/utility.h"
#include "common/config/utility.h"
#include "common/http/http1/codec_stats.h"
#include "common/http/http2/codec_stats.h"
#include "common/http/utility.h"
#include "common/network/address_impl.h"
#include "common/network/resolver_impl.h"
#include "common/network/socket_option_factory.h"
#include "common/network/socket_option_impl.h"
#include "common/protobuf/protobuf.h"
#include "common/protobuf/utility.h"
#include "common/router/config_utility.h"
#include "common/runtime/runtime_features.h"
#include "common/runtime/runtime_impl.h"
#include "common/upstream/eds.h"
#include "common/upstream/health_checker_impl.h"
#include "common/upstream/logical_dns_cluster.h"
#include "common/upstream/original_dst_cluster.h"
#include "server/transport_socket_config_impl.h"
#include "extensions/filters/network/common/utility.h"
#include "extensions/transport_sockets/well_known_names.h"
#include "absl/container/node_hash_set.h"
#include "absl/strings/str_cat.h"
namespace Envoy {
namespace Upstream {
namespace {
const Network::Address::InstanceConstSharedPtr
getSourceAddress(const envoy::config::cluster::v3::Cluster& cluster,
const envoy::config::core::v3::BindConfig& bind_config) {
// The source address from cluster config takes precedence.
if (cluster.upstream_bind_config().has_source_address()) {
return Network::Address::resolveProtoSocketAddress(
cluster.upstream_bind_config().source_address());
}
// If there's no source address in the cluster config, use any default from the bootstrap proto.
if (bind_config.has_source_address()) {
return Network::Address::resolveProtoSocketAddress(bind_config.source_address());
}
return nullptr;
}
// TODO(alyssawilk) move this to the new config library in a follow-up.
uint64_t
parseFeatures(const envoy::config::cluster::v3::Cluster& config,
std::shared_ptr<const ClusterInfoImpl::HttpProtocolOptionsConfigImpl> options) {
uint64_t features = 0;
if (options) {
if (options->use_http2_) {
features |= ClusterInfoImpl::Features::HTTP2;
}
if (options->use_downstream_protocol_) {
features |= ClusterInfoImpl::Features::USE_DOWNSTREAM_PROTOCOL;
}
} else {
if (config.has_http2_protocol_options()) {
features |= ClusterInfoImpl::Features::HTTP2;
}
if (config.protocol_selection() ==
envoy::config::cluster::v3::Cluster::USE_DOWNSTREAM_PROTOCOL) {
features |= ClusterInfoImpl::Features::USE_DOWNSTREAM_PROTOCOL;
}
}
if (config.close_connections_on_host_health_failure()) {
features |= ClusterInfoImpl::Features::CLOSE_CONNECTIONS_ON_HOST_HEALTH_FAILURE;
}
return features;
}
Network::TcpKeepaliveConfig
parseTcpKeepaliveConfig(const envoy::config::cluster::v3::Cluster& config) {
const envoy::config::core::v3::TcpKeepalive& options =
config.upstream_connection_options().tcp_keepalive();
return Network::TcpKeepaliveConfig{
PROTOBUF_GET_WRAPPED_OR_DEFAULT(options, keepalive_probes, absl::optional<uint32_t>()),
PROTOBUF_GET_WRAPPED_OR_DEFAULT(options, keepalive_time, absl::optional<uint32_t>()),
PROTOBUF_GET_WRAPPED_OR_DEFAULT(options, keepalive_interval, absl::optional<uint32_t>())};
}
const Network::ConnectionSocket::OptionsSharedPtr
parseClusterSocketOptions(const envoy::config::cluster::v3::Cluster& config,
const envoy::config::core::v3::BindConfig bind_config) {
Network::ConnectionSocket::OptionsSharedPtr cluster_options =
std::make_shared<Network::ConnectionSocket::Options>();
// The process-wide `signal()` handling may fail to handle SIGPIPE if overridden
// in the process (i.e., on a mobile client). Some OSes support handling it at the socket layer:
if (ENVOY_SOCKET_SO_NOSIGPIPE.hasValue()) {
Network::Socket::appendOptions(cluster_options,
Network::SocketOptionFactory::buildSocketNoSigpipeOptions());
}
// Cluster IP_FREEBIND settings, when set, will override the cluster manager wide settings.
if ((bind_config.freebind().value() && !config.upstream_bind_config().has_freebind()) ||
config.upstream_bind_config().freebind().value()) {
Network::Socket::appendOptions(cluster_options,
Network::SocketOptionFactory::buildIpFreebindOptions());
}
if (config.upstream_connection_options().has_tcp_keepalive()) {
Network::Socket::appendOptions(
cluster_options,
Network::SocketOptionFactory::buildTcpKeepaliveOptions(parseTcpKeepaliveConfig(config)));
}
// Cluster socket_options trump cluster manager wide.
if (bind_config.socket_options().size() + config.upstream_bind_config().socket_options().size() >
0) {
auto socket_options = !config.upstream_bind_config().socket_options().empty()
? config.upstream_bind_config().socket_options()
: bind_config.socket_options();
Network::Socket::appendOptions(
cluster_options, Network::SocketOptionFactory::buildLiteralOptions(socket_options));
}
if (cluster_options->empty()) {
return nullptr;
}
return cluster_options;
}
ProtocolOptionsConfigConstSharedPtr
createProtocolOptionsConfig(const std::string& name, const ProtobufWkt::Any& typed_config,
const ProtobufWkt::Struct& config,
Server::Configuration::ProtocolOptionsFactoryContext& factory_context) {
Server::Configuration::ProtocolOptionsFactory* factory =
Registry::FactoryRegistry<Server::Configuration::NamedNetworkFilterConfigFactory>::getFactory(
name);
if (factory == nullptr) {
factory =
Registry::FactoryRegistry<Server::Configuration::NamedHttpFilterConfigFactory>::getFactory(
name);
}
if (factory == nullptr) {
factory =
Registry::FactoryRegistry<Server::Configuration::ProtocolOptionsFactory>::getFactory(name);
}
if (factory == nullptr) {
throw EnvoyException(fmt::format("Didn't find a registered network or http filter or protocol "
"options implementation for name: '{}'",
name));
}
ProtobufTypes::MessagePtr proto_config = factory->createEmptyProtocolOptionsProto();
if (proto_config == nullptr) {
throw EnvoyException(fmt::format("filter {} does not support protocol options", name));
}
Envoy::Config::Utility::translateOpaqueConfig(
typed_config, config, factory_context.messageValidationVisitor(), *proto_config);
return factory->createProtocolOptionsConfig(*proto_config, factory_context);
}
absl::flat_hash_map<std::string, ProtocolOptionsConfigConstSharedPtr> parseExtensionProtocolOptions(
const envoy::config::cluster::v3::Cluster& config,
Server::Configuration::ProtocolOptionsFactoryContext& factory_context) {
if (!config.typed_extension_protocol_options().empty() &&
!config.hidden_envoy_deprecated_extension_protocol_options().empty()) {
throw EnvoyException("Only one of typed_extension_protocol_options or "
"extension_protocol_options can be specified");
}
absl::flat_hash_map<std::string, ProtocolOptionsConfigConstSharedPtr> options;
for (const auto& it : config.typed_extension_protocol_options()) {
// TODO(zuercher): canonicalization may be removed when deprecated filter names are removed
// We only handle deprecated network filter names here because no existing HTTP filter has
// protocol options.
auto& name = Extensions::NetworkFilters::Common::FilterNameUtil::canonicalFilterName(it.first);
auto object = createProtocolOptionsConfig(
name, it.second, ProtobufWkt::Struct::default_instance(), factory_context);
if (object != nullptr) {
options[name] = std::move(object);
}
}
for (const auto& it : config.hidden_envoy_deprecated_extension_protocol_options()) {
// TODO(zuercher): canonicalization may be removed when deprecated filter names are removed
// We only handle deprecated network filter names here because no existing HTTP filter has
// protocol options.
auto& name = Extensions::NetworkFilters::Common::FilterNameUtil::canonicalFilterName(it.first);
auto object = createProtocolOptionsConfig(name, ProtobufWkt::Any::default_instance(), it.second,
factory_context);
if (object != nullptr) {
options[name] = std::move(object);
}
}
return options;
}
// Updates the health flags for an existing host to match the new host.
// @param updated_host the new host to read health flag values from.
// @param existing_host the host to update.
// @param flag the health flag to update.
// @return bool whether the flag update caused the host health to change.
bool updateHealthFlag(const Host& updated_host, Host& existing_host, Host::HealthFlag flag) {
// Check if the health flag has changed.
if (existing_host.healthFlagGet(flag) != updated_host.healthFlagGet(flag)) {
// Keep track of the previous health value of the host.
const auto previous_health = existing_host.health();
if (updated_host.healthFlagGet(flag)) {
existing_host.healthFlagSet(flag);
} else {
existing_host.healthFlagClear(flag);
}
// Rebuild if changing the flag affected the host health.
return previous_health != existing_host.health();
}
return false;
}
// Converts a set of hosts into a HostVector, excluding certain hosts.
// @param hosts hosts to convert
// @param excluded_hosts hosts to exclude from the resulting vector.
HostVector filterHosts(const absl::node_hash_set<HostSharedPtr>& hosts,
const absl::node_hash_set<HostSharedPtr>& excluded_hosts) {
HostVector net_hosts;
net_hosts.reserve(hosts.size());
for (const auto& host : hosts) {
if (excluded_hosts.find(host) == excluded_hosts.end()) {
net_hosts.emplace_back(host);
}
}
return net_hosts;
}
} // namespace
HostDescriptionImpl::HostDescriptionImpl(
ClusterInfoConstSharedPtr cluster, const std::string& hostname,
Network::Address::InstanceConstSharedPtr dest_address, MetadataConstSharedPtr metadata,
const envoy::config::core::v3::Locality& locality,
const envoy::config::endpoint::v3::Endpoint::HealthCheckConfig& health_check_config,
uint32_t priority, TimeSource& time_source)
: cluster_(cluster), hostname_(hostname),
health_checks_hostname_(health_check_config.hostname()), address_(dest_address),
canary_(Config::Metadata::metadataValue(metadata.get(),
Config::MetadataFilters::get().ENVOY_LB,
Config::MetadataEnvoyLbKeys::get().CANARY)
.bool_value()),
metadata_(metadata), locality_(locality),
locality_zone_stat_name_(locality.zone(), cluster->statsScope().symbolTable()),
priority_(priority),
socket_factory_(resolveTransportSocketFactory(dest_address, metadata_.get())),
creation_time_(time_source.monotonicTime()) {
if (health_check_config.port_value() != 0 && dest_address->type() != Network::Address::Type::Ip) {
// Setting the health check port to non-0 only works for IP-type addresses. Setting the port
// for a pipe address is a misconfiguration. Throw an exception.
throw EnvoyException(
fmt::format("Invalid host configuration: non-zero port for non-IP address"));
}
health_check_address_ =
health_check_config.port_value() == 0
? dest_address
: Network::Utility::getAddressWithPort(*dest_address, health_check_config.port_value());
}
Network::TransportSocketFactory& HostDescriptionImpl::resolveTransportSocketFactory(
const Network::Address::InstanceConstSharedPtr& dest_address,
const envoy::config::core::v3::Metadata* metadata) const {
auto match = cluster_->transportSocketMatcher().resolve(metadata);
match.stats_.total_match_count_.inc();
ENVOY_LOG(debug, "transport socket match, socket {} selected for host with address {}",
match.name_, dest_address ? dest_address->asString() : "empty");
return match.factory_;
}
Host::CreateConnectionData HostImpl::createConnection(
Event::Dispatcher& dispatcher, const Network::ConnectionSocket::OptionsSharedPtr& options,
Network::TransportSocketOptionsSharedPtr transport_socket_options) const {
return {createConnection(dispatcher, *cluster_, address_, socket_factory_, options,
transport_socket_options),
shared_from_this()};
}
void HostImpl::setEdsHealthFlag(envoy::config::core::v3::HealthStatus health_status) {
switch (health_status) {
case envoy::config::core::v3::UNHEALTHY:
FALLTHRU;
case envoy::config::core::v3::DRAINING:
FALLTHRU;
case envoy::config::core::v3::TIMEOUT:
healthFlagSet(Host::HealthFlag::FAILED_EDS_HEALTH);
break;
case envoy::config::core::v3::DEGRADED:
healthFlagSet(Host::HealthFlag::DEGRADED_EDS_HEALTH);
break;
default:;
break;
// No health flags should be set.
}
}
Host::CreateConnectionData HostImpl::createHealthCheckConnection(
Event::Dispatcher& dispatcher,
Network::TransportSocketOptionsSharedPtr transport_socket_options,
const envoy::config::core::v3::Metadata* metadata) const {
Network::TransportSocketFactory& factory =
(metadata != nullptr) ? resolveTransportSocketFactory(healthCheckAddress(), metadata)
: socket_factory_;
return {createConnection(dispatcher, *cluster_, healthCheckAddress(), factory, nullptr,
transport_socket_options),
shared_from_this()};
}
Network::ClientConnectionPtr
HostImpl::createConnection(Event::Dispatcher& dispatcher, const ClusterInfo& cluster,
const Network::Address::InstanceConstSharedPtr& address,
Network::TransportSocketFactory& socket_factory,
const Network::ConnectionSocket::OptionsSharedPtr& options,
Network::TransportSocketOptionsSharedPtr transport_socket_options) {
Network::ConnectionSocket::OptionsSharedPtr connection_options;
if (cluster.clusterSocketOptions() != nullptr) {
if (options) {
connection_options = std::make_shared<Network::ConnectionSocket::Options>();
*connection_options = *options;
std::copy(cluster.clusterSocketOptions()->begin(), cluster.clusterSocketOptions()->end(),
std::back_inserter(*connection_options));
} else {
connection_options = cluster.clusterSocketOptions();
}
} else {
connection_options = options;
}
ASSERT(!address->envoyInternalAddress());
Network::ClientConnectionPtr connection = dispatcher.createClientConnection(
address, cluster.sourceAddress(),
socket_factory.createTransportSocket(std::move(transport_socket_options)),
connection_options);
connection->setBufferLimits(cluster.perConnectionBufferLimitBytes());
cluster.createNetworkFilterChain(*connection);
return connection;
}
void HostImpl::weight(uint32_t new_weight) { weight_ = std::max(1U, new_weight); }
std::vector<HostsPerLocalityConstSharedPtr> HostsPerLocalityImpl::filter(
const std::vector<std::function<bool(const Host&)>>& predicates) const {
// We keep two lists: one for being able to mutate the clone and one for returning to the caller.
// Creating them both at the start avoids iterating over the mutable values at the end to convert
// them to a const pointer.
std::vector<std::shared_ptr<HostsPerLocalityImpl>> mutable_clones;
std::vector<HostsPerLocalityConstSharedPtr> filtered_clones;
for (size_t i = 0; i < predicates.size(); ++i) {
mutable_clones.emplace_back(std::make_shared<HostsPerLocalityImpl>());
filtered_clones.emplace_back(mutable_clones.back());
mutable_clones.back()->local_ = local_;
}
for (const auto& hosts_locality : hosts_per_locality_) {
std::vector<HostVector> current_locality_hosts;
current_locality_hosts.resize(predicates.size());
// Since # of hosts >> # of predicates, we iterate over the hosts in the outer loop.
for (const auto& host : hosts_locality) {
for (size_t i = 0; i < predicates.size(); ++i) {
if (predicates[i](*host)) {
current_locality_hosts[i].emplace_back(host);
}
}
}
for (size_t i = 0; i < predicates.size(); ++i) {
mutable_clones[i]->hosts_per_locality_.push_back(std::move(current_locality_hosts[i]));
}
}
return filtered_clones;
}
void HostSetImpl::updateHosts(PrioritySet::UpdateHostsParams&& update_hosts_params,
LocalityWeightsConstSharedPtr locality_weights,
const HostVector& hosts_added, const HostVector& hosts_removed,
absl::optional<uint32_t> overprovisioning_factor) {
if (overprovisioning_factor.has_value()) {
ASSERT(overprovisioning_factor.value() > 0);
overprovisioning_factor_ = overprovisioning_factor.value();
}
hosts_ = std::move(update_hosts_params.hosts);
healthy_hosts_ = std::move(update_hosts_params.healthy_hosts);
degraded_hosts_ = std::move(update_hosts_params.degraded_hosts);
excluded_hosts_ = std::move(update_hosts_params.excluded_hosts);
hosts_per_locality_ = std::move(update_hosts_params.hosts_per_locality);
healthy_hosts_per_locality_ = std::move(update_hosts_params.healthy_hosts_per_locality);
degraded_hosts_per_locality_ = std::move(update_hosts_params.degraded_hosts_per_locality);
excluded_hosts_per_locality_ = std::move(update_hosts_params.excluded_hosts_per_locality);
locality_weights_ = std::move(locality_weights);
rebuildLocalityScheduler(healthy_locality_scheduler_, healthy_locality_entries_,
*healthy_hosts_per_locality_, healthy_hosts_->get(), hosts_per_locality_,
excluded_hosts_per_locality_, locality_weights_,
overprovisioning_factor_);
rebuildLocalityScheduler(degraded_locality_scheduler_, degraded_locality_entries_,
*degraded_hosts_per_locality_, degraded_hosts_->get(),
hosts_per_locality_, excluded_hosts_per_locality_, locality_weights_,
overprovisioning_factor_);
runUpdateCallbacks(hosts_added, hosts_removed);
}
void HostSetImpl::rebuildLocalityScheduler(
std::unique_ptr<EdfScheduler<LocalityEntry>>& locality_scheduler,
std::vector<std::shared_ptr<LocalityEntry>>& locality_entries,
const HostsPerLocality& eligible_hosts_per_locality, const HostVector& eligible_hosts,
HostsPerLocalityConstSharedPtr all_hosts_per_locality,
HostsPerLocalityConstSharedPtr excluded_hosts_per_locality,
LocalityWeightsConstSharedPtr locality_weights, uint32_t overprovisioning_factor) {
// Rebuild the locality scheduler by computing the effective weight of each
// locality in this priority. The scheduler is reset by default, and is rebuilt only if we have
// locality weights (i.e. using EDS) and there is at least one eligible host in this priority.
//
// We omit building a scheduler when there are zero eligible hosts in the priority as
// all the localities will have zero effective weight. At selection time, we'll either select
// from a different scheduler or there will be no available hosts in the priority. At that point
// we'll rely on other mechanisms such as panic mode to select a host, none of which rely on the
// scheduler.
//
// TODO(htuch): if the underlying locality index ->
// envoy::config::core::v3::Locality hasn't changed in hosts_/healthy_hosts_/degraded_hosts_, we
// could just update locality_weight_ without rebuilding. Similar to how host
// level WRR works, we would age out the existing entries via picks and lazily
// apply the new weights.
locality_scheduler = nullptr;
if (all_hosts_per_locality != nullptr && locality_weights != nullptr &&
!locality_weights->empty() && !eligible_hosts.empty()) {
locality_scheduler = std::make_unique<EdfScheduler<LocalityEntry>>();
locality_entries.clear();
for (uint32_t i = 0; i < all_hosts_per_locality->get().size(); ++i) {
const double effective_weight = effectiveLocalityWeight(
i, eligible_hosts_per_locality, *excluded_hosts_per_locality, *all_hosts_per_locality,
*locality_weights, overprovisioning_factor);
if (effective_weight > 0) {
locality_entries.emplace_back(std::make_shared<LocalityEntry>(i, effective_weight));
locality_scheduler->add(effective_weight, locality_entries.back());
}
}
// If all effective weights were zero, reset the scheduler.
if (locality_scheduler->empty()) {
locality_scheduler = nullptr;
}
}
}
absl::optional<uint32_t> HostSetImpl::chooseHealthyLocality() {
return chooseLocality(healthy_locality_scheduler_.get());
}
absl::optional<uint32_t> HostSetImpl::chooseDegradedLocality() {
return chooseLocality(degraded_locality_scheduler_.get());
}
absl::optional<uint32_t>
HostSetImpl::chooseLocality(EdfScheduler<LocalityEntry>* locality_scheduler) {
if (locality_scheduler == nullptr) {
return {};
}
const std::shared_ptr<LocalityEntry> locality = locality_scheduler->pickAndAdd(
[](const LocalityEntry& locality) { return locality.effective_weight_; });
// We don't build a schedule if there are no weighted localities, so we should always succeed.
ASSERT(locality != nullptr);
// If we picked it before, its weight must have been positive.
ASSERT(locality->effective_weight_ > 0);
return locality->index_;
}
PrioritySet::UpdateHostsParams
HostSetImpl::updateHostsParams(HostVectorConstSharedPtr hosts,
HostsPerLocalityConstSharedPtr hosts_per_locality,
HealthyHostVectorConstSharedPtr healthy_hosts,
HostsPerLocalityConstSharedPtr healthy_hosts_per_locality,
DegradedHostVectorConstSharedPtr degraded_hosts,
HostsPerLocalityConstSharedPtr degraded_hosts_per_locality,
ExcludedHostVectorConstSharedPtr excluded_hosts,
HostsPerLocalityConstSharedPtr excluded_hosts_per_locality) {
return PrioritySet::UpdateHostsParams{std::move(hosts),
std::move(healthy_hosts),
std::move(degraded_hosts),
std::move(excluded_hosts),
std::move(hosts_per_locality),
std::move(healthy_hosts_per_locality),
std::move(degraded_hosts_per_locality),
std::move(excluded_hosts_per_locality)};
}
PrioritySet::UpdateHostsParams HostSetImpl::updateHostsParams(const HostSet& host_set) {
return updateHostsParams(host_set.hostsPtr(), host_set.hostsPerLocalityPtr(),
host_set.healthyHostsPtr(), host_set.healthyHostsPerLocalityPtr(),
host_set.degradedHostsPtr(), host_set.degradedHostsPerLocalityPtr(),
host_set.excludedHostsPtr(), host_set.excludedHostsPerLocalityPtr());
}
PrioritySet::UpdateHostsParams
HostSetImpl::partitionHosts(HostVectorConstSharedPtr hosts,
HostsPerLocalityConstSharedPtr hosts_per_locality) {
auto partitioned_hosts = ClusterImplBase::partitionHostList(*hosts);
auto healthy_degraded_excluded_hosts_per_locality =
ClusterImplBase::partitionHostsPerLocality(*hosts_per_locality);
return updateHostsParams(std::move(hosts), std::move(hosts_per_locality),
std::move(std::get<0>(partitioned_hosts)),
std::move(std::get<0>(healthy_degraded_excluded_hosts_per_locality)),
std::move(std::get<1>(partitioned_hosts)),
std::move(std::get<1>(healthy_degraded_excluded_hosts_per_locality)),
std::move(std::get<2>(partitioned_hosts)),
std::move(std::get<2>(healthy_degraded_excluded_hosts_per_locality)));
}
double HostSetImpl::effectiveLocalityWeight(uint32_t index,
const HostsPerLocality& eligible_hosts_per_locality,
const HostsPerLocality& excluded_hosts_per_locality,
const HostsPerLocality& all_hosts_per_locality,
const LocalityWeights& locality_weights,
uint32_t overprovisioning_factor) {
const auto& locality_eligible_hosts = eligible_hosts_per_locality.get()[index];
const uint32_t excluded_count = excluded_hosts_per_locality.get().size() > index
? excluded_hosts_per_locality.get()[index].size()
: 0;
const auto host_count = all_hosts_per_locality.get()[index].size() - excluded_count;
if (host_count == 0) {
return 0.0;
}
const double locality_availability_ratio = 1.0 * locality_eligible_hosts.size() / host_count;
const uint32_t weight = locality_weights[index];
// Availability ranges from 0-1.0, and is the ratio of eligible hosts to total hosts, modified by
// the overprovisioning factor.
const double effective_locality_availability_ratio =
std::min(1.0, (overprovisioning_factor / 100.0) * locality_availability_ratio);
return weight * effective_locality_availability_ratio;
}
const HostSet&
PrioritySetImpl::getOrCreateHostSet(uint32_t priority,
absl::optional<uint32_t> overprovisioning_factor) {
if (host_sets_.size() < priority + 1) {
for (size_t i = host_sets_.size(); i <= priority; ++i) {
HostSetImplPtr host_set = createHostSet(i, overprovisioning_factor);
host_set->addPriorityUpdateCb([this](uint32_t priority, const HostVector& hosts_added,
const HostVector& hosts_removed) {
runReferenceUpdateCallbacks(priority, hosts_added, hosts_removed);
});
host_sets_.push_back(std::move(host_set));
}
}
return *host_sets_[priority];
}
void PrioritySetImpl::updateHosts(uint32_t priority, UpdateHostsParams&& update_hosts_params,
LocalityWeightsConstSharedPtr locality_weights,
const HostVector& hosts_added, const HostVector& hosts_removed,
absl::optional<uint32_t> overprovisioning_factor) {
// Ensure that we have a HostSet for the given priority.
getOrCreateHostSet(priority, overprovisioning_factor);
static_cast<HostSetImpl*>(host_sets_[priority].get())
->updateHosts(std::move(update_hosts_params), std::move(locality_weights), hosts_added,
hosts_removed, overprovisioning_factor);
if (!batch_update_) {
runUpdateCallbacks(hosts_added, hosts_removed);
}
}
void PrioritySetImpl::batchHostUpdate(BatchUpdateCb& callback) {
BatchUpdateScope scope(*this);
// We wrap the update call with a lambda that tracks all the hosts that have been added/removed.
callback.batchUpdate(scope);
// Now that all the updates have been complete, we can compute the diff.
HostVector net_hosts_added = filterHosts(scope.all_hosts_added_, scope.all_hosts_removed_);
HostVector net_hosts_removed = filterHosts(scope.all_hosts_removed_, scope.all_hosts_added_);
runUpdateCallbacks(net_hosts_added, net_hosts_removed);
}
void PrioritySetImpl::BatchUpdateScope::updateHosts(
uint32_t priority, PrioritySet::UpdateHostsParams&& update_hosts_params,
LocalityWeightsConstSharedPtr locality_weights, const HostVector& hosts_added,
const HostVector& hosts_removed, absl::optional<uint32_t> overprovisioning_factor) {
// We assume that each call updates a different priority.
ASSERT(priorities_.find(priority) == priorities_.end());
priorities_.insert(priority);
for (const auto& host : hosts_added) {
all_hosts_added_.insert(host);
}
for (const auto& host : hosts_removed) {
all_hosts_removed_.insert(host);
}
parent_.updateHosts(priority, std::move(update_hosts_params), locality_weights, hosts_added,
hosts_removed, overprovisioning_factor);
}
ClusterStats ClusterInfoImpl::generateStats(Stats::Scope& scope,
const ClusterStatNames& stat_names) {
return ClusterStats(stat_names, scope);
}
ClusterRequestResponseSizeStats
ClusterInfoImpl::generateRequestResponseSizeStats(Stats::Scope& scope) {
return {ALL_CLUSTER_REQUEST_RESPONSE_SIZE_STATS(POOL_HISTOGRAM(scope))};
}
ClusterLoadReportStats ClusterInfoImpl::generateLoadReportStats(Stats::Scope& scope) {
return {ALL_CLUSTER_LOAD_REPORT_STATS(POOL_COUNTER(scope))};
}
ClusterTimeoutBudgetStats ClusterInfoImpl::generateTimeoutBudgetStats(Stats::Scope& scope) {
return {ALL_CLUSTER_TIMEOUT_BUDGET_STATS(POOL_HISTOGRAM(scope))};
}
// Implements the FactoryContext interface required by network filters.
class FactoryContextImpl : public Server::Configuration::CommonFactoryContext {
public:
// Create from a TransportSocketFactoryContext using parent stats_scope and runtime
// other contexts taken from TransportSocketFactoryContext.
FactoryContextImpl(Stats::Scope& stats_scope, Envoy::Runtime::Loader& runtime,
Server::Configuration::TransportSocketFactoryContext& c)
: admin_(c.admin()), stats_scope_(stats_scope), cluster_manager_(c.clusterManager()),
local_info_(c.localInfo()), dispatcher_(c.dispatcher()), runtime_(runtime),
singleton_manager_(c.singletonManager()), tls_(c.threadLocal()), api_(c.api()) {}
Upstream::ClusterManager& clusterManager() override { return cluster_manager_; }
Event::Dispatcher& dispatcher() override { return dispatcher_; }
const LocalInfo::LocalInfo& localInfo() const override { return local_info_; }
Envoy::Runtime::Loader& runtime() override { return runtime_; }
Stats::Scope& scope() override { return stats_scope_; }
Singleton::Manager& singletonManager() override { return singleton_manager_; }
ThreadLocal::SlotAllocator& threadLocal() override { return tls_; }
Server::Admin& admin() override { return admin_; }
TimeSource& timeSource() override { return api().timeSource(); }
ProtobufMessage::ValidationContext& messageValidationContext() override {
// Not used.
NOT_IMPLEMENTED_GCOVR_EXCL_LINE;
}
Api::Api& api() override { return api_; }
private:
Server::Admin& admin_;
Stats::Scope& stats_scope_;
Upstream::ClusterManager& cluster_manager_;
const LocalInfo::LocalInfo& local_info_;
Event::Dispatcher& dispatcher_;
Envoy::Runtime::Loader& runtime_;
Singleton::Manager& singleton_manager_;
ThreadLocal::SlotAllocator& tls_;
Api::Api& api_;
};
std::shared_ptr<const ClusterInfoImpl::HttpProtocolOptionsConfigImpl>
createOptions(const envoy::config::cluster::v3::Cluster& config,
std::shared_ptr<const ClusterInfoImpl::HttpProtocolOptionsConfigImpl>&& options) {
if (options) {
return std::move(options);
}
if (config.protocol_selection() == envoy::config::cluster::v3::Cluster::USE_CONFIGURED_PROTOCOL) {
// Make sure multiple protocol configurations are not present
if (config.has_http_protocol_options() && config.has_http2_protocol_options()) {
throw EnvoyException(fmt::format("cluster: Both HTTP1 and HTTP2 options may only be "
"configured with non-default 'protocol_selection' values"));
}
}
return std::make_shared<ClusterInfoImpl::HttpProtocolOptionsConfigImpl>(
config.http_protocol_options(), config.http2_protocol_options(),
config.common_http_protocol_options(),
(config.has_upstream_http_protocol_options()
? absl::make_optional<envoy::config::core::v3::UpstreamHttpProtocolOptions>(
config.upstream_http_protocol_options())
: absl::nullopt),
config.protocol_selection() == envoy::config::cluster::v3::Cluster::USE_DOWNSTREAM_PROTOCOL,
config.has_http2_protocol_options());
}
ClusterInfoImpl::ClusterInfoImpl(
const envoy::config::cluster::v3::Cluster& config,
const envoy::config::core::v3::BindConfig& bind_config, Runtime::Loader& runtime,
TransportSocketMatcherPtr&& socket_matcher, Stats::ScopePtr&& stats_scope, bool added_via_api,
Server::Configuration::TransportSocketFactoryContext& factory_context)
: runtime_(runtime), name_(config.name()), type_(config.type()),
extension_protocol_options_(parseExtensionProtocolOptions(config, factory_context)),
http_protocol_options_(
createOptions(config, extensionProtocolOptionsTyped<HttpProtocolOptionsConfigImpl>(
"envoy.extensions.upstreams.http.v3.HttpProtocolOptions"))),
max_requests_per_connection_(
PROTOBUF_GET_WRAPPED_OR_DEFAULT(config, max_requests_per_connection, 0)),
max_response_headers_count_(PROTOBUF_GET_WRAPPED_OR_DEFAULT(
http_protocol_options_->common_http_protocol_options_, max_headers_count,
runtime_.snapshot().getInteger(Http::MaxResponseHeadersCountOverrideKey,
Http::DEFAULT_MAX_HEADERS_COUNT))),
connect_timeout_(
std::chrono::milliseconds(PROTOBUF_GET_MS_REQUIRED(config, connect_timeout))),
per_upstream_prefetch_ratio_(PROTOBUF_GET_WRAPPED_OR_DEFAULT(
config.prefetch_policy(), per_upstream_prefetch_ratio, 1.0)),
peekahead_ratio_(
PROTOBUF_GET_WRAPPED_OR_DEFAULT(config.prefetch_policy(), predictive_prefetch_ratio, 0)),
per_connection_buffer_limit_bytes_(
PROTOBUF_GET_WRAPPED_OR_DEFAULT(config, per_connection_buffer_limit_bytes, 1024 * 1024)),
socket_matcher_(std::move(socket_matcher)), stats_scope_(std::move(stats_scope)),
stats_(generateStats(*stats_scope_, factory_context.clusterManager().clusterStatNames())),
load_report_stats_store_(stats_scope_->symbolTable()),
load_report_stats_(generateLoadReportStats(load_report_stats_store_)),
optional_cluster_stats_((config.has_track_cluster_stats() || config.track_timeout_budgets())
? std::make_unique<OptionalClusterStats>(config, *stats_scope_)
: nullptr),
features_(parseFeatures(config, http_protocol_options_)),
resource_managers_(config, runtime, name_, *stats_scope_),
maintenance_mode_runtime_key_(absl::StrCat("upstream.maintenance_mode.", name_)),
source_address_(getSourceAddress(config, bind_config)),
lb_least_request_config_(config.least_request_lb_config()),
lb_ring_hash_config_(config.ring_hash_lb_config()),
lb_maglev_config_(config.maglev_lb_config()),
lb_original_dst_config_(config.original_dst_lb_config()),
upstream_config_(config.has_upstream_config()
? absl::make_optional<envoy::config::core::v3::TypedExtensionConfig>(
config.upstream_config())
: absl::nullopt),
added_via_api_(added_via_api),
lb_subset_(LoadBalancerSubsetInfoImpl(config.lb_subset_config())),
metadata_(config.metadata()), typed_metadata_(config.metadata()),
common_lb_config_(config.common_lb_config()),
cluster_socket_options_(parseClusterSocketOptions(config, bind_config)),
drain_connections_on_host_removal_(config.ignore_health_on_host_removal()),
connection_pool_per_downstream_connection_(
config.connection_pool_per_downstream_connection()),
warm_hosts_(!config.health_checks().empty() &&
common_lb_config_.ignore_new_hosts_until_first_hc()),
cluster_type_(
config.has_cluster_type()
? absl::make_optional<envoy::config::cluster::v3::Cluster::CustomClusterType>(
config.cluster_type())
: absl::nullopt),
factory_context_(
std::make_unique<FactoryContextImpl>(*stats_scope_, runtime, factory_context)) {
switch (config.lb_policy()) {
case envoy::config::cluster::v3::Cluster::ROUND_ROBIN:
lb_type_ = LoadBalancerType::RoundRobin;
break;
case envoy::config::cluster::v3::Cluster::LEAST_REQUEST:
lb_type_ = LoadBalancerType::LeastRequest;
break;
case envoy::config::cluster::v3::Cluster::RANDOM:
lb_type_ = LoadBalancerType::Random;
break;
case envoy::config::cluster::v3::Cluster::RING_HASH:
lb_type_ = LoadBalancerType::RingHash;
break;
case envoy::config::cluster::v3::Cluster::hidden_envoy_deprecated_ORIGINAL_DST_LB:
if (config.type() != envoy::config::cluster::v3::Cluster::ORIGINAL_DST) {
throw EnvoyException(
fmt::format("cluster: LB policy {} is not valid for Cluster type {}. 'ORIGINAL_DST_LB' "
"is allowed only with cluster type 'ORIGINAL_DST'",
envoy::config::cluster::v3::Cluster::LbPolicy_Name(config.lb_policy()),
envoy::config::cluster::v3::Cluster::DiscoveryType_Name(config.type())));
}
if (config.has_lb_subset_config()) {
throw EnvoyException(
fmt::format("cluster: LB policy {} cannot be combined with lb_subset_config",
envoy::config::cluster::v3::Cluster::LbPolicy_Name(config.lb_policy())));
}
lb_type_ = LoadBalancerType::ClusterProvided;
break;
case envoy::config::cluster::v3::Cluster::MAGLEV:
lb_type_ = LoadBalancerType::Maglev;
break;
case envoy::config::cluster::v3::Cluster::CLUSTER_PROVIDED:
if (config.has_lb_subset_config()) {
throw EnvoyException(
fmt::format("cluster: LB policy {} cannot be combined with lb_subset_config",
envoy::config::cluster::v3::Cluster::LbPolicy_Name(config.lb_policy())));
}
lb_type_ = LoadBalancerType::ClusterProvided;
break;
default:
NOT_REACHED_GCOVR_EXCL_LINE;
}
if (config.lb_subset_config().locality_weight_aware() &&
!config.common_lb_config().has_locality_weighted_lb_config()) {
throw EnvoyException(fmt::format(
"Locality weight aware subset LB requires that a locality_weighted_lb_config be set in {}",
name_));
}
if (http_protocol_options_->common_http_protocol_options_.has_idle_timeout()) {
idle_timeout_ = std::chrono::milliseconds(DurationUtil::durationToMilliseconds(
http_protocol_options_->common_http_protocol_options_.idle_timeout()));
if (idle_timeout_.value().count() == 0) {
idle_timeout_ = absl::nullopt;
}
} else {
idle_timeout_ = std::chrono::hours(1);
}
if (config.has_eds_cluster_config()) {
if (config.type() != envoy::config::cluster::v3::Cluster::EDS) {
throw EnvoyException("eds_cluster_config set in a non-EDS cluster");
}
eds_service_name_ = config.eds_cluster_config().service_name();
}
// TODO(htuch): Remove this temporary workaround when we have
// https://github.com/envoyproxy/protoc-gen-validate/issues/97 resolved. This just provides
// early validation of sanity of fields that we should catch at config ingestion.
DurationUtil::durationToMilliseconds(common_lb_config_.update_merge_window());
// Create upstream filter factories
auto filters = config.filters();
for (ssize_t i = 0; i < filters.size(); i++) {
const auto& proto_config = filters[i];
ENVOY_LOG(debug, " upstream filter #{}:", i);
ENVOY_LOG(debug, " name: {}", proto_config.name());
auto& factory = Config::Utility::getAndCheckFactory<
Server::Configuration::NamedUpstreamNetworkFilterConfigFactory>(proto_config);
auto message = factory.createEmptyConfigProto();
Config::Utility::translateOpaqueConfig(proto_config.typed_config(), ProtobufWkt::Struct(),
factory_context.messageValidationVisitor(), *message);
Network::FilterFactoryCb callback =
factory.createFilterFactoryFromProto(*message, *factory_context_);
filter_factories_.push_back(callback);
}
}
ProtocolOptionsConfigConstSharedPtr
ClusterInfoImpl::extensionProtocolOptions(const std::string& name) const {
auto i = extension_protocol_options_.find(name);
if (i != extension_protocol_options_.end()) {
return i->second;
}
return nullptr;
}
Network::TransportSocketFactoryPtr createTransportSocketFactory(
const envoy::config::cluster::v3::Cluster& config,
Server::Configuration::TransportSocketFactoryContext& factory_context) {
// If the cluster config doesn't have a transport socket configured, override with the default
// transport socket implementation based on the tls_context. We copy by value first then override
// if necessary.
auto transport_socket = config.transport_socket();
if (!config.has_transport_socket()) {
if (config.has_hidden_envoy_deprecated_tls_context()) {
transport_socket.set_name(Extensions::TransportSockets::TransportSocketNames::get().Tls);
transport_socket.mutable_typed_config()->PackFrom(
config.hidden_envoy_deprecated_tls_context());
} else {
transport_socket.set_name(
Extensions::TransportSockets::TransportSocketNames::get().RawBuffer);
}
}
auto& config_factory = Config::Utility::getAndCheckFactory<
Server::Configuration::UpstreamTransportSocketConfigFactory>(transport_socket);
ProtobufTypes::MessagePtr message = Config::Utility::translateToFactoryConfig(
transport_socket, factory_context.messageValidationVisitor(), config_factory);
return config_factory.createTransportSocketFactory(*message, factory_context);
}
void ClusterInfoImpl::createNetworkFilterChain(Network::Connection& connection) const {
for (const auto& factory : filter_factories_) {
factory(connection);
}
}
Http::Protocol
ClusterInfoImpl::upstreamHttpProtocol(absl::optional<Http::Protocol> downstream_protocol) const {
if (downstream_protocol.has_value() &&
features_ & Upstream::ClusterInfo::Features::USE_DOWNSTREAM_PROTOCOL) {
return downstream_protocol.value();
} else {
return (features_ & Upstream::ClusterInfo::Features::HTTP2) ? Http::Protocol::Http2
: Http::Protocol::Http11;
}
}
ClusterImplBase::ClusterImplBase(
const envoy::config::cluster::v3::Cluster& cluster, Runtime::Loader& runtime,
Server::Configuration::TransportSocketFactoryContextImpl& factory_context,
Stats::ScopePtr&& stats_scope, bool added_via_api, TimeSource& time_source)
: init_manager_(fmt::format("Cluster {}", cluster.name())),
init_watcher_("ClusterImplBase", [this]() { onInitDone(); }), runtime_(runtime),
time_source_(time_source),
local_cluster_(factory_context.clusterManager().localClusterName().value_or("") ==
cluster.name()),
const_metadata_shared_pool_(Config::Metadata::getConstMetadataSharedPool(
factory_context.singletonManager(), factory_context.dispatcher())) {
factory_context.setInitManager(init_manager_);
auto socket_factory = createTransportSocketFactory(cluster, factory_context);
auto socket_matcher = std::make_unique<TransportSocketMatcherImpl>(
cluster.transport_socket_matches(), factory_context, socket_factory, *stats_scope);
info_ = std::make_unique<ClusterInfoImpl>(cluster, factory_context.clusterManager().bindConfig(),
runtime, std::move(socket_matcher),
std::move(stats_scope), added_via_api, factory_context);
// Create the default (empty) priority set before registering callbacks to
// avoid getting an update the first time it is accessed.
priority_set_.getOrCreateHostSet(0);
priority_set_.addPriorityUpdateCb(
[this](uint32_t, const HostVector& hosts_added, const HostVector& hosts_removed) {
if (!hosts_added.empty() || !hosts_removed.empty()) {
info_->stats().membership_change_.inc();
}
uint32_t healthy_hosts = 0;
uint32_t degraded_hosts = 0;
uint32_t excluded_hosts = 0;
uint32_t hosts = 0;
for (const auto& host_set : prioritySet().hostSetsPerPriority()) {
hosts += host_set->hosts().size();
healthy_hosts += host_set->healthyHosts().size();
degraded_hosts += host_set->degradedHosts().size();
excluded_hosts += host_set->excludedHosts().size();
}
info_->stats().membership_total_.set(hosts);
info_->stats().membership_healthy_.set(healthy_hosts);
info_->stats().membership_degraded_.set(degraded_hosts);
info_->stats().membership_excluded_.set(excluded_hosts);
});
}
std::tuple<HealthyHostVectorConstSharedPtr, DegradedHostVectorConstSharedPtr,
ExcludedHostVectorConstSharedPtr>
ClusterImplBase::partitionHostList(const HostVector& hosts) {
auto healthy_list = std::make_shared<HealthyHostVector>();
auto degraded_list = std::make_shared<DegradedHostVector>();
auto excluded_list = std::make_shared<ExcludedHostVector>();
for (const auto& host : hosts) {
if (host->health() == Host::Health::Healthy) {
healthy_list->get().emplace_back(host);
}
if (host->health() == Host::Health::Degraded) {
degraded_list->get().emplace_back(host);
}
if (host->healthFlagGet(Host::HealthFlag::PENDING_ACTIVE_HC)) {
excluded_list->get().emplace_back(host);
}
}
return std::make_tuple(healthy_list, degraded_list, excluded_list);
}
std::tuple<HostsPerLocalityConstSharedPtr, HostsPerLocalityConstSharedPtr,
HostsPerLocalityConstSharedPtr>
ClusterImplBase::partitionHostsPerLocality(const HostsPerLocality& hosts) {
auto filtered_clones = hosts.filter(
{[](const Host& host) { return host.health() == Host::Health::Healthy; },
[](const Host& host) { return host.health() == Host::Health::Degraded; },
[](const Host& host) { return host.healthFlagGet(Host::HealthFlag::PENDING_ACTIVE_HC); }});
return std::make_tuple(std::move(filtered_clones[0]), std::move(filtered_clones[1]),
std::move(filtered_clones[2]));
}