Coverage Report

Created: 2023-11-12 09:30

/proc/self/cwd/envoy/upstream/upstream.h
Line
Count
Source (jump to first uncovered line)
1
#pragma once
2
3
#include <chrono>
4
#include <cstdint>
5
#include <functional>
6
#include <list>
7
#include <memory>
8
#include <string>
9
#include <vector>
10
11
#include "envoy/common/callback.h"
12
#include "envoy/common/optref.h"
13
#include "envoy/config/cluster/v3/cluster.pb.h"
14
#include "envoy/config/core/v3/base.pb.h"
15
#include "envoy/config/core/v3/protocol.pb.h"
16
#include "envoy/config/typed_metadata.h"
17
#include "envoy/http/codec.h"
18
#include "envoy/http/filter_factory.h"
19
#include "envoy/http/header_validator.h"
20
#include "envoy/network/connection.h"
21
#include "envoy/network/transport_socket.h"
22
#include "envoy/ssl/context.h"
23
#include "envoy/stats/scope.h"
24
#include "envoy/stats/stats.h"
25
#include "envoy/upstream/health_check_host_monitor.h"
26
#include "envoy/upstream/load_balancer_type.h"
27
#include "envoy/upstream/locality.h"
28
#include "envoy/upstream/outlier_detection.h"
29
#include "envoy/upstream/resource_manager.h"
30
#include "envoy/upstream/types.h"
31
32
#include "absl/strings/string_view.h"
33
#include "absl/types/optional.h"
34
#include "fmt/format.h"
35
36
namespace Envoy {
37
namespace Http {
38
class FilterChainManager;
39
}
40
41
namespace Upstream {
42
43
/**
44
 * A bundle struct for address and socket options.
45
 */
46
struct UpstreamLocalAddress {
47
public:
48
  Network::Address::InstanceConstSharedPtr address_;
49
  Network::ConnectionSocket::OptionsSharedPtr socket_options_;
50
};
51
52
/**
53
 * Interface to select upstream local address based on the endpoint address.
54
 */
55
class UpstreamLocalAddressSelector {
56
public:
57
406k
  virtual ~UpstreamLocalAddressSelector() = default;
58
59
  /**
60
   * Return UpstreamLocalAddress based on the endpoint address.
61
   * @param endpoint_address is the address used to select upstream local address.
62
   * @param socket_options applied to the selected address.
63
   * @return UpstreamLocalAddress which includes the selected upstream local address and socket
64
   * options.
65
   */
66
  UpstreamLocalAddress
67
  getUpstreamLocalAddress(const Network::Address::InstanceConstSharedPtr& endpoint_address,
68
23.7k
                          const Network::ConnectionSocket::OptionsSharedPtr& socket_options) const {
69
23.7k
    UpstreamLocalAddress local_address = getUpstreamLocalAddressImpl(endpoint_address);
70
23.7k
    Network::ConnectionSocket::OptionsSharedPtr connection_options =
71
23.7k
        std::make_shared<Network::ConnectionSocket::Options>(
72
23.7k
            socket_options ? *socket_options
73
23.7k
                           : std::vector<Network::ConnectionSocket::OptionConstSharedPtr>{});
74
23.7k
    return {local_address.address_,
75
23.7k
            local_address.socket_options_ != nullptr
76
23.7k
                ? Network::Socket::appendOptions(connection_options, local_address.socket_options_)
77
23.7k
                : connection_options};
78
23.7k
  }
79
80
private:
81
  /*
82
   * The implementation is responsible for picking the ``UpstreamLocalAddress``
83
   * based on the ``endpoint_address``. However adding the connection socket
84
   * options is the responsibility of the base class.
85
   */
86
  virtual UpstreamLocalAddress getUpstreamLocalAddressImpl(
87
      const Network::Address::InstanceConstSharedPtr& endpoint_address) const PURE;
88
};
89
90
using UpstreamLocalAddressSelectorConstSharedPtr =
91
    std::shared_ptr<const UpstreamLocalAddressSelector>;
92
93
class UpstreamLocalAddressSelectorFactory : public Config::TypedFactory {
94
public:
95
  ~UpstreamLocalAddressSelectorFactory() override = default;
96
97
  /**
98
   * @param cluster_name is set to the name of the cluster if ``bind_config`` is
99
   *   from cluster config. If the bind config from the cluster manager, the param
100
   *   is empty.
101
   */
102
  virtual UpstreamLocalAddressSelectorConstSharedPtr
103
  createLocalAddressSelector(std::vector<UpstreamLocalAddress> upstream_local_addresses,
104
                             absl::optional<std::string> cluster_name) const PURE;
105
106
220
  std::string category() const override { return "envoy.upstream.local_address_selector"; }
107
};
108
109
/**
110
 * RAII handle for tracking the host usage by the connection pools.
111
 **/
112
class HostHandle {
113
public:
114
1.32k
  virtual ~HostHandle() = default;
115
};
116
117
using HostHandlePtr = std::unique_ptr<HostHandle>;
118
119
/**
120
 * An upstream host.
121
 */
122
class Host : virtual public HostDescription {
123
public:
124
  struct CreateConnectionData {
125
    Network::ClientConnectionPtr connection_;
126
    HostDescriptionConstSharedPtr host_description_;
127
  };
128
129
  // We use an X-macro here to make it easier to verify that all the enum values are accounted for.
130
  // clang-format off
131
#define HEALTH_FLAG_ENUM_VALUES(m)                                               \
132
  /* The host is currently failing active health checks. */                      \
133
0
  m(FAILED_ACTIVE_HC, 0x1)                                                       \
134
0
  /* The host is currently considered an outlier and has been ejected. */        \
135
0
  m(FAILED_OUTLIER_CHECK, 0x02)                                                  \
136
0
  /* The host is currently marked as unhealthy by EDS. */                        \
137
0
  m(FAILED_EDS_HEALTH, 0x04)                                                     \
138
0
  /* The host is currently marked as degraded through active health checking. */ \
139
0
  m(DEGRADED_ACTIVE_HC, 0x08)                                                    \
140
0
  /* The host is currently marked as degraded by EDS. */                         \
141
0
  m(DEGRADED_EDS_HEALTH, 0x10)                                                   \
142
0
  /* The host is pending removal from discovery but is stabilized due to */      \
143
0
  /* active HC. */                                                               \
144
0
  m(PENDING_DYNAMIC_REMOVAL, 0x20)                                               \
145
0
  /* The host is pending its initial active health check. */                     \
146
0
  m(PENDING_ACTIVE_HC, 0x40)                                                     \
147
0
  /* The host should be excluded from panic, spillover, etc. calculations */     \
148
0
  /* because it was explicitly taken out of rotation via protocol signal and */  \
149
0
  /* is not meant to be routed to. */                                            \
150
0
  m(EXCLUDED_VIA_IMMEDIATE_HC_FAIL, 0x80)                                        \
151
0
  /* The host failed active HC due to timeout. */                                \
152
0
  m(ACTIVE_HC_TIMEOUT, 0x100)
153
  // clang-format on
154
155
#define DECLARE_ENUM(name, value) name = value,
156
157
  enum class HealthFlag { HEALTH_FLAG_ENUM_VALUES(DECLARE_ENUM) };
158
159
#undef DECLARE_ENUM
160
161
  /**
162
   * @return host specific counters.
163
   */
164
  virtual std::vector<std::pair<absl::string_view, Stats::PrimitiveCounterReference>>
165
  counters() const PURE;
166
167
  /**
168
   * Create a connection for this host.
169
   * @param dispatcher supplies the owning dispatcher.
170
   * @param options supplies the socket options that will be set on the new connection.
171
   * @param transport_socket_options supplies the transport options that will be set on the new
172
   * connection.
173
   * @return the connection data which includes the raw network connection as well as the *real*
174
   *         host that backs it. The reason why a 2nd host is returned is that some hosts are
175
   *         logical and wrap multiple real network destinations. In this case, a different host
176
   *         will be returned along with the connection vs. the host the method was called on.
177
   *         If it matters, callers should not assume that the returned host will be the same.
178
   */
179
  virtual CreateConnectionData createConnection(
180
      Event::Dispatcher& dispatcher, const Network::ConnectionSocket::OptionsSharedPtr& options,
181
      Network::TransportSocketOptionsConstSharedPtr transport_socket_options) const PURE;
182
183
  /**
184
   * Create a health check connection for this host.
185
   * @param dispatcher supplies the owning dispatcher.
186
   * @param transport_socket_options supplies the transport options that will be set on the new
187
   * connection.
188
   * @return the connection data.
189
   */
190
  virtual CreateConnectionData createHealthCheckConnection(
191
      Event::Dispatcher& dispatcher,
192
      Network::TransportSocketOptionsConstSharedPtr transport_socket_options,
193
      const envoy::config::core::v3::Metadata* metadata) const PURE;
194
195
  /**
196
   * @return host specific gauges.
197
   */
198
  virtual std::vector<std::pair<absl::string_view, Stats::PrimitiveGaugeReference>>
199
  gauges() const PURE;
200
201
  /**
202
   * Atomically clear a health flag for a host. Flags are specified in HealthFlags.
203
   */
204
  virtual void healthFlagClear(HealthFlag flag) PURE;
205
206
  /**
207
   * Atomically get whether a health flag is set for a host. Flags are specified in HealthFlags.
208
   */
209
  virtual bool healthFlagGet(HealthFlag flag) const PURE;
210
211
  /**
212
   * Atomically set a health flag for a host. Flags are specified in HealthFlags.
213
   */
214
  virtual void healthFlagSet(HealthFlag flag) PURE;
215
216
  /**
217
   * Atomically get multiple health flags that are set for a host. Flags are specified
218
   * as a bitset of HealthFlags.
219
   */
220
  virtual uint32_t healthFlagsGetAll() const PURE;
221
222
  /**
223
   * Atomically set the health flag for a host. Flags are specified as a bitset
224
   * of HealthFlags.
225
   */
226
  virtual void healthFlagsSetAll(uint32_t bits) PURE;
227
228
  enum class Health {
229
    /**
230
     * Host is unhealthy and is not able to serve traffic. A host may be marked as unhealthy either
231
     * through EDS or through active health checking.
232
     */
233
    Unhealthy,
234
    /**
235
     * Host is healthy, but degraded. It is able to serve traffic, but hosts that aren't degraded
236
     * should be preferred. A host may be marked as degraded either through EDS or through active
237
     * health checking.
238
     */
239
    Degraded,
240
    /**
241
     * Host is healthy and is able to serve traffic.
242
     */
243
    Healthy,
244
  };
245
246
  /**
247
   * @return the coarse health status of the host.
248
   */
249
  virtual Health coarseHealth() const PURE;
250
251
  using HealthStatus = envoy::config::core::v3::HealthStatus;
252
253
  /**
254
   * @return more specific health status of host. This status is hybrid of EDS status and runtime
255
   * active status (from active health checker or outlier detection). Active status will be taken as
256
   * a priority.
257
   */
258
  virtual HealthStatus healthStatus() const PURE;
259
260
  /**
261
   * Set the EDS health status of the host. This is used when the host status is updated via EDS.
262
   */
263
  virtual void setEdsHealthStatus(HealthStatus health_status) PURE;
264
265
  /**
266
   * @return the EDS health status of the host.
267
   */
268
  virtual HealthStatus edsHealthStatus() const PURE;
269
270
  /**
271
   * Set the host's health checker monitor. Monitors are assumed to be thread safe, however
272
   * a new monitor must be installed before the host is used across threads. Thus,
273
   * this routine should only be called on the main thread before the host is used across threads.
274
   */
275
  virtual void setHealthChecker(HealthCheckHostMonitorPtr&& health_checker) PURE;
276
277
  /**
278
   * Set the host's outlier detector monitor. Outlier detector monitors are assumed to be thread
279
   * safe, however a new outlier detector monitor must be installed before the host is used across
280
   * threads. Thus, this routine should only be called on the main thread before the host is used
281
   * across threads.
282
   */
283
  virtual void setOutlierDetector(Outlier::DetectorHostMonitorPtr&& outlier_detector) PURE;
284
285
  /**
286
   * Set the timestamp of when the host has transitioned from unhealthy to healthy state via an
287
   * active health checking.
288
   */
289
  virtual void setLastHcPassTime(MonotonicTime last_hc_pass_time) PURE;
290
291
  /**
292
   * @return the current load balancing weight of the host, in the range 1-128 (see
293
   * envoy.api.v2.endpoint.Endpoint.load_balancing_weight).
294
   */
295
  virtual uint32_t weight() const PURE;
296
297
  /**
298
   * Set the current load balancing weight of the host, in the range 1-128 (see
299
   * envoy.api.v2.endpoint.Endpoint.load_balancing_weight).
300
   */
301
  virtual void weight(uint32_t new_weight) PURE;
302
303
  /**
304
   * @return the current boolean value of host being in use by any connection pool.
305
   */
306
  virtual bool used() const PURE;
307
308
  /**
309
   * Creates a handle for a host. Deletion of the handle signals that the
310
   * connection pools no longer need this host.
311
   */
312
  virtual HostHandlePtr acquireHandle() const PURE;
313
314
  /**
315
   * @return true if active health check is disabled.
316
   */
317
  virtual bool disableActiveHealthCheck() const PURE;
318
319
  /**
320
   * Set true to disable active health check for the host.
321
   */
322
  virtual void setDisableActiveHealthCheck(bool disable_active_health_check) PURE;
323
};
324
325
using HostConstSharedPtr = std::shared_ptr<const Host>;
326
327
using HostVector = std::vector<HostSharedPtr>;
328
using HealthyHostVector = Phantom<HostVector, Healthy>;
329
using DegradedHostVector = Phantom<HostVector, Degraded>;
330
using ExcludedHostVector = Phantom<HostVector, Excluded>;
331
using HostMap = absl::flat_hash_map<std::string, Upstream::HostSharedPtr>;
332
using HostMapSharedPtr = std::shared_ptr<HostMap>;
333
using HostMapConstSharedPtr = std::shared_ptr<const HostMap>;
334
using HostVectorSharedPtr = std::shared_ptr<HostVector>;
335
using HostVectorConstSharedPtr = std::shared_ptr<const HostVector>;
336
337
using HealthyHostVectorConstSharedPtr = std::shared_ptr<const HealthyHostVector>;
338
using DegradedHostVectorConstSharedPtr = std::shared_ptr<const DegradedHostVector>;
339
using ExcludedHostVectorConstSharedPtr = std::shared_ptr<const ExcludedHostVector>;
340
341
using HostListPtr = std::unique_ptr<HostVector>;
342
using LocalityWeightsMap =
343
    absl::node_hash_map<envoy::config::core::v3::Locality, uint32_t, LocalityHash, LocalityEqualTo>;
344
using PriorityState = std::vector<std::pair<HostListPtr, LocalityWeightsMap>>;
345
346
/**
347
 * Bucket hosts by locality.
348
 */
349
class HostsPerLocality {
350
public:
351
257k
  virtual ~HostsPerLocality() = default;
352
353
  /**
354
   * @return bool is local locality one of the locality buckets? If so, the
355
   *         local locality will be the first in the get() vector.
356
   */
357
  virtual bool hasLocalLocality() const PURE;
358
359
  /**
360
   * @return const std::vector<HostVector>& list of hosts organized per
361
   *         locality. The local locality is the first entry if
362
   *         hasLocalLocality() is true. All hosts within the same entry have the same locality
363
   *         and all hosts with a given locality are in the same entry. With the exception of
364
   *         the local locality entry (if present), all entries are sorted by locality with
365
   *         those considered less by the LocalityLess comparator ordered earlier in the list.
366
   */
367
  virtual const std::vector<HostVector>& get() const PURE;
368
369
  /**
370
   * Clone object with multiple filter predicates. Returns a vector of clones, each with host that
371
   * match the provided predicates.
372
   * @param predicates vector of predicates on Host entries.
373
   * @return vector of HostsPerLocalityConstSharedPtr clones of the HostsPerLocality that match
374
   *         hosts according to predicates.
375
   */
376
  virtual std::vector<std::shared_ptr<const HostsPerLocality>>
377
  filter(const std::vector<std::function<bool(const Host&)>>& predicates) const PURE;
378
379
  /**
380
   * Clone object.
381
   * @return HostsPerLocalityConstSharedPtr clone of the HostsPerLocality.
382
   */
383
0
  std::shared_ptr<const HostsPerLocality> clone() const {
384
0
    return filter({[](const Host&) { return true; }})[0];
385
0
  }
386
};
387
388
using HostsPerLocalitySharedPtr = std::shared_ptr<HostsPerLocality>;
389
using HostsPerLocalityConstSharedPtr = std::shared_ptr<const HostsPerLocality>;
390
391
// Weight for each locality index in HostsPerLocality.
392
using LocalityWeights = std::vector<uint32_t>;
393
using LocalityWeightsSharedPtr = std::shared_ptr<LocalityWeights>;
394
using LocalityWeightsConstSharedPtr = std::shared_ptr<const LocalityWeights>;
395
396
/**
397
 * Base host set interface. This contains all of the endpoints for a given LocalityLbEndpoints
398
 * priority level.
399
 */
400
// TODO(snowp): Remove the const ref accessors in favor of the shared_ptr ones.
401
class HostSet {
402
public:
403
61.5k
  virtual ~HostSet() = default;
404
405
  /**
406
   * @return all hosts that make up the set at the current time.
407
   */
408
  virtual const HostVector& hosts() const PURE;
409
410
  /**
411
   * @return a shared ptr to the vector returned by hosts().
412
   */
413
  virtual HostVectorConstSharedPtr hostsPtr() const PURE;
414
415
  /**
416
   * @return all healthy hosts contained in the set at the current time. NOTE: This set is
417
   *         eventually consistent. There is a time window where a host in this set may become
418
   *         unhealthy and calling healthy() on it will return false. Code should be written to
419
   *         deal with this case if it matters.
420
   */
421
  virtual const HostVector& healthyHosts() const PURE;
422
423
  /**
424
   * @return a shared ptr to the vector returned by healthyHosts().
425
   */
426
  virtual HealthyHostVectorConstSharedPtr healthyHostsPtr() const PURE;
427
428
  /**
429
   * @return all degraded hosts contained in the set at the current time. NOTE: This set is
430
   *         eventually consistent. There is a time window where a host in this set may become
431
   *         undegraded and calling degraded() on it will return false. Code should be written to
432
   *         deal with this case if it matters.
433
   */
434
  virtual const HostVector& degradedHosts() const PURE;
435
436
  /**
437
   * @return a shared ptr to the vector returned by degradedHosts().
438
   */
439
  virtual DegradedHostVectorConstSharedPtr degradedHostsPtr() const PURE;
440
441
  /*
442
   * @return all excluded hosts contained in the set at the current time. Excluded hosts should be
443
   * ignored when computing load balancing weights, but may overlap with hosts in hosts().
444
   */
445
  virtual const HostVector& excludedHosts() const PURE;
446
447
  /**
448
   * @return a shared ptr to the vector returned by excludedHosts().
449
   */
450
  virtual ExcludedHostVectorConstSharedPtr excludedHostsPtr() const PURE;
451
452
  /**
453
   * @return hosts per locality.
454
   */
455
  virtual const HostsPerLocality& hostsPerLocality() const PURE;
456
457
  /**
458
   * @return a shared ptr to the HostsPerLocality returned by hostsPerLocality().
459
   */
460
  virtual HostsPerLocalityConstSharedPtr hostsPerLocalityPtr() const PURE;
461
462
  /**
463
   * @return same as hostsPerLocality but only contains healthy hosts.
464
   */
465
  virtual const HostsPerLocality& healthyHostsPerLocality() const PURE;
466
467
  /**
468
   * @return a shared ptr to the HostsPerLocality returned by healthyHostsPerLocality().
469
   */
470
  virtual HostsPerLocalityConstSharedPtr healthyHostsPerLocalityPtr() const PURE;
471
472
  /**
473
   * @return same as hostsPerLocality but only contains degraded hosts.
474
   */
475
  virtual const HostsPerLocality& degradedHostsPerLocality() const PURE;
476
477
  /**
478
   * @return a shared ptr to the HostsPerLocality returned by degradedHostsPerLocality().
479
   */
480
  virtual HostsPerLocalityConstSharedPtr degradedHostsPerLocalityPtr() const PURE;
481
482
  /**
483
   * @return same as hostsPerLocality but only contains excluded hosts.
484
   */
485
  virtual const HostsPerLocality& excludedHostsPerLocality() const PURE;
486
487
  /**
488
   * @return a shared ptr to the HostsPerLocality returned by excludedHostsPerLocality().
489
   */
490
  virtual HostsPerLocalityConstSharedPtr excludedHostsPerLocalityPtr() const PURE;
491
492
  /**
493
   * @return weights for each locality in the host set.
494
   */
495
  virtual LocalityWeightsConstSharedPtr localityWeights() const PURE;
496
497
  /**
498
   * @return next locality index to route to if performing locality weighted balancing
499
   * against healthy hosts.
500
   */
501
  virtual absl::optional<uint32_t> chooseHealthyLocality() PURE;
502
503
  /**
504
   * @return next locality index to route to if performing locality weighted balancing
505
   * against degraded hosts.
506
   */
507
  virtual absl::optional<uint32_t> chooseDegradedLocality() PURE;
508
509
  /**
510
   * @return uint32_t the priority of this host set.
511
   */
512
  virtual uint32_t priority() const PURE;
513
514
  /**
515
   * @return uint32_t the overprovisioning factor of this host set.
516
   */
517
  virtual uint32_t overprovisioningFactor() const PURE;
518
519
  /**
520
   * @return true to use host weights to calculate the health of a priority.
521
   */
522
  virtual bool weightedPriorityHealth() const PURE;
523
};
524
525
using HostSetPtr = std::unique_ptr<HostSet>;
526
527
/**
528
 * This class contains all of the HostSets for a given cluster grouped by priority, for
529
 * ease of load balancing.
530
 */
531
class PrioritySet {
532
public:
533
  using MemberUpdateCb =
534
      std::function<void(const HostVector& hosts_added, const HostVector& hosts_removed)>;
535
536
  using PriorityUpdateCb = std::function<void(uint32_t priority, const HostVector& hosts_added,
537
                                              const HostVector& hosts_removed)>;
538
539
56.7k
  virtual ~PrioritySet() = default;
540
541
  /**
542
   * Install a callback that will be invoked when any of the HostSets in the PrioritySet changes.
543
   * hosts_added and hosts_removed will only be populated when a host is added or completely removed
544
   * from the PrioritySet.
545
   * This includes when a new HostSet is created.
546
   *
547
   * @param callback supplies the callback to invoke.
548
   * @return Common::CallbackHandlePtr a handle which can be used to unregister the callback.
549
   */
550
  ABSL_MUST_USE_RESULT virtual Common::CallbackHandlePtr
551
  addMemberUpdateCb(MemberUpdateCb callback) const PURE;
552
553
  /**
554
   * Install a callback that will be invoked when a host set changes. Triggers when any change
555
   * happens to the hosts within the host set. If hosts are added/removed from the host set, the
556
   * added/removed hosts will be passed to the callback.
557
   *
558
   * @param callback supplies the callback to invoke.
559
   * @return Common::CallbackHandlePtr a handle which can be used to unregister the callback.
560
   */
561
  ABSL_MUST_USE_RESULT virtual Common::CallbackHandlePtr
562
  addPriorityUpdateCb(PriorityUpdateCb callback) const PURE;
563
564
  /**
565
   * @return const std::vector<HostSetPtr>& the host sets, ordered by priority.
566
   */
567
  virtual const std::vector<HostSetPtr>& hostSetsPerPriority() const PURE;
568
569
  /**
570
   * @return HostMapConstSharedPtr read only cross priority host map that indexed by host address
571
   * string.
572
   */
573
  virtual HostMapConstSharedPtr crossPriorityHostMap() const PURE;
574
575
  /**
576
   * Parameter class for updateHosts.
577
   */
578
  struct UpdateHostsParams {
579
    HostVectorConstSharedPtr hosts;
580
    HealthyHostVectorConstSharedPtr healthy_hosts;
581
    DegradedHostVectorConstSharedPtr degraded_hosts;
582
    ExcludedHostVectorConstSharedPtr excluded_hosts;
583
    HostsPerLocalityConstSharedPtr hosts_per_locality;
584
    HostsPerLocalityConstSharedPtr healthy_hosts_per_locality;
585
    HostsPerLocalityConstSharedPtr degraded_hosts_per_locality;
586
    HostsPerLocalityConstSharedPtr excluded_hosts_per_locality;
587
  };
588
589
  /**
590
   * Updates the hosts in a given host set.
591
   *
592
   * @param priority the priority of the host set to update.
593
   * @param update_hosts_param supplies the list of hosts and hosts per locality.
594
   * @param locality_weights supplies a map from locality to associated weight.
595
   * @param hosts_added supplies the hosts added since the last update.
596
   * @param hosts_removed supplies the hosts removed since the last update.
597
   * @param weighted_priority_health if present, overwrites the current weighted_priority_health.
598
   * @param overprovisioning_factor if present, overwrites the current overprovisioning_factor.
599
   * @param cross_priority_host_map read only cross-priority host map which is created in the main
600
   * thread and shared by all the worker threads.
601
   */
602
  virtual void updateHosts(uint32_t priority, UpdateHostsParams&& update_hosts_params,
603
                           LocalityWeightsConstSharedPtr locality_weights,
604
                           const HostVector& hosts_added, const HostVector& hosts_removed,
605
                           absl::optional<bool> weighted_priority_health,
606
                           absl::optional<uint32_t> overprovisioning_factor,
607
                           HostMapConstSharedPtr cross_priority_host_map = nullptr) PURE;
608
609
  /**
610
   * Callback provided during batch updates that can be used to update hosts.
611
   */
612
  class HostUpdateCb {
613
  public:
614
14
    virtual ~HostUpdateCb() = default;
615
    /**
616
     * Updates the hosts in a given host set.
617
     *
618
     * @param priority the priority of the host set to update.
619
     * @param update_hosts_param supplies the list of hosts and hosts per locality.
620
     * @param locality_weights supplies a map from locality to associated weight.
621
     * @param hosts_added supplies the hosts added since the last update.
622
     * @param hosts_removed supplies the hosts removed since the last update.
623
     * @param weighted_priority_health if present, overwrites the current weighted_priority_health.
624
     * @param overprovisioning_factor if present, overwrites the current overprovisioning_factor.
625
     */
626
    virtual void updateHosts(uint32_t priority, UpdateHostsParams&& update_hosts_params,
627
                             LocalityWeightsConstSharedPtr locality_weights,
628
                             const HostVector& hosts_added, const HostVector& hosts_removed,
629
                             absl::optional<bool> weighted_priority_health,
630
                             absl::optional<uint32_t> overprovisioning_factor) PURE;
631
  };
632
633
  /**
634
   * Callback that provides the mechanism for performing batch host updates for a PrioritySet.
635
   */
636
  class BatchUpdateCb {
637
  public:
638
14
    virtual ~BatchUpdateCb() = default;
639
640
    /**
641
     * Performs a batch host update. Implementors should use the provided callback to update hosts
642
     * in the PrioritySet.
643
     */
644
    virtual void batchUpdate(HostUpdateCb& host_update_cb) PURE;
645
  };
646
647
  /**
648
   * Allows updating hosts for multiple priorities at once, deferring the MemberUpdateCb from
649
   * triggering until all priorities have been updated. The resulting callback will take into
650
   * account hosts moved from one priority to another.
651
   *
652
   * @param callback callback to use to add hosts.
653
   */
654
  virtual void batchHostUpdate(BatchUpdateCb& callback) PURE;
655
};
656
657
/**
658
 * All cluster config update related stats.
659
 * See https://github.com/envoyproxy/envoy/issues/23575 for details. Stats from ClusterInfo::stats()
660
 * will be split into subgroups "config-update", "lb", "endpoint" and "the rest"(which are mainly
661
 * upstream related), roughly based on their semantics.
662
 */
663
#define ALL_CLUSTER_CONFIG_UPDATE_STATS(COUNTER, GAUGE, HISTOGRAM, TEXT_READOUT, STATNAME)         \
664
  COUNTER(assignment_stale)                                                                        \
665
  COUNTER(assignment_timeout_received)                                                             \
666
  COUNTER(assignment_use_cached)                                                                   \
667
  COUNTER(update_attempt)                                                                          \
668
  COUNTER(update_empty)                                                                            \
669
  COUNTER(update_failure)                                                                          \
670
  COUNTER(update_no_rebuild)                                                                       \
671
  COUNTER(update_success)                                                                          \
672
  GAUGE(version, NeverImport)                                                                      \
673
  GAUGE(warming_state, NeverImport)
674
675
/**
676
 * All cluster endpoints related stats.
677
 */
678
#define ALL_CLUSTER_ENDPOINT_STATS(COUNTER, GAUGE, HISTOGRAM, TEXT_READOUT, STATNAME)              \
679
  GAUGE(max_host_weight, NeverImport)                                                              \
680
  COUNTER(membership_change)                                                                       \
681
  GAUGE(membership_degraded, NeverImport)                                                          \
682
  GAUGE(membership_excluded, NeverImport)                                                          \
683
  GAUGE(membership_healthy, NeverImport)                                                           \
684
  GAUGE(membership_total, NeverImport)
685
686
/**
687
 * All cluster load balancing related stats.
688
 */
689
#define ALL_CLUSTER_LB_STATS(COUNTER, GAUGE, HISTOGRAM, TEXT_READOUT, STATNAME)                    \
690
  COUNTER(lb_healthy_panic)                                                                        \
691
  COUNTER(lb_local_cluster_not_ok)                                                                 \
692
  COUNTER(lb_recalculate_zone_structures)                                                          \
693
  COUNTER(lb_subsets_created)                                                                      \
694
  COUNTER(lb_subsets_fallback)                                                                     \
695
  COUNTER(lb_subsets_fallback_panic)                                                               \
696
  COUNTER(lb_subsets_removed)                                                                      \
697
  COUNTER(lb_subsets_selected)                                                                     \
698
  COUNTER(lb_zone_cluster_too_small)                                                               \
699
  COUNTER(lb_zone_no_capacity_left)                                                                \
700
  COUNTER(lb_zone_number_differs)                                                                  \
701
  COUNTER(lb_zone_routing_all_directly)                                                            \
702
  COUNTER(lb_zone_routing_cross_zone)                                                              \
703
  COUNTER(lb_zone_routing_sampled)                                                                 \
704
  GAUGE(lb_subsets_active, Accumulate)
705
706
/**
707
 * All cluster stats. @see stats_macros.h
708
 */
709
#define ALL_CLUSTER_TRAFFIC_STATS(COUNTER, GAUGE, HISTOGRAM, TEXT_READOUT, STATNAME)               \
710
  COUNTER(bind_errors)                                                                             \
711
  COUNTER(original_dst_host_invalid)                                                               \
712
  COUNTER(retry_or_shadow_abandoned)                                                               \
713
  COUNTER(upstream_cx_close_notify)                                                                \
714
  COUNTER(upstream_cx_connect_attempts_exceeded)                                                   \
715
  COUNTER(upstream_cx_connect_fail)                                                                \
716
  COUNTER(upstream_cx_connect_timeout)                                                             \
717
  COUNTER(upstream_cx_connect_with_0_rtt)                                                          \
718
  COUNTER(upstream_cx_destroy)                                                                     \
719
  COUNTER(upstream_cx_destroy_local)                                                               \
720
  COUNTER(upstream_cx_destroy_local_with_active_rq)                                                \
721
  COUNTER(upstream_cx_destroy_remote)                                                              \
722
  COUNTER(upstream_cx_destroy_remote_with_active_rq)                                               \
723
  COUNTER(upstream_cx_destroy_with_active_rq)                                                      \
724
  COUNTER(upstream_cx_http1_total)                                                                 \
725
  COUNTER(upstream_cx_http2_total)                                                                 \
726
  COUNTER(upstream_cx_http3_total)                                                                 \
727
  COUNTER(upstream_cx_idle_timeout)                                                                \
728
  COUNTER(upstream_cx_max_duration_reached)                                                        \
729
  COUNTER(upstream_cx_max_requests)                                                                \
730
  COUNTER(upstream_cx_none_healthy)                                                                \
731
  COUNTER(upstream_cx_overflow)                                                                    \
732
  COUNTER(upstream_cx_pool_overflow)                                                               \
733
  COUNTER(upstream_cx_protocol_error)                                                              \
734
  COUNTER(upstream_cx_rx_bytes_total)                                                              \
735
  COUNTER(upstream_cx_total)                                                                       \
736
  COUNTER(upstream_cx_tx_bytes_total)                                                              \
737
  COUNTER(upstream_flow_control_backed_up_total)                                                   \
738
  COUNTER(upstream_flow_control_drained_total)                                                     \
739
  COUNTER(upstream_flow_control_paused_reading_total)                                              \
740
  COUNTER(upstream_flow_control_resumed_reading_total)                                             \
741
  COUNTER(upstream_internal_redirect_failed_total)                                                 \
742
  COUNTER(upstream_internal_redirect_succeeded_total)                                              \
743
  COUNTER(upstream_rq_cancelled)                                                                   \
744
  COUNTER(upstream_rq_completed)                                                                   \
745
  COUNTER(upstream_rq_maintenance_mode)                                                            \
746
  COUNTER(upstream_rq_max_duration_reached)                                                        \
747
  COUNTER(upstream_rq_pending_failure_eject)                                                       \
748
  COUNTER(upstream_rq_pending_overflow)                                                            \
749
  COUNTER(upstream_rq_pending_total)                                                               \
750
  COUNTER(upstream_rq_0rtt)                                                                        \
751
  COUNTER(upstream_rq_per_try_timeout)                                                             \
752
  COUNTER(upstream_rq_per_try_idle_timeout)                                                        \
753
  COUNTER(upstream_rq_retry)                                                                       \
754
  COUNTER(upstream_rq_retry_backoff_exponential)                                                   \
755
  COUNTER(upstream_rq_retry_backoff_ratelimited)                                                   \
756
  COUNTER(upstream_rq_retry_limit_exceeded)                                                        \
757
  COUNTER(upstream_rq_retry_overflow)                                                              \
758
  COUNTER(upstream_rq_retry_success)                                                               \
759
  COUNTER(upstream_rq_rx_reset)                                                                    \
760
  COUNTER(upstream_rq_timeout)                                                                     \
761
  COUNTER(upstream_rq_total)                                                                       \
762
  COUNTER(upstream_rq_tx_reset)                                                                    \
763
  COUNTER(upstream_http3_broken)                                                                   \
764
  GAUGE(upstream_cx_active, Accumulate)                                                            \
765
  GAUGE(upstream_cx_rx_bytes_buffered, Accumulate)                                                 \
766
  GAUGE(upstream_cx_tx_bytes_buffered, Accumulate)                                                 \
767
  GAUGE(upstream_rq_active, Accumulate)                                                            \
768
  GAUGE(upstream_rq_pending_active, Accumulate)                                                    \
769
  HISTOGRAM(upstream_cx_connect_ms, Milliseconds)                                                  \
770
  HISTOGRAM(upstream_cx_length_ms, Milliseconds)
771
772
/**
773
 * All cluster load report stats. These are only use for EDS load reporting and not sent to the
774
 * stats sink. See envoy.api.v2.endpoint.ClusterStats for the definition of upstream_rq_dropped.
775
 * These are latched by LoadStatsReporter, independent of the normal stats sink flushing.
776
 */
777
#define ALL_CLUSTER_LOAD_REPORT_STATS(COUNTER, GAUGE, HISTOGRAM, TEXT_READOUT, STATNAME)           \
778
  COUNTER(upstream_rq_dropped)
779
780
/**
781
 * Cluster circuit breakers gauges. Note that we do not generate a stats
782
 * structure from this macro. This is because depending on flags, we want to use
783
 * null gauges for all the "remaining" ones. This is hard to automate with the
784
 * 2-phase macros, so ClusterInfoImpl::generateCircuitBreakersStats is
785
 * hand-coded and must be changed if we alter the set of gauges in this macro.
786
 * We also include stat-names in this structure that are used when composing
787
 * the circuit breaker names, depending on priority settings.
788
 */
789
#define ALL_CLUSTER_CIRCUIT_BREAKERS_STATS(COUNTER, GAUGE, HISTOGRAM, TEXT_READOUT, STATNAME)      \
790
  GAUGE(cx_open, Accumulate)                                                                       \
791
  GAUGE(cx_pool_open, Accumulate)                                                                  \
792
  GAUGE(rq_open, Accumulate)                                                                       \
793
  GAUGE(rq_pending_open, Accumulate)                                                               \
794
  GAUGE(rq_retry_open, Accumulate)                                                                 \
795
  GAUGE(remaining_cx, Accumulate)                                                                  \
796
  GAUGE(remaining_cx_pools, Accumulate)                                                            \
797
  GAUGE(remaining_pending, Accumulate)                                                             \
798
  GAUGE(remaining_retries, Accumulate)                                                             \
799
  GAUGE(remaining_rq, Accumulate)                                                                  \
800
  STATNAME(circuit_breakers)                                                                       \
801
  STATNAME(default)                                                                                \
802
  STATNAME(high)
803
804
/**
805
 * All stats tracking request/response headers and body sizes. Not used by default.
806
 */
807
#define ALL_CLUSTER_REQUEST_RESPONSE_SIZE_STATS(COUNTER, GAUGE, HISTOGRAM, TEXT_READOUT, STATNAME) \
808
  HISTOGRAM(upstream_rq_headers_size, Bytes)                                                       \
809
  HISTOGRAM(upstream_rq_body_size, Bytes)                                                          \
810
  HISTOGRAM(upstream_rs_headers_size, Bytes)                                                       \
811
  HISTOGRAM(upstream_rs_body_size, Bytes)
812
813
/**
814
 * All stats around timeout budgets. Not used by default.
815
 */
816
#define ALL_CLUSTER_TIMEOUT_BUDGET_STATS(COUNTER, GAUGE, HISTOGRAM, TEXT_READOUT, STATNAME)        \
817
  HISTOGRAM(upstream_rq_timeout_budget_percent_used, Unspecified)                                  \
818
  HISTOGRAM(upstream_rq_timeout_budget_per_try_percent_used, Unspecified)
819
820
/**
821
 * Struct definition for cluster config update stats. @see stats_macros.h
822
 */
823
MAKE_STAT_NAMES_STRUCT(ClusterConfigUpdateStatNames, ALL_CLUSTER_CONFIG_UPDATE_STATS);
824
MAKE_STATS_STRUCT(ClusterConfigUpdateStats, ClusterConfigUpdateStatNames,
825
                  ALL_CLUSTER_CONFIG_UPDATE_STATS);
826
827
/**
828
 * Struct definition for cluster endpoint related stats. @see stats_macros.h
829
 */
830
MAKE_STAT_NAMES_STRUCT(ClusterEndpointStatNames, ALL_CLUSTER_ENDPOINT_STATS);
831
MAKE_STATS_STRUCT(ClusterEndpointStats, ClusterEndpointStatNames, ALL_CLUSTER_ENDPOINT_STATS);
832
833
/**
834
 * Struct definition for cluster load balancing stats. @see stats_macros.h
835
 */
836
MAKE_STAT_NAMES_STRUCT(ClusterLbStatNames, ALL_CLUSTER_LB_STATS);
837
MAKE_STATS_STRUCT(ClusterLbStats, ClusterLbStatNames, ALL_CLUSTER_LB_STATS);
838
839
/**
840
 * Struct definition for all cluster traffic stats. @see stats_macros.h
841
 */
842
MAKE_STAT_NAMES_STRUCT(ClusterTrafficStatNames, ALL_CLUSTER_TRAFFIC_STATS);
843
MAKE_STATS_STRUCT(ClusterTrafficStats, ClusterTrafficStatNames, ALL_CLUSTER_TRAFFIC_STATS);
844
using DeferredCreationCompatibleClusterTrafficStats =
845
    Stats::DeferredCreationCompatibleStats<ClusterTrafficStats>;
846
847
MAKE_STAT_NAMES_STRUCT(ClusterLoadReportStatNames, ALL_CLUSTER_LOAD_REPORT_STATS);
848
MAKE_STATS_STRUCT(ClusterLoadReportStats, ClusterLoadReportStatNames,
849
                  ALL_CLUSTER_LOAD_REPORT_STATS);
850
851
// We can't use macros to make the Stats class for circuit breakers due to
852
// the conditional inclusion of 'remaining' gauges. But we do auto-generate
853
// the StatNames struct.
854
MAKE_STAT_NAMES_STRUCT(ClusterCircuitBreakersStatNames, ALL_CLUSTER_CIRCUIT_BREAKERS_STATS);
855
856
MAKE_STAT_NAMES_STRUCT(ClusterRequestResponseSizeStatNames,
857
                       ALL_CLUSTER_REQUEST_RESPONSE_SIZE_STATS);
858
MAKE_STATS_STRUCT(ClusterRequestResponseSizeStats, ClusterRequestResponseSizeStatNames,
859
                  ALL_CLUSTER_REQUEST_RESPONSE_SIZE_STATS);
860
861
MAKE_STAT_NAMES_STRUCT(ClusterTimeoutBudgetStatNames, ALL_CLUSTER_TIMEOUT_BUDGET_STATS);
862
MAKE_STATS_STRUCT(ClusterTimeoutBudgetStats, ClusterTimeoutBudgetStatNames,
863
                  ALL_CLUSTER_TIMEOUT_BUDGET_STATS);
864
865
/**
866
 * Struct definition for cluster circuit breakers stats. @see stats_macros.h
867
 */
868
struct ClusterCircuitBreakersStats {
869
  ALL_CLUSTER_CIRCUIT_BREAKERS_STATS(c, GENERATE_GAUGE_STRUCT, h, tr, GENERATE_STATNAME_STRUCT)
870
};
871
872
using ClusterRequestResponseSizeStatsPtr = std::unique_ptr<ClusterRequestResponseSizeStats>;
873
using ClusterRequestResponseSizeStatsOptRef =
874
    absl::optional<std::reference_wrapper<ClusterRequestResponseSizeStats>>;
875
876
using ClusterTimeoutBudgetStatsPtr = std::unique_ptr<ClusterTimeoutBudgetStats>;
877
using ClusterTimeoutBudgetStatsOptRef =
878
    absl::optional<std::reference_wrapper<ClusterTimeoutBudgetStats>>;
879
880
/**
881
 * All extension protocol specific options returned by the method at
882
 *   NamedNetworkFilterConfigFactory::createProtocolOptions
883
 * must be derived from this class.
884
 */
885
class ProtocolOptionsConfig {
886
public:
887
3.26k
  virtual ~ProtocolOptionsConfig() = default;
888
};
889
using ProtocolOptionsConfigConstSharedPtr = std::shared_ptr<const ProtocolOptionsConfig>;
890
891
/**
892
 *  Base class for all cluster typed metadata factory.
893
 */
894
class ClusterTypedMetadataFactory : public Envoy::Config::TypedMetadataFactory {};
895
896
class LoadBalancerConfig;
897
class TypedLoadBalancerFactory;
898
899
/**
900
 * This is a function used by upstream binding config to select the source address based on the
901
 * target address. Given the target address through the parameter expect the source address
902
 * returned.
903
 */
904
using AddressSelectFn = std::function<const Network::Address::InstanceConstSharedPtr(
905
    const Network::Address::InstanceConstSharedPtr&)>;
906
907
/**
908
 * Information about a given upstream cluster.
909
 * This includes the information and interfaces for building an upstream filter chain.
910
 */
911
class ClusterInfo : public Http::FilterChainFactory {
912
public:
913
  struct Features {
914
    // Whether the upstream supports HTTP2. This is used when creating connection pools.
915
    static constexpr uint64_t HTTP2 = 0x1;
916
    // Use the downstream protocol (HTTP1.1, HTTP2) for upstream connections as well, if available.
917
    // This is used when creating connection pools.
918
    static constexpr uint64_t USE_DOWNSTREAM_PROTOCOL = 0x2;
919
    // Whether connections should be immediately closed upon health failure.
920
    static constexpr uint64_t CLOSE_CONNECTIONS_ON_HOST_HEALTH_FAILURE = 0x4;
921
    // If USE_ALPN and HTTP2 are true, the upstream protocol will be negotiated using ALPN.
922
    // If ALPN is attempted but not supported by the upstream HTTP/1.1 is used.
923
    static constexpr uint64_t USE_ALPN = 0x8;
924
    // Whether the upstream supports HTTP3. This is used when creating connection pools.
925
    static constexpr uint64_t HTTP3 = 0x10;
926
  };
927
928
  ~ClusterInfo() override = default;
929
930
  /**
931
   * @return bool whether the cluster was added via API (if false the cluster was present in the
932
   *         initial configuration and cannot be removed or updated).
933
   */
934
  virtual bool addedViaApi() const PURE;
935
936
  /**
937
   * @return the connect timeout for upstream hosts that belong to this cluster.
938
   */
939
  virtual std::chrono::milliseconds connectTimeout() const PURE;
940
941
  /**
942
   * @return the idle timeout for upstream HTTP connection pool connections.
943
   */
944
  virtual const absl::optional<std::chrono::milliseconds> idleTimeout() const PURE;
945
946
  /**
947
   * @return the idle timeout for each connection in TCP connection pool.
948
   */
949
  virtual const absl::optional<std::chrono::milliseconds> tcpPoolIdleTimeout() const PURE;
950
951
  /**
952
   * @return optional maximum connection duration timeout for manager connections.
953
   */
954
  virtual const absl::optional<std::chrono::milliseconds> maxConnectionDuration() const PURE;
955
956
  /**
957
   * @return how many streams should be anticipated per each current stream.
958
   */
959
  virtual float perUpstreamPreconnectRatio() const PURE;
960
961
  /**
962
   * @return how many streams should be anticipated per each current stream.
963
   */
964
  virtual float peekaheadRatio() const PURE;
965
966
  /**
967
   * @return soft limit on size of the cluster's connections read and write buffers.
968
   */
969
  virtual uint32_t perConnectionBufferLimitBytes() const PURE;
970
971
  /**
972
   * @return uint64_t features supported by the cluster. @see Features.
973
   */
974
  virtual uint64_t features() const PURE;
975
976
  /**
977
   * @return const Http::Http1Settings& for HTTP/1.1 connections created on behalf of this cluster.
978
   *         @see Http::Http1Settings.
979
   */
980
  virtual const Http::Http1Settings& http1Settings() const PURE;
981
982
  /**
983
   * @return const envoy::config::core::v3::Http2ProtocolOptions& for HTTP/2 connections
984
   * created on behalf of this cluster.
985
   *         @see envoy::config::core::v3::Http2ProtocolOptions.
986
   */
987
  virtual const envoy::config::core::v3::Http2ProtocolOptions& http2Options() const PURE;
988
989
  /**
990
   * @return const envoy::config::core::v3::Http3ProtocolOptions& for HTTP/3 connections
991
   * created on behalf of this cluster. @see envoy::config::core::v3::Http3ProtocolOptions.
992
   */
993
  virtual const envoy::config::core::v3::Http3ProtocolOptions& http3Options() const PURE;
994
995
  /**
996
   * @return const envoy::config::core::v3::HttpProtocolOptions for all of HTTP versions.
997
   */
998
  virtual const envoy::config::core::v3::HttpProtocolOptions&
999
  commonHttpProtocolOptions() const PURE;
1000
1001
  /**
1002
   * @param name std::string containing the well-known name of the extension for which protocol
1003
   *        options are desired
1004
   * @return std::shared_ptr<const Derived> where Derived is a subclass of ProtocolOptionsConfig
1005
   *         and contains extension-specific protocol options for upstream connections.
1006
   */
1007
  template <class Derived>
1008
6.53k
  std::shared_ptr<const Derived> extensionProtocolOptionsTyped(const std::string& name) const {
1009
6.53k
    return std::dynamic_pointer_cast<const Derived>(extensionProtocolOptions(name));
1010
6.53k
  }
std::__1::shared_ptr<Envoy::Extensions::Upstreams::Http::ProtocolOptionsConfigImpl const> Envoy::Upstream::ClusterInfo::extensionProtocolOptionsTyped<Envoy::Extensions::Upstreams::Http::ProtocolOptionsConfigImpl>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) const
Line
Count
Source
1008
3.26k
  std::shared_ptr<const Derived> extensionProtocolOptionsTyped(const std::string& name) const {
1009
3.26k
    return std::dynamic_pointer_cast<const Derived>(extensionProtocolOptions(name));
1010
3.26k
  }
std::__1::shared_ptr<Envoy::Extensions::Upstreams::Tcp::ProtocolOptionsConfigImpl const> Envoy::Upstream::ClusterInfo::extensionProtocolOptionsTyped<Envoy::Extensions::Upstreams::Tcp::ProtocolOptionsConfigImpl>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) const
Line
Count
Source
1008
3.26k
  std::shared_ptr<const Derived> extensionProtocolOptionsTyped(const std::string& name) const {
1009
3.26k
    return std::dynamic_pointer_cast<const Derived>(extensionProtocolOptions(name));
1010
3.26k
  }
Unexecuted instantiation: std::__1::shared_ptr<Envoy::Extensions::NetworkFilters::RedisProxy::ProtocolOptionsConfigImpl const> Envoy::Upstream::ClusterInfo::extensionProtocolOptionsTyped<Envoy::Extensions::NetworkFilters::RedisProxy::ProtocolOptionsConfigImpl>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) const
Unexecuted instantiation: std::__1::shared_ptr<Envoy::Extensions::NetworkFilters::ThriftProxy::ProtocolOptionsConfig const> Envoy::Upstream::ClusterInfo::extensionProtocolOptionsTyped<Envoy::Extensions::NetworkFilters::ThriftProxy::ProtocolOptionsConfig>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) const
1011
1012
  /**
1013
   * @return OptRef<const LoadBalancerConfig> the validated load balancing policy configuration to
1014
   * use for this cluster.
1015
   */
1016
  virtual OptRef<const LoadBalancerConfig> loadBalancerConfig() const PURE;
1017
1018
  /**
1019
   * @return the load balancer factory for this cluster if the load balancing type is
1020
   * LOAD_BALANCING_POLICY_CONFIG.
1021
   * TODO(wbpcode): change the return type to return a reference after
1022
   * 'envoy_reloadable_features_convert_legacy_lb_config' is removed. The factory should never be
1023
   * nullptr when the load balancing type is LOAD_BALANCING_POLICY_CONFIG.
1024
   */
1025
  virtual TypedLoadBalancerFactory* loadBalancerFactory() const PURE;
1026
1027
  /**
1028
   * @return const envoy::config::cluster::v3::Cluster::CommonLbConfig& the common configuration for
1029
   * all load balancers for this cluster.
1030
   */
1031
  virtual const envoy::config::cluster::v3::Cluster::CommonLbConfig& lbConfig() const PURE;
1032
1033
  /**
1034
   * @return the type of load balancing that the cluster should use.
1035
   */
1036
  virtual LoadBalancerType lbType() const PURE;
1037
1038
  /**
1039
   * @return the service discovery type to use for resolving the cluster.
1040
   */
1041
  virtual envoy::config::cluster::v3::Cluster::DiscoveryType type() const PURE;
1042
1043
  /**
1044
   * @return the type of cluster, only used for custom discovery types.
1045
   */
1046
  virtual OptRef<const envoy::config::cluster::v3::Cluster::CustomClusterType>
1047
  clusterType() const PURE;
1048
1049
  /**
1050
   * @return configuration for round robin load balancing, only used if LB type is round robin.
1051
   */
1052
  virtual OptRef<const envoy::config::cluster::v3::Cluster::RoundRobinLbConfig>
1053
  lbRoundRobinConfig() const PURE;
1054
1055
  /**
1056
   * @return configuration for least request load balancing, only used if LB type is least request.
1057
   */
1058
  virtual OptRef<const envoy::config::cluster::v3::Cluster::LeastRequestLbConfig>
1059
  lbLeastRequestConfig() const PURE;
1060
1061
  /**
1062
   * @return configuration for ring hash load balancing, only used if type is set to ring_hash_lb.
1063
   */
1064
  virtual OptRef<const envoy::config::cluster::v3::Cluster::RingHashLbConfig>
1065
  lbRingHashConfig() const PURE;
1066
1067
  /**
1068
   * @return configuration for maglev load balancing, only used if type is set to maglev_lb.
1069
   */
1070
  virtual OptRef<const envoy::config::cluster::v3::Cluster::MaglevLbConfig>
1071
  lbMaglevConfig() const PURE;
1072
1073
  /**
1074
   * @return const absl::optional<envoy::config::cluster::v3::Cluster::OriginalDstLbConfig>& the
1075
   * configuration for the Original Destination load balancing policy, only used if type is set to
1076
   *         ORIGINAL_DST_LB.
1077
   */
1078
  virtual OptRef<const envoy::config::cluster::v3::Cluster::OriginalDstLbConfig>
1079
  lbOriginalDstConfig() const PURE;
1080
1081
  /**
1082
   * @return const absl::optional<envoy::config::core::v3::TypedExtensionConfig>& the configuration
1083
   *         for the upstream, if a custom upstream is configured.
1084
   */
1085
  virtual OptRef<const envoy::config::core::v3::TypedExtensionConfig> upstreamConfig() const PURE;
1086
1087
  /**
1088
   * @return Whether the cluster is currently in maintenance mode and should not be routed to.
1089
   *         Different filters may handle this situation in different ways. The implementation
1090
   *         of this routine is typically based on randomness and may not return the same answer
1091
   *         on each call.
1092
   */
1093
  virtual bool maintenanceMode() const PURE;
1094
1095
  /**
1096
   * @return uint64_t the maximum number of outbound requests that a connection pool will make on
1097
   *         each upstream connection. This can be used to increase spread if the backends cannot
1098
   *         tolerate imbalance. 0 indicates no maximum.
1099
   */
1100
  virtual uint64_t maxRequestsPerConnection() const PURE;
1101
1102
  /**
1103
   * @return uint32_t the maximum number of response headers. The default value is 100. Results in a
1104
   * reset if the number of headers exceeds this value.
1105
   */
1106
  virtual uint32_t maxResponseHeadersCount() const PURE;
1107
1108
  /**
1109
   * @return the human readable name of the cluster.
1110
   */
1111
  virtual const std::string& name() const PURE;
1112
1113
  /**
1114
   * @return the observability name associated to the cluster. Used in stats, tracing, logging, and
1115
   * config dumps. The observability name is configured with :ref:`alt_stat_name
1116
   * <envoy_api_field_config.cluster.v3.Cluster.alt_stat_name>`. If unprovided, the default value is
1117
   * the cluster name.
1118
   */
1119
  virtual const std::string& observabilityName() const PURE;
1120
1121
  /**
1122
   * @return ResourceManager& the resource manager to use by proxy agents for this cluster (at
1123
   *         a particular priority).
1124
   */
1125
  virtual ResourceManager& resourceManager(ResourcePriority priority) const PURE;
1126
1127
  /**
1128
   * @return TransportSocketMatcher& the transport socket matcher associated
1129
   * factory.
1130
   */
1131
  virtual TransportSocketMatcher& transportSocketMatcher() const PURE;
1132
1133
  /**
1134
   * @return ClusterConfigUpdateStats& config update stats for this cluster.
1135
   */
1136
  virtual ClusterConfigUpdateStats& configUpdateStats() const PURE;
1137
1138
  /**
1139
   * @return ClusterLbStats& load-balancer-related stats for this cluster.
1140
   */
1141
  virtual ClusterLbStats& lbStats() const PURE;
1142
1143
  /**
1144
   * @return ClusterEndpointStats& endpoint related stats for this cluster.
1145
   */
1146
  virtual ClusterEndpointStats& endpointStats() const PURE;
1147
1148
  /**
1149
   * @return  all traffic related stats for this cluster.
1150
   */
1151
  virtual DeferredCreationCompatibleClusterTrafficStats& trafficStats() const PURE;
1152
  /**
1153
   * @return the stats scope that contains all cluster stats. This can be used to produce dynamic
1154
   *         stats that will be freed when the cluster is removed.
1155
   */
1156
  virtual Stats::Scope& statsScope() const PURE;
1157
1158
  /**
1159
   * @return ClusterLoadReportStats& load report stats for this cluster.
1160
   */
1161
  virtual ClusterLoadReportStats& loadReportStats() const PURE;
1162
1163
  /**
1164
   * @return absl::optional<std::reference_wrapper<ClusterRequestResponseSizeStats>> stats to track
1165
   * headers/body sizes of request/response for this cluster.
1166
   */
1167
  virtual ClusterRequestResponseSizeStatsOptRef requestResponseSizeStats() const PURE;
1168
1169
  /**
1170
   * @return absl::optional<std::reference_wrapper<ClusterTimeoutBudgetStats>> stats on timeout
1171
   * budgets for this cluster.
1172
   */
1173
  virtual ClusterTimeoutBudgetStatsOptRef timeoutBudgetStats() const PURE;
1174
1175
  /**
1176
   * @return true if this cluster should produce per-endpoint stats.
1177
   */
1178
  virtual bool perEndpointStatsEnabled() const PURE;
1179
1180
  /**
1181
   * @return std::shared_ptr<UpstreamLocalAddressSelector> as upstream local address selector.
1182
   */
1183
  virtual UpstreamLocalAddressSelectorConstSharedPtr getUpstreamLocalAddressSelector() const PURE;
1184
1185
  /**
1186
   * @return the configuration for load balancer subsets.
1187
   */
1188
  virtual const LoadBalancerSubsetInfo& lbSubsetInfo() const PURE;
1189
1190
  /**
1191
   * @return const envoy::config::core::v3::Metadata& the configuration metadata for this cluster.
1192
   */
1193
  virtual const envoy::config::core::v3::Metadata& metadata() const PURE;
1194
1195
  /**
1196
   * @return const Envoy::Config::TypedMetadata&& the typed metadata for this cluster.
1197
   */
1198
  virtual const Envoy::Config::TypedMetadata& typedMetadata() const PURE;
1199
1200
  /**
1201
   * @return whether to skip waiting for health checking before draining connections
1202
   *         after a host is removed from service discovery.
1203
   */
1204
  virtual bool drainConnectionsOnHostRemoval() const PURE;
1205
1206
  /**
1207
   *  @return whether to create a new connection pool for each downstream connection routed to
1208
   *          the cluster
1209
   */
1210
  virtual bool connectionPoolPerDownstreamConnection() const PURE;
1211
1212
  /**
1213
   * @return true if this cluster is configured to ignore hosts for the purpose of load balancing
1214
   * computations until they have been health checked for the first time.
1215
   */
1216
  virtual bool warmHosts() const PURE;
1217
1218
  /**
1219
   * @return true if this cluster is configured to set local interface name on upstream connections.
1220
   */
1221
  virtual bool setLocalInterfaceNameOnUpstreamConnections() const PURE;
1222
1223
  /**
1224
   * @return const std::string& eds cluster service_name of the cluster. Empty if not an EDS
1225
   * cluster or eds cluster service_name is not set.
1226
   */
1227
  virtual const std::string& edsServiceName() const PURE;
1228
1229
  /**
1230
   * Create network filters on a new upstream connection.
1231
   */
1232
  virtual void createNetworkFilterChain(Network::Connection& connection) const PURE;
1233
1234
  /**
1235
   * Calculate upstream protocol(s) based on features.
1236
   */
1237
  virtual std::vector<Http::Protocol>
1238
  upstreamHttpProtocol(absl::optional<Http::Protocol> downstream_protocol) const PURE;
1239
1240
  /**
1241
   * @return http protocol options for upstream connection
1242
   */
1243
  virtual const absl::optional<envoy::config::core::v3::UpstreamHttpProtocolOptions>&
1244
  upstreamHttpProtocolOptions() const PURE;
1245
1246
  /**
1247
   * @return alternate protocols cache options for upstream connections.
1248
   */
1249
  virtual const absl::optional<const envoy::config::core::v3::AlternateProtocolsCacheOptions>&
1250
  alternateProtocolsCacheOptions() const PURE;
1251
1252
  /**
1253
   * @return the Http1 Codec Stats.
1254
   */
1255
  virtual Http::Http1::CodecStats& http1CodecStats() const PURE;
1256
1257
  /**
1258
   * @return the Http2 Codec Stats.
1259
   */
1260
  virtual Http::Http2::CodecStats& http2CodecStats() const PURE;
1261
1262
  /**
1263
   * @return the Http3 Codec Stats.
1264
   */
1265
  virtual Http::Http3::CodecStats& http3CodecStats() const PURE;
1266
1267
  /**
1268
   * @return create header validator based on cluster configuration. Returns nullptr if
1269
   * ENVOY_ENABLE_UHV is undefined.
1270
   */
1271
  virtual Http::ClientHeaderValidatorPtr makeHeaderValidator(Http::Protocol protocol) const PURE;
1272
1273
protected:
1274
  /**
1275
   * Invoked by extensionProtocolOptionsTyped.
1276
   * @param name std::string containing the well-known name of the extension for which protocol
1277
   *        options are desired
1278
   * @return ProtocolOptionsConfigConstSharedPtr with extension-specific protocol options for
1279
   *         upstream connections.
1280
   */
1281
  virtual ProtocolOptionsConfigConstSharedPtr
1282
  extensionProtocolOptions(const std::string& name) const PURE;
1283
};
1284
1285
using ClusterInfoConstSharedPtr = std::shared_ptr<const ClusterInfo>;
1286
1287
class HealthChecker;
1288
1289
/**
1290
 * An upstream cluster (group of hosts). This class is the "primary" singleton cluster used amongst
1291
 * all forwarding threads/workers. Individual HostSets are used on the workers themselves.
1292
 */
1293
class Cluster {
1294
public:
1295
47.4k
  virtual ~Cluster() = default;
1296
1297
  enum class InitializePhase { Primary, Secondary };
1298
1299
  /**
1300
   * @return a pointer to the cluster's health checker. If a health checker has not been installed,
1301
   *         returns nullptr.
1302
   */
1303
  virtual HealthChecker* healthChecker() PURE;
1304
1305
  /**
1306
   * @return the information about this upstream cluster.
1307
   */
1308
  virtual ClusterInfoConstSharedPtr info() const PURE;
1309
1310
  /**
1311
   * @return a pointer to the cluster's outlier detector. If an outlier detector has not been
1312
   *         installed, returns nullptr.
1313
   */
1314
  virtual Outlier::Detector* outlierDetector() PURE;
1315
  virtual const Outlier::Detector* outlierDetector() const PURE;
1316
1317
  /**
1318
   * Initialize the cluster. This will be called either immediately at creation or after all primary
1319
   * clusters have been initialized (determined via initializePhase()).
1320
   * @param callback supplies a callback that will be invoked after the cluster has undergone first
1321
   *        time initialization. E.g., for a dynamic DNS cluster the initialize callback will be
1322
   *        called when initial DNS resolution is complete.
1323
   */
1324
  virtual void initialize(std::function<void()> callback) PURE;
1325
1326
  /**
1327
   * @return the phase in which the cluster is initialized at boot. This mechanism is used such that
1328
   *         clusters that depend on other clusters can correctly initialize. (E.g., an EDS cluster
1329
   *         that depends on resolution of the EDS server itself).
1330
   */
1331
  virtual InitializePhase initializePhase() const PURE;
1332
1333
  /**
1334
   * @return the PrioritySet for the cluster.
1335
   */
1336
  virtual PrioritySet& prioritySet() PURE;
1337
1338
  /**
1339
   * @return the const PrioritySet for the cluster.
1340
   */
1341
  virtual const PrioritySet& prioritySet() const PURE;
1342
};
1343
1344
using ClusterSharedPtr = std::shared_ptr<Cluster>;
1345
using ClusterConstOptRef = absl::optional<std::reference_wrapper<const Cluster>>;
1346
1347
} // namespace Upstream
1348
} // namespace Envoy
1349
1350
// NOLINT(namespace-envoy)
1351
namespace fmt {
1352
1353
// fmt formatter class for Host
1354
template <> struct formatter<Envoy::Upstream::Host> : formatter<absl::string_view> {
1355
  template <typename FormatContext>
1356
0
  auto format(const Envoy::Upstream::Host& host, FormatContext& ctx) -> decltype(ctx.out()) {
1357
0
    absl::string_view out = !host.hostname().empty() ? host.hostname()
1358
0
                            : host.address()         ? host.address()->asStringView()
1359
0
                                                     : "<empty>";
1360
0
    return formatter<absl::string_view>().format(out, ctx);
1361
0
  }
1362
};
1363
1364
} // namespace fmt