| 1 |
// |
| 2 |
// Copyright 2015 gRPC authors. |
| 3 |
// |
| 4 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
// you may not use this file except in compliance with the License. |
| 6 |
// You may obtain a copy of the License at |
| 7 |
// |
| 8 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
// |
| 10 |
// Unless required by applicable law or agreed to in writing, software |
| 11 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
// See the License for the specific language governing permissions and |
| 14 |
// limitations under the License. |
| 15 |
// |
| 16 |
|
| 17 |
#ifndef GRPC_CORE_LIB_LOAD_BALANCING_LB_POLICY_H |
| 18 |
#define GRPC_CORE_LIB_LOAD_BALANCING_LB_POLICY_H |
| 19 |
|
| 20 |
#include <grpc/support/port_platform.h> |
| 21 |
|
| 22 |
#include <stddef.h> |
| 23 |
#include <stdint.h> |
| 24 |
|
| 25 |
#include <memory> |
| 26 |
#include <string> |
| 27 |
#include <utility> |
| 28 |
#include <vector> |
| 29 |
|
| 30 |
#include "absl/status/status.h" |
| 31 |
#include "absl/status/statusor.h" |
| 32 |
#include "absl/strings/string_view.h" |
| 33 |
#include "absl/types/optional.h" |
| 34 |
#include "absl/types/variant.h" |
| 35 |
|
| 36 |
#include <grpc/event_engine/event_engine.h> |
| 37 |
#include <grpc/impl/codegen/connectivity_state.h> |
| 38 |
|
| 39 |
#include "src/core/ext/filters/client_channel/lb_policy/backend_metric_data.h" |
| 40 |
#include "src/core/lib/channel/channel_args.h" |
| 41 |
#include "src/core/lib/debug/trace.h" |
| 42 |
#include "src/core/lib/gprpp/debug_location.h" |
| 43 |
#include "src/core/lib/gprpp/orphanable.h" |
| 44 |
#include "src/core/lib/gprpp/ref_counted.h" |
| 45 |
#include "src/core/lib/gprpp/ref_counted_ptr.h" |
| 46 |
#include "src/core/lib/gprpp/work_serializer.h" |
| 47 |
#include "src/core/lib/iomgr/iomgr_fwd.h" |
| 48 |
#include "src/core/lib/load_balancing/subchannel_interface.h" |
| 49 |
#include "src/core/lib/resolver/server_address.h" |
| 50 |
|
| 51 |
namespace grpc_core { |
| 52 |
|
| 53 |
extern DebugOnlyTraceFlag grpc_trace_lb_policy_refcount; |
| 54 |
|
| 55 |
/// Interface for load balancing policies. |
| 56 |
/// |
| 57 |
/// The following concepts are used here: |
| 58 |
/// |
| 59 |
/// Channel: An abstraction that manages connections to backend servers |
| 60 |
/// on behalf of a client application. The application creates a channel |
| 61 |
/// for a given server name and then sends calls (RPCs) on it, and the |
| 62 |
/// channel figures out which backend server to send each call to. A channel |
| 63 |
/// contains a resolver, a load balancing policy (or a tree of LB policies), |
| 64 |
/// and a set of one or more subchannels. |
| 65 |
/// |
| 66 |
/// Subchannel: A subchannel represents a connection to one backend server. |
| 67 |
/// The LB policy decides which subchannels to create, manages the |
| 68 |
/// connectivity state of those subchannels, and decides which subchannel |
| 69 |
/// to send any given call to. |
| 70 |
/// |
| 71 |
/// Resolver: A plugin that takes a gRPC server URI and resolves it to a |
| 72 |
/// list of one or more addresses and a service config, as described |
| 73 |
/// in https://github.com/grpc/grpc/blob/master/doc/naming.md. See |
| 74 |
/// resolver.h for the resolver API. |
| 75 |
/// |
| 76 |
/// Load Balancing (LB) Policy: A plugin that takes a list of addresses |
| 77 |
/// from the resolver, maintains and manages a subchannel for each |
| 78 |
/// backend address, and decides which subchannel to send each call on. |
| 79 |
/// An LB policy has two parts: |
| 80 |
/// - A LoadBalancingPolicy, which deals with the control plane work of |
| 81 |
/// managing subchannels. |
| 82 |
/// - A SubchannelPicker, which handles the data plane work of |
| 83 |
/// determining which subchannel a given call should be sent on. |
| 84 |
|
| 85 |
/// LoadBalacingPolicy API. |
| 86 |
/// |
| 87 |
/// Note: All methods with a "Locked" suffix must be called from the |
| 88 |
/// work_serializer passed to the constructor. |
| 89 |
/// |
| 90 |
/// Any I/O done by the LB policy should be done under the pollset_set |
| 91 |
/// returned by \a interested_parties(). |
| 92 |
// TODO(roth): Once we move to EventManager-based polling, remove the |
| 93 |
// interested_parties() hooks from the API. |
| 94 |
class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> { |
| 95 |
public: |
| 96 |
/// Interface for accessing per-call state. |
| 97 |
/// Implemented by the client channel and used by the SubchannelPicker. |
| 98 |
class CallState { |
| 99 |
public: |
| 100 |
CallState() = default; |
| 101 |
virtual ~CallState() = default; |
| 102 |
|
| 103 |
/// Allocates memory associated with the call, which will be |
| 104 |
/// automatically freed when the call is complete. |
| 105 |
/// It is more efficient to use this than to allocate memory directly |
| 106 |
/// for allocations that need to be made on a per-call basis. |
| 107 |
virtual void* Alloc(size_t size) = 0; |
| 108 |
}; |
| 109 |
|
| 110 |
/// Interface for accessing metadata. |
| 111 |
/// Implemented by the client channel and used by the SubchannelPicker. |
| 112 |
class MetadataInterface { |
| 113 |
public: |
| 114 |
virtual ~MetadataInterface() = default; |
| 115 |
|
| 116 |
////////////////////////////////////////////////////////////////////////// |
| 117 |
// TODO(ctiller): DO NOT MAKE THIS A PUBLIC API YET |
| 118 |
// This needs some API design to ensure we can add/remove/replace metadata |
| 119 |
// keys... we're deliberately not doing so to save some time whilst |
| 120 |
// cleaning up the internal metadata representation, but we should add |
| 121 |
// something back before making this a public API. |
| 122 |
////////////////////////////////////////////////////////////////////////// |
| 123 |
|
| 124 |
/// Adds a key/value pair. |
| 125 |
/// Does NOT take ownership of \a key or \a value. |
| 126 |
/// Implementations must ensure that the key and value remain alive |
| 127 |
/// until the call ends. If desired, they may be allocated via |
| 128 |
/// CallState::Alloc(). |
| 129 |
virtual void Add(absl::string_view key, absl::string_view value) = 0; |
| 130 |
|
| 131 |
/// Produce a vector of metadata key/value strings for tests. |
| 132 |
virtual std::vector<std::pair<std::string, std::string>> |
| 133 |
TestOnlyCopyToVector() = 0; |
| 134 |
|
| 135 |
virtual absl::optional<absl::string_view> Lookup( |
| 136 |
absl::string_view key, std::string* buffer) const = 0; |
| 137 |
}; |
| 138 |
|
| 139 |
/// Arguments used when picking a subchannel for a call. |
| 140 |
struct PickArgs { |
| 141 |
/// The path of the call. Indicates the RPC service and method name. |
| 142 |
absl::string_view path; |
| 143 |
/// Initial metadata associated with the picking call. |
| 144 |
/// The LB policy may use the existing metadata to influence its routing |
| 145 |
/// decision, and it may add new metadata elements to be sent with the |
| 146 |
/// call to the chosen backend. |
| 147 |
MetadataInterface* initial_metadata; |
| 148 |
/// An interface for accessing call state. Can be used to allocate |
| 149 |
/// memory associated with the call in an efficient way. |
| 150 |
CallState* call_state; |
| 151 |
}; |
| 152 |
|
| 153 |
/// Interface for accessing backend metric data. |
| 154 |
/// Implemented by the client channel and used by |
| 155 |
/// SubchannelCallTrackerInterface. |
| 156 |
class BackendMetricAccessor { |
| 157 |
public: |
| 158 |
virtual ~BackendMetricAccessor() = default; |
| 159 |
|
| 160 |
/// Returns the backend metric data returned by the server for the call, |
| 161 |
/// or null if no backend metric data was returned. |
| 162 |
virtual const BackendMetricData* GetBackendMetricData() = 0; |
| 163 |
}; |
| 164 |
|
| 165 |
/// Interface for tracking subchannel calls. |
| 166 |
/// Implemented by LB policy and used by the channel. |
| 167 |
class SubchannelCallTrackerInterface { |
| 168 |
public: |
| 169 |
virtual ~SubchannelCallTrackerInterface() = default; |
| 170 |
|
| 171 |
/// Called when a subchannel call is started after an LB pick. |
| 172 |
virtual void Start() = 0; |
| 173 |
|
| 174 |
/// Called when a subchannel call is completed. |
| 175 |
/// The metadata may be modified by the implementation. However, the |
| 176 |
/// implementation does not take ownership, so any data that needs to be |
| 177 |
/// used after returning must be copied. |
| 178 |
struct FinishArgs { |
| 179 |
absl::Status status; |
| 180 |
MetadataInterface* trailing_metadata; |
| 181 |
BackendMetricAccessor* backend_metric_accessor; |
| 182 |
}; |
| 183 |
virtual void Finish(FinishArgs args) = 0; |
| 184 |
}; |
| 185 |
|
| 186 |
/// The result of picking a subchannel for a call. |
| 187 |
struct PickResult { |
| 188 |
/// A successful pick. |
| 189 |
struct Complete { |
| 190 |
/// The subchannel to be used for the call. Must be non-null. |
| 191 |
RefCountedPtr<SubchannelInterface> subchannel; |
| 192 |
|
| 193 |
/// Optionally set by the LB policy when it wishes to be notified |
| 194 |
/// about the resulting subchannel call. |
| 195 |
/// Note that if the pick is abandoned by the channel, this may never |
| 196 |
/// be used. |
| 197 |
std::unique_ptr<SubchannelCallTrackerInterface> subchannel_call_tracker; |
| 198 |
|
| 199 |
explicit Complete( |
| 200 |
RefCountedPtr<SubchannelInterface> sc, |
| 201 |
std::unique_ptr<SubchannelCallTrackerInterface> tracker = nullptr) |
| 202 |
: subchannel(std::move(sc)), |
| 203 |
subchannel_call_tracker(std::move(tracker)) {} |
| 204 |
}; |
| 205 |
|
| 206 |
/// Pick cannot be completed until something changes on the control |
| 207 |
/// plane. The client channel will queue the pick and try again the |
| 208 |
/// next time the picker is updated. |
| 209 |
struct Queue {}; |
| 210 |
|
| 211 |
/// Pick failed. If the call is wait_for_ready, the client channel |
| 212 |
/// will wait for the next picker and try again; otherwise, it |
| 213 |
/// will immediately fail the call with the status indicated (although |
| 214 |
/// the call may be retried if the client channel is configured to do so). |
| 215 |
struct Fail { |
| 216 |
absl::Status status; |
| 217 |
|
| 218 |
explicit Fail(absl::Status s) : status(s) {} |
| 219 |
}; |
| 220 |
|
| 221 |
/// Pick will be dropped with the status specified. |
| 222 |
/// Unlike FailPick, the call will be dropped even if it is |
| 223 |
/// wait_for_ready, and retries (if configured) will be inhibited. |
| 224 |
struct Drop { |
| 225 |
absl::Status status; |
| 226 |
|
| 227 |
explicit Drop(absl::Status s) : status(s) {} |
| 228 |
}; |
| 229 |
|
| 230 |
// A pick result must be one of these types. |
| 231 |
// Default to Queue, just to allow default construction. |
| 232 |
absl::variant<Complete, Queue, Fail, Drop> result = Queue(); |
| 233 |
|
| 234 |
PickResult() = default; |
| 235 |
// NOLINTNEXTLINE(google-explicit-constructor) |
| 236 |
PickResult(Complete complete) : result(std::move(complete)) {} |
| 237 |
// NOLINTNEXTLINE(google-explicit-constructor) |
| 238 |
PickResult(Queue queue) : result(queue) {} |
| 239 |
// NOLINTNEXTLINE(google-explicit-constructor) |
| 240 |
PickResult(Fail fail) : result(std::move(fail)) {} |
| 241 |
// NOLINTNEXTLINE(google-explicit-constructor) |
| 242 |
PickResult(Drop drop) : result(std::move(drop)) {} |
| 243 |
}; |
| 244 |
|
| 245 |
/// A subchannel picker is the object used to pick the subchannel to |
| 246 |
/// use for a given call. This is implemented by the LB policy and |
| 247 |
/// used by the client channel to perform picks. |
| 248 |
/// |
| 249 |
/// Pickers are intended to encapsulate all of the state and logic |
| 250 |
/// needed on the data plane (i.e., to actually process picks for |
| 251 |
/// individual calls sent on the channel) while excluding all of the |
| 252 |
/// state and logic needed on the control plane (i.e., resolver |
| 253 |
/// updates, connectivity state notifications, etc); the latter should |
| 254 |
/// live in the LB policy object itself. |
| 255 |
/// |
| 256 |
/// Currently, pickers are always accessed from within the |
| 257 |
/// client_channel data plane mutex, so they do not have to be |
| 258 |
/// thread-safe. |
| 259 |
class SubchannelPicker { |
| 260 |
public: |
| 261 |
SubchannelPicker() = default; |
| 262 |
virtual ~SubchannelPicker() = default; |
| 263 |
|
| 264 |
virtual PickResult Pick(PickArgs args) = 0; |
| 265 |
}; |
| 266 |
|
| 267 |
/// A proxy object implemented by the client channel and used by the |
| 268 |
/// LB policy to communicate with the channel. |
| 269 |
// TODO(roth): Once insecure builds go away, add methods for accessing |
| 270 |
// channel creds. By default, that should strip off the call creds |
| 271 |
// attached to the channel creds, but there should also be a "use at |
| 272 |
// your own risk" option to get the channel creds without stripping |
| 273 |
// off the attached call creds. |
| 274 |
class ChannelControlHelper { |
| 275 |
public: |
| 276 |
ChannelControlHelper() = default; |
| 277 |
virtual ~ChannelControlHelper() = default; |
| 278 |
|
| 279 |
/// Creates a new subchannel with the specified channel args. |
| 280 |
virtual RefCountedPtr<SubchannelInterface> CreateSubchannel( |
| 281 |
ServerAddress address, const ChannelArgs& args) = 0; |
| 282 |
|
| 283 |
/// Sets the connectivity state and returns a new picker to be used |
| 284 |
/// by the client channel. |
| 285 |
virtual void UpdateState(grpc_connectivity_state state, |
| 286 |
const absl::Status& status, |
| 287 |
std::unique_ptr<SubchannelPicker>) = 0; |
| 288 |
|
| 289 |
/// Requests that the resolver re-resolve. |
| 290 |
virtual void RequestReresolution() = 0; |
| 291 |
|
| 292 |
/// Returns the channel authority. |
| 293 |
virtual absl::string_view GetAuthority() = 0; |
| 294 |
|
| 295 |
/// Returns the EventEngine to use for timers and async work. |
| 296 |
virtual grpc_event_engine::experimental::EventEngine* GetEventEngine() = 0; |
| 297 |
|
| 298 |
/// Adds a trace message associated with the channel. |
| 299 |
enum TraceSeverity { TRACE_INFO, TRACE_WARNING, TRACE_ERROR }; |
| 300 |
virtual void AddTraceEvent(TraceSeverity severity, |
| 301 |
absl::string_view message) = 0; |
| 302 |
}; |
| 303 |
|
| 304 |
/// Interface for configuration data used by an LB policy implementation. |
| 305 |
/// Individual implementations will create a subclass that adds methods to |
| 306 |
/// return the parameters they need. |
| 307 |
class Config : public RefCounted<Config> { |
| 308 |
public: |
| 309 |
~Config() override = default; |
| 310 |
|
| 311 |
// Returns the load balancing policy name |
| 312 |
virtual absl::string_view name() const = 0; |
| 313 |
}; |
| 314 |
|
| 315 |
/// Data passed to the UpdateLocked() method when new addresses and |
| 316 |
/// config are available. |
| 317 |
struct UpdateArgs { |
| 318 |
/// A list of addresses, or an error indicating a failure to obtain the |
| 319 |
/// list of addresses. |
| 320 |
absl::StatusOr<ServerAddressList> addresses; |
| 321 |
/// The LB policy config. |
| 322 |
RefCountedPtr<Config> config; |
| 323 |
/// A human-readable note providing context about the name resolution that |
| 324 |
/// provided this update. LB policies may wish to include this message |
| 325 |
/// in RPC failure status messages. For example, if the update has an |
| 326 |
/// empty list of addresses, this message might say "no DNS entries |
| 327 |
/// found for <name>". |
| 328 |
std::string resolution_note; |
| 329 |
|
| 330 |
// TODO(roth): Before making this a public API, find a better |
| 331 |
// abstraction for representing channel args. |
| 332 |
ChannelArgs args; |
| 333 |
}; |
| 334 |
|
| 335 |
/// Args used to instantiate an LB policy. |
| 336 |
struct Args { |
| 337 |
/// The work_serializer under which all LB policy calls will be run. |
| 338 |
std::shared_ptr<WorkSerializer> work_serializer; |
| 339 |
/// Channel control helper. |
| 340 |
/// Note: LB policies MUST NOT call any method on the helper from |
| 341 |
/// their constructor. |
| 342 |
std::unique_ptr<ChannelControlHelper> channel_control_helper; |
| 343 |
/// Channel args. |
| 344 |
// TODO(roth): Find a better channel args representation for this API. |
| 345 |
ChannelArgs args; |
| 346 |
}; |
| 347 |
|
| 348 |
explicit LoadBalancingPolicy(Args args, intptr_t initial_refcount = 1); |
| 349 |
~LoadBalancingPolicy() override; |
| 350 |
|
| 351 |
// Not copyable nor movable. |
| 352 |
LoadBalancingPolicy(const LoadBalancingPolicy&) = delete; |
| 353 |
LoadBalancingPolicy& operator=(const LoadBalancingPolicy&) = delete; |
| 354 |
|
| 355 |
/// Returns the name of the LB policy. |
| 356 |
virtual absl::string_view name() const = 0; |
| 357 |
|
| 358 |
/// Updates the policy with new data from the resolver. Will be invoked |
| 359 |
/// immediately after LB policy is constructed, and then again whenever |
| 360 |
/// the resolver returns a new result. The returned status indicates |
| 361 |
/// whether the LB policy accepted the update; if non-OK, informs |
| 362 |
/// polling-based resolvers that they should go into backoff delay and |
| 363 |
/// eventually reattempt the resolution. |
| 364 |
virtual absl::Status UpdateLocked(UpdateArgs) = 0; // NOLINT |
| 365 |
|
| 366 |
/// Tries to enter a READY connectivity state. |
| 367 |
/// This is a no-op by default, since most LB policies never go into |
| 368 |
/// IDLE state. |
| 369 |
virtual void ExitIdleLocked() {} |
| 370 |
|
| 371 |
/// Resets connection backoff. |
| 372 |
virtual void ResetBackoffLocked() = 0; |
| 373 |
|
| 374 |
grpc_pollset_set* interested_parties() const { return interested_parties_; } |
| 375 |
|
| 376 |
// Note: This must be invoked while holding the work_serializer. |
| 377 |
void Orphan() override; |
| 378 |
|
| 379 |
// A picker that returns PickResult::Queue for all picks. |
| 380 |
// Also calls the parent LB policy's ExitIdleLocked() method when the |
| 381 |
// first pick is seen. |
| 382 |
class QueuePicker : public SubchannelPicker { |
| 383 |
public: |
| 384 |
explicit QueuePicker(RefCountedPtr<LoadBalancingPolicy> parent) |
| 385 |
: parent_(std::move(parent)) {} |
| 386 |
|
| 387 |
~QueuePicker() override { parent_.reset(DEBUG_LOCATION, "QueuePicker"); } |
| 388 |
|
| 389 |
PickResult Pick(PickArgs args) override; |
| 390 |
|
| 391 |
private: |
| 392 |
RefCountedPtr<LoadBalancingPolicy> parent_; |
| 393 |
bool exit_idle_called_ = false; |
| 394 |
}; |
| 395 |
|
| 396 |
// A picker that returns PickResult::Fail for all picks. |
| 397 |
class TransientFailurePicker : public SubchannelPicker { |
| 398 |
public: |
| 399 |
explicit TransientFailurePicker(absl::Status status) : status_(status) {} |
| 400 |
|
| 401 |
PickResult Pick(PickArgs /*args*/) override { |
| 402 |
return PickResult::Fail(status_); |
| 403 |
} |
| 404 |
|
| 405 |
private: |
| 406 |
absl::Status status_; |
| 407 |
}; |
| 408 |
|
| 409 |
protected: |
| 410 |
std::shared_ptr<WorkSerializer> work_serializer() const { |
| 411 |
return work_serializer_; |
| 412 |
} |
| 413 |
|
| 414 |
const ChannelArgs& channel_args() const { return channel_args_; } |
| 415 |
|
| 416 |
// Note: LB policies MUST NOT call any method on the helper from their |
| 417 |
// constructor. |
| 418 |
ChannelControlHelper* channel_control_helper() const { |
| 419 |
return channel_control_helper_.get(); |
| 420 |
} |
| 421 |
|
| 422 |
/// Shuts down the policy. |
| 423 |
virtual void ShutdownLocked() = 0; |
| 424 |
|
| 425 |
private: |
| 426 |
/// Work Serializer under which LB policy actions take place. |
| 427 |
std::shared_ptr<WorkSerializer> work_serializer_; |
| 428 |
/// Owned pointer to interested parties in load balancing decisions. |
| 429 |
grpc_pollset_set* interested_parties_; |
| 430 |
/// Channel control helper. |
| 431 |
std::unique_ptr<ChannelControlHelper> channel_control_helper_; |
| 432 |
/// Channel args passed in. |
| 433 |
// TODO(roth): Rework Args so that we don't need to capture channel args here. |
| 434 |
ChannelArgs channel_args_; |
| 435 |
}; |
| 436 |
|
| 437 |
} // namespace grpc_core |
| 438 |
|
| 439 |
#endif // GRPC_CORE_LIB_LOAD_BALANCING_LB_POLICY_H |