Built motion from commit 6a09e18b.|2.6.11
[motion2.git] / legacy-libs / grpc-cloned / deps / grpc / src / core / ext / filters / client_channel / lb_policy.h
1 /*
2  *
3  * Copyright 2015 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18
19 #ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_H
20 #define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_H
21
22 #include <grpc/support/port_platform.h>
23
24 #include "src/core/ext/filters/client_channel/server_address.h"
25 #include "src/core/ext/filters/client_channel/service_config.h"
26 #include "src/core/ext/filters/client_channel/subchannel_interface.h"
27 #include "src/core/lib/gprpp/abstract.h"
28 #include "src/core/lib/gprpp/map.h"
29 #include "src/core/lib/gprpp/orphanable.h"
30 #include "src/core/lib/gprpp/ref_counted_ptr.h"
31 #include "src/core/lib/gprpp/string_view.h"
32 #include "src/core/lib/iomgr/combiner.h"
33 #include "src/core/lib/iomgr/polling_entity.h"
34 #include "src/core/lib/transport/connectivity_state.h"
35
36 namespace grpc_core {
37
38 extern DebugOnlyTraceFlag grpc_trace_lb_policy_refcount;
39
40 /// Interface for load balancing policies.
41 ///
42 /// The following concepts are used here:
43 ///
44 /// Channel: An abstraction that manages connections to backend servers
45 ///   on behalf of a client application.  The application creates a channel
46 ///   for a given server name and then sends calls (RPCs) on it, and the
47 ///   channel figures out which backend server to send each call to.  A channel
48 ///   contains a resolver, a load balancing policy (or a tree of LB policies),
49 ///   and a set of one or more subchannels.
50 ///
51 /// Subchannel: A subchannel represents a connection to one backend server.
52 ///   The LB policy decides which subchannels to create, manages the
53 ///   connectivity state of those subchannels, and decides which subchannel
54 ///   to send any given call to.
55 ///
56 /// Resolver: A plugin that takes a gRPC server URI and resolves it to a
57 ///   list of one or more addresses and a service config, as described
58 ///   in https://github.com/grpc/grpc/blob/master/doc/naming.md.  See
59 ///   resolver.h for the resolver API.
60 ///
61 /// Load Balancing (LB) Policy: A plugin that takes a list of addresses
62 ///   from the resolver, maintains and manages a subchannel for each
63 ///   backend address, and decides which subchannel to send each call on.
64 ///   An LB policy has two parts:
65 ///   - A LoadBalancingPolicy, which deals with the control plane work of
66 ///     managing subchannels.
67 ///   - A SubchannelPicker, which handles the data plane work of
68 ///     determining which subchannel a given call should be sent on.
69
70 /// LoadBalacingPolicy API.
71 ///
72 /// Note: All methods with a "Locked" suffix must be called from the
73 /// combiner passed to the constructor.
74 ///
75 /// Any I/O done by the LB policy should be done under the pollset_set
76 /// returned by \a interested_parties().
77 // TODO(roth): Once we move to EventManager-based polling, remove the
78 // interested_parties() hooks from the API.
79 class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> {
80  public:
81   // Represents backend metrics reported by the backend to the client.
82   struct BackendMetricData {
83     /// CPU utilization expressed as a fraction of available CPU resources.
84     double cpu_utilization;
85     /// Memory utilization expressed as a fraction of available memory
86     /// resources.
87     double mem_utilization;
88     /// Total requests per second being served by the backend.  This
89     /// should include all services that a backend is responsible for.
90     uint64_t requests_per_second;
91     /// Application-specific requests cost metrics.  Metric names are
92     /// determined by the application.  Each value is an absolute cost
93     /// (e.g. 3487 bytes of storage) associated with the request.
94     Map<StringView, double, StringLess> request_cost;
95     /// Application-specific resource utilization metrics.  Metric names
96     /// are determined by the application.  Each value is expressed as a
97     /// fraction of total resources available.
98     Map<StringView, double, StringLess> utilization;
99   };
100
101   /// Interface for accessing per-call state.
102   /// Implemented by the client channel and used by the SubchannelPicker.
103   class CallState {
104    public:
105     CallState() = default;
106     virtual ~CallState() = default;
107
108     /// Allocates memory associated with the call, which will be
109     /// automatically freed when the call is complete.
110     /// It is more efficient to use this than to allocate memory directly
111     /// for allocations that need to be made on a per-call basis.
112     virtual void* Alloc(size_t size) GRPC_ABSTRACT;
113
114     /// Returns the backend metric data returned by the server for the call,
115     /// or null if no backend metric data was returned.
116     virtual const BackendMetricData* GetBackendMetricData() GRPC_ABSTRACT;
117
118     GRPC_ABSTRACT_BASE_CLASS
119   };
120
121   /// Interface for accessing metadata.
122   /// Implemented by the client channel and used by the SubchannelPicker.
123   class MetadataInterface {
124    public:
125     // Implementations whose iterators fit in intptr_t may internally
126     // cast this directly to their iterator type.  Otherwise, they may
127     // dynamically allocate their iterators and store the address here.
128     typedef intptr_t Iterator;
129
130     virtual ~MetadataInterface() = default;
131
132     /// Adds a key/value pair.
133     /// Does NOT take ownership of \a key or \a value.
134     /// Implementations must ensure that the key and value remain alive
135     /// until the call ends.  If desired, they may be allocated via
136     /// CallState::Alloc().
137     virtual void Add(StringView key, StringView value) GRPC_ABSTRACT;
138
139     /// Iteration interface.
140     virtual Iterator Begin() const GRPC_ABSTRACT;
141     virtual bool IsEnd(Iterator it) const GRPC_ABSTRACT;
142     virtual void Next(Iterator* it) const GRPC_ABSTRACT;
143     virtual StringView Key(Iterator it) const GRPC_ABSTRACT;
144     virtual StringView Value(Iterator it) const GRPC_ABSTRACT;
145
146     /// Removes the element pointed to by \a it, which is modified to
147     /// point to the next element.
148     virtual void Erase(Iterator* it) GRPC_ABSTRACT;
149
150     GRPC_ABSTRACT_BASE_CLASS
151   };
152
153   /// Arguments used when picking a subchannel for a call.
154   struct PickArgs {
155     /// Initial metadata associated with the picking call.
156     /// The LB policy may use the existing metadata to influence its routing
157     /// decision, and it may add new metadata elements to be sent with the
158     /// call to the chosen backend.
159     MetadataInterface* initial_metadata;
160     /// An interface for accessing call state.  Can be used to allocate
161     /// data associated with the call in an efficient way.
162     CallState* call_state;
163   };
164
165   /// The result of picking a subchannel for a call.
166   struct PickResult {
167     enum ResultType {
168       /// Pick complete.  If \a subchannel is non-null, the client channel
169       /// will immediately proceed with the call on that subchannel;
170       /// otherwise, it will drop the call.
171       PICK_COMPLETE,
172       /// Pick cannot be completed until something changes on the control
173       /// plane.  The client channel will queue the pick and try again the
174       /// next time the picker is updated.
175       PICK_QUEUE,
176       /// Pick failed.  If the call is wait_for_ready, the client channel
177       /// will wait for the next picker and try again; otherwise, it
178       /// will immediately fail the call with the status indicated via
179       /// \a error (although the call may be retried if the client channel
180       /// is configured to do so).
181       PICK_FAILED,
182     };
183     ResultType type;
184
185     /// Used only if type is PICK_COMPLETE.  Will be set to the selected
186     /// subchannel, or nullptr if the LB policy decides to drop the call.
187     RefCountedPtr<SubchannelInterface> subchannel;
188
189     /// Used only if type is PICK_FAILED.
190     /// Error to be set when returning a failure.
191     // TODO(roth): Replace this with something similar to grpc::Status,
192     // so that we don't expose grpc_error to this API.
193     grpc_error* error = GRPC_ERROR_NONE;
194
195     /// Used only if type is PICK_COMPLETE.
196     /// Callback set by LB policy to be notified of trailing metadata.
197     /// The user_data argument will be set to the
198     /// recv_trailing_metadata_ready_user_data field.
199     /// recv_trailing_metadata will be set to the metadata, which may be
200     /// modified by the callback.  The callback does not take ownership,
201     /// however, so any data that needs to be used after returning must
202     /// be copied.
203     /// call_state can be used to obtain backend metric data.
204     // TODO(roth): Replace grpc_error with something better before we allow
205     // people outside of gRPC team to use this API.
206     void (*recv_trailing_metadata_ready)(
207         void* user_data, grpc_error* error,
208         MetadataInterface* recv_trailing_metadata,
209         CallState* call_state) = nullptr;
210     void* recv_trailing_metadata_ready_user_data = nullptr;
211   };
212
213   /// A subchannel picker is the object used to pick the subchannel to
214   /// use for a given call.  This is implemented by the LB policy and
215   /// used by the client channel to perform picks.
216   ///
217   /// Pickers are intended to encapsulate all of the state and logic
218   /// needed on the data plane (i.e., to actually process picks for
219   /// individual calls sent on the channel) while excluding all of the
220   /// state and logic needed on the control plane (i.e., resolver
221   /// updates, connectivity state notifications, etc); the latter should
222   /// live in the LB policy object itself.
223   ///
224   /// Currently, pickers are always accessed from within the
225   /// client_channel data plane combiner, so they do not have to be
226   /// thread-safe.
227   class SubchannelPicker {
228    public:
229     SubchannelPicker() = default;
230     virtual ~SubchannelPicker() = default;
231
232     virtual PickResult Pick(PickArgs args) GRPC_ABSTRACT;
233
234     GRPC_ABSTRACT_BASE_CLASS
235   };
236
237   /// A proxy object implemented by the client channel and used by the
238   /// LB policy to communicate with the channel.
239   // TODO(juanlishen): Consider adding a mid-layer subclass that helps handle
240   // things like swapping in pending policy when it's ready. Currently, we are
241   // duplicating the logic in many subclasses.
242   class ChannelControlHelper {
243    public:
244     ChannelControlHelper() = default;
245     virtual ~ChannelControlHelper() = default;
246
247     /// Creates a new subchannel with the specified channel args.
248     virtual RefCountedPtr<SubchannelInterface> CreateSubchannel(
249         const grpc_channel_args& args) GRPC_ABSTRACT;
250
251     /// Sets the connectivity state and returns a new picker to be used
252     /// by the client channel.
253     virtual void UpdateState(grpc_connectivity_state state,
254                              UniquePtr<SubchannelPicker>) GRPC_ABSTRACT;
255
256     /// Requests that the resolver re-resolve.
257     virtual void RequestReresolution() GRPC_ABSTRACT;
258
259     /// Adds a trace message associated with the channel.
260     enum TraceSeverity { TRACE_INFO, TRACE_WARNING, TRACE_ERROR };
261     virtual void AddTraceEvent(TraceSeverity severity,
262                                StringView message) GRPC_ABSTRACT;
263
264     GRPC_ABSTRACT_BASE_CLASS
265   };
266
267   /// Interface for configuration data used by an LB policy implementation.
268   /// Individual implementations will create a subclass that adds methods to
269   /// return the parameters they need.
270   class Config : public RefCounted<Config> {
271    public:
272     virtual ~Config() = default;
273
274     // Returns the load balancing policy name
275     virtual const char* name() const GRPC_ABSTRACT;
276
277     GRPC_ABSTRACT_BASE_CLASS
278   };
279
280   /// Data passed to the UpdateLocked() method when new addresses and
281   /// config are available.
282   struct UpdateArgs {
283     ServerAddressList addresses;
284     RefCountedPtr<Config> config;
285     const grpc_channel_args* args = nullptr;
286
287     // TODO(roth): Remove everything below once channel args is
288     // converted to a copyable and movable C++ object.
289     UpdateArgs() = default;
290     ~UpdateArgs() { grpc_channel_args_destroy(args); }
291     UpdateArgs(const UpdateArgs& other);
292     UpdateArgs(UpdateArgs&& other);
293     UpdateArgs& operator=(const UpdateArgs& other);
294     UpdateArgs& operator=(UpdateArgs&& other);
295   };
296
297   /// Args used to instantiate an LB policy.
298   struct Args {
299     /// The combiner under which all LB policy calls will be run.
300     /// Policy does NOT take ownership of the reference to the combiner.
301     // TODO(roth): Once we have a C++-like interface for combiners, this
302     // API should change to take a smart pointer that does pass ownership
303     // of a reference.
304     grpc_combiner* combiner = nullptr;
305     /// Channel control helper.
306     /// Note: LB policies MUST NOT call any method on the helper from
307     /// their constructor.
308     UniquePtr<ChannelControlHelper> channel_control_helper;
309     /// Channel args.
310     // TODO(roth): Find a better channel args representation for this API.
311     const grpc_channel_args* args = nullptr;
312   };
313
314   explicit LoadBalancingPolicy(Args args, intptr_t initial_refcount = 1);
315   virtual ~LoadBalancingPolicy();
316
317   // Not copyable nor movable.
318   LoadBalancingPolicy(const LoadBalancingPolicy&) = delete;
319   LoadBalancingPolicy& operator=(const LoadBalancingPolicy&) = delete;
320
321   /// Returns the name of the LB policy.
322   virtual const char* name() const GRPC_ABSTRACT;
323
324   /// Updates the policy with new data from the resolver.  Will be invoked
325   /// immediately after LB policy is constructed, and then again whenever
326   /// the resolver returns a new result.
327   virtual void UpdateLocked(UpdateArgs) GRPC_ABSTRACT;  // NOLINT
328
329   /// Tries to enter a READY connectivity state.
330   /// This is a no-op by default, since most LB policies never go into
331   /// IDLE state.
332   virtual void ExitIdleLocked() {}
333
334   /// Resets connection backoff.
335   virtual void ResetBackoffLocked() GRPC_ABSTRACT;
336
337   grpc_pollset_set* interested_parties() const { return interested_parties_; }
338
339   // Note: This must be invoked while holding the combiner.
340   void Orphan() override;
341
342   // A picker that returns PICK_QUEUE for all picks.
343   // Also calls the parent LB policy's ExitIdleLocked() method when the
344   // first pick is seen.
345   class QueuePicker : public SubchannelPicker {
346    public:
347     explicit QueuePicker(RefCountedPtr<LoadBalancingPolicy> parent)
348         : parent_(std::move(parent)) {}
349
350     ~QueuePicker() { parent_.reset(DEBUG_LOCATION, "QueuePicker"); }
351
352     PickResult Pick(PickArgs args) override;
353
354    private:
355     static void CallExitIdle(void* arg, grpc_error* error);
356
357     RefCountedPtr<LoadBalancingPolicy> parent_;
358     bool exit_idle_called_ = false;
359   };
360
361   // A picker that returns PICK_TRANSIENT_FAILURE for all picks.
362   class TransientFailurePicker : public SubchannelPicker {
363    public:
364     explicit TransientFailurePicker(grpc_error* error) : error_(error) {}
365     ~TransientFailurePicker() override { GRPC_ERROR_UNREF(error_); }
366
367     PickResult Pick(PickArgs args) override;
368
369    private:
370     grpc_error* error_;
371   };
372
373   GRPC_ABSTRACT_BASE_CLASS
374
375  protected:
376   grpc_combiner* combiner() const { return combiner_; }
377
378   // Note: LB policies MUST NOT call any method on the helper from their
379   // constructor.
380   ChannelControlHelper* channel_control_helper() const {
381     return channel_control_helper_.get();
382   }
383
384   /// Shuts down the policy.
385   virtual void ShutdownLocked() GRPC_ABSTRACT;
386
387  private:
388   /// Combiner under which LB policy actions take place.
389   grpc_combiner* combiner_;
390   /// Owned pointer to interested parties in load balancing decisions.
391   grpc_pollset_set* interested_parties_;
392   /// Channel control helper.
393   UniquePtr<ChannelControlHelper> channel_control_helper_;
394 };
395
396 }  // namespace grpc_core
397
398 #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_H */