blob: 01d05dbb14c2ee034940daa20424b0f123e3cc40 [file] [log] [blame]
David Garcia Quintas3fb8f732016-06-15 22:53:08 -07001/*
2 *
Jan Tattermusch7897ae92017-06-07 22:57:36 +02003 * Copyright 2016 gRPC authors.
David Garcia Quintas3fb8f732016-06-15 22:53:08 -07004 *
Jan Tattermusch7897ae92017-06-07 22:57:36 +02005 * 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
David Garcia Quintas3fb8f732016-06-15 22:53:08 -07008 *
Jan Tattermusch7897ae92017-06-07 22:57:36 +02009 * http://www.apache.org/licenses/LICENSE-2.0
David Garcia Quintas3fb8f732016-06-15 22:53:08 -070010 *
Jan Tattermusch7897ae92017-06-07 22:57:36 +020011 * 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.
David Garcia Quintas3fb8f732016-06-15 22:53:08 -070016 *
17 */
18
Mark D. Rothc8875492018-02-20 08:33:48 -080019/// Implementation of the gRPC LB policy.
20///
21/// This policy takes as input a list of resolved addresses, which must
22/// include at least one balancer address.
23///
24/// An internal channel (\a lb_channel_) is created for the addresses
25/// from that are balancers. This channel behaves just like a regular
26/// channel that uses pick_first to select from the list of balancer
27/// addresses.
28///
29/// The first time the policy gets a request for a pick, a ping, or to exit
30/// the idle state, \a StartPickingLocked() is called. This method is
31/// responsible for instantiating the internal *streaming* call to the LB
32/// server (whichever address pick_first chose). The call will be complete
33/// when either the balancer sends status or when we cancel the call (e.g.,
34/// because we are shutting down). In needed, we retry the call. If we
35/// received at least one valid message from the server, a new call attempt
36/// will be made immediately; otherwise, we apply back-off delays between
37/// attempts.
38///
39/// We maintain an internal round_robin policy instance for distributing
40/// requests across backends. Whenever we receive a new serverlist from
41/// the balancer, we update the round_robin policy with the new list of
42/// addresses. If we cannot communicate with the balancer on startup,
43/// however, we may enter fallback mode, in which case we will populate
44/// the RR policy's addresses from the backend addresses returned by the
45/// resolver.
46///
47/// Once an RR policy instance is in place (and getting updated as described),
48/// calls for a pick, a ping, or a cancellation will be serviced right
49/// away by forwarding them to the RR instance. Any time there's no RR
50/// policy available (i.e., right after the creation of the gRPCLB policy),
51/// pick and ping requests are added to a list of pending picks and pings
52/// to be flushed and serviced when the RR policy instance becomes available.
53///
54/// \see https://github.com/grpc/grpc/blob/master/doc/load-balancing.md for the
55/// high level design and details.
David Garcia Quintas8b3b97f2016-07-15 07:46:47 -070056
Mark D. Rothc8875492018-02-20 08:33:48 -080057// With the addition of a libuv endpoint, sockaddr.h now includes uv.h when
58// using that endpoint. Because of various transitive includes in uv.h,
59// including windows.h on Windows, uv.h must be included before other system
60// headers. Therefore, sockaddr.h must always be included first.
Alexander Polcyndb3e8982018-02-21 16:59:24 -080061#include <grpc/support/port_platform.h>
62
murgatroid997871f732016-09-23 13:49:05 -070063#include "src/core/lib/iomgr/sockaddr.h"
kpayson64539f5062018-03-12 19:16:30 -070064#include "src/core/lib/iomgr/socket_utils.h"
murgatroid997871f732016-09-23 13:49:05 -070065
Yash Tibrewalfcd26bc2017-09-25 15:08:28 -070066#include <inttypes.h>
Mark D. Roth64d922a2017-05-03 12:52:04 -070067#include <limits.h>
David Garcia Quintas22e8f1d2016-06-15 23:53:00 -070068#include <string.h>
69
70#include <grpc/byte_buffer_reader.h>
71#include <grpc/grpc.h>
72#include <grpc/support/alloc.h>
David Garcia Quintas22e8f1d2016-06-15 23:53:00 -070073#include <grpc/support/string_util.h>
David Garcia Quintas69099222016-10-03 11:28:37 -070074#include <grpc/support/time.h>
David Garcia Quintas22e8f1d2016-06-15 23:53:00 -070075
Craig Tiller9eb0fde2017-03-31 16:59:30 -070076#include "src/core/ext/filters/client_channel/client_channel.h"
77#include "src/core/ext/filters/client_channel/client_channel_factory.h"
Mark D. Roth09e458c2017-05-02 08:13:26 -070078#include "src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.h"
Yihua Zhang392dad72018-05-03 20:12:20 -070079#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h"
Craig Tiller9eb0fde2017-03-31 16:59:30 -070080#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h"
Mark D. Roth09e458c2017-05-02 08:13:26 -070081#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h"
Craig Tiller9eb0fde2017-03-31 16:59:30 -070082#include "src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.h"
Craig Tillerd52e22f2017-04-02 16:22:52 -070083#include "src/core/ext/filters/client_channel/lb_policy_factory.h"
84#include "src/core/ext/filters/client_channel/lb_policy_registry.h"
85#include "src/core/ext/filters/client_channel/parse_address.h"
David Garcia Quintas87d5a312017-06-06 19:45:58 -070086#include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
Juanli Shen6502ecc2017-09-13 13:10:54 -070087#include "src/core/ext/filters/client_channel/subchannel_index.h"
Craig Tillerc0df1c02017-07-17 16:12:33 -070088#include "src/core/lib/backoff/backoff.h"
Mark D. Roth046cf762016-09-26 11:13:51 -070089#include "src/core/lib/channel/channel_args.h"
Mark D. Roth09e458c2017-05-02 08:13:26 -070090#include "src/core/lib/channel/channel_stack.h"
Vijay Paiae376bf2018-01-25 22:54:02 -080091#include "src/core/lib/gpr/host_port.h"
Mark D. Rothdbdf4952018-01-18 11:21:12 -080092#include "src/core/lib/gpr/string.h"
Mark D. Roth4f2b0fd2018-01-19 12:12:23 -080093#include "src/core/lib/gprpp/manual_constructor.h"
Mark D. Rothc8875492018-02-20 08:33:48 -080094#include "src/core/lib/gprpp/memory.h"
95#include "src/core/lib/gprpp/orphanable.h"
Mark D. Roth209f6442018-02-08 10:26:46 -080096#include "src/core/lib/gprpp/ref_counted_ptr.h"
Craig Tiller2400bf52017-02-09 16:25:19 -080097#include "src/core/lib/iomgr/combiner.h"
David Garcia Quintas98da61b2016-10-29 08:46:31 +020098#include "src/core/lib/iomgr/sockaddr.h"
David Garcia Quintas3fb8f732016-06-15 22:53:08 -070099#include "src/core/lib/iomgr/sockaddr_utils.h"
David Garcia Quintas98da61b2016-10-29 08:46:31 +0200100#include "src/core/lib/iomgr/timer.h"
David Garcia Quintas01291502017-02-07 13:26:41 -0800101#include "src/core/lib/slice/slice_hash_table.h"
Craig Tiller18b4ba32016-11-09 15:23:42 -0800102#include "src/core/lib/slice/slice_internal.h"
Craig Tiller0f310802016-10-26 16:25:56 -0700103#include "src/core/lib/slice/slice_string_helpers.h"
David Garcia Quintas3fb8f732016-06-15 22:53:08 -0700104#include "src/core/lib/surface/call.h"
105#include "src/core/lib/surface/channel.h"
Mark D. Roth09e458c2017-05-02 08:13:26 -0700106#include "src/core/lib/surface/channel_init.h"
David Garcia Quintas331b9c02016-09-12 18:37:05 -0700107#include "src/core/lib/transport/static_metadata.h"
David Garcia Quintas3fb8f732016-06-15 22:53:08 -0700108
David Garcia Quintas1edfb952016-11-22 17:15:34 -0800109#define GRPC_GRPCLB_INITIAL_CONNECT_BACKOFF_SECONDS 1
110#define GRPC_GRPCLB_RECONNECT_BACKOFF_MULTIPLIER 1.6
111#define GRPC_GRPCLB_RECONNECT_MAX_BACKOFF_SECONDS 120
112#define GRPC_GRPCLB_RECONNECT_JITTER 0.2
Juanli Shenfe408152017-09-27 12:27:20 -0700113#define GRPC_GRPCLB_DEFAULT_FALLBACK_TIMEOUT_MS 10000
David Garcia Quintas98da61b2016-10-29 08:46:31 +0200114
Mark D. Rothc8875492018-02-20 08:33:48 -0800115namespace grpc_core {
David Garcia Quintas3fb8f732016-06-15 22:53:08 -0700116
Mark D. Rothc8875492018-02-20 08:33:48 -0800117TraceFlag grpc_lb_glb_trace(false, "glb");
David Garcia Quintas3fb8f732016-06-15 22:53:08 -0700118
Vijay Pai849bd732018-01-02 23:30:47 +0000119namespace {
Mark D. Rothc0febd32018-01-09 10:25:24 -0800120
Mark D. Rothc8875492018-02-20 08:33:48 -0800121class GrpcLb : public LoadBalancingPolicy {
122 public:
123 GrpcLb(const grpc_lb_addresses* addresses, const Args& args);
124
125 void UpdateLocked(const grpc_channel_args& args) override;
126 bool PickLocked(PickState* pick) override;
127 void CancelPickLocked(PickState* pick, grpc_error* error) override;
128 void CancelMatchingPicksLocked(uint32_t initial_metadata_flags_mask,
129 uint32_t initial_metadata_flags_eq,
130 grpc_error* error) override;
131 void NotifyOnStateChangeLocked(grpc_connectivity_state* state,
132 grpc_closure* closure) override;
133 grpc_connectivity_state CheckConnectivityLocked(
134 grpc_error** connectivity_error) override;
135 void HandOffPendingPicksLocked(LoadBalancingPolicy* new_policy) override;
136 void PingOneLocked(grpc_closure* on_initiate, grpc_closure* on_ack) override;
137 void ExitIdleLocked() override;
138
139 private:
140 /// Linked list of pending pick requests. It stores all information needed to
141 /// eventually call (Round Robin's) pick() on them. They mainly stay pending
142 /// waiting for the RR policy to be created.
143 ///
144 /// Note that when a pick is sent to the RR policy, we inject our own
145 /// on_complete callback, so that we can intercept the result before
146 /// invoking the original on_complete callback. This allows us to set the
147 /// LB token metadata and add client_stats to the call context.
148 /// See \a pending_pick_complete() for details.
149 struct PendingPick {
150 // The grpclb instance that created the wrapping. This instance is not
151 // owned; reference counts are untouched. It's used only for logging
152 // purposes.
153 GrpcLb* grpclb_policy;
154 // The original pick.
155 PickState* pick;
156 // Our on_complete closure and the original one.
157 grpc_closure on_complete;
158 grpc_closure* original_on_complete;
159 // The LB token associated with the pick. This is set via user_data in
160 // the pick.
161 grpc_mdelem lb_token;
Mark D. Roth290d35e2018-05-17 14:15:36 -0700162 // Stats for client-side load reporting.
163 RefCountedPtr<GrpcLbClientStats> client_stats;
Mark D. Rothc8875492018-02-20 08:33:48 -0800164 // Next pending pick.
165 PendingPick* next = nullptr;
166 };
167
168 /// A linked list of pending pings waiting for the RR policy to be created.
169 struct PendingPing {
170 grpc_closure* on_initiate;
171 grpc_closure* on_ack;
172 PendingPing* next = nullptr;
173 };
174
175 /// Contains a call to the LB server and all the data related to the call.
176 class BalancerCallState
177 : public InternallyRefCountedWithTracing<BalancerCallState> {
178 public:
179 explicit BalancerCallState(
180 RefCountedPtr<LoadBalancingPolicy> parent_grpclb_policy);
181
182 // It's the caller's responsibility to ensure that Orphan() is called from
183 // inside the combiner.
184 void Orphan() override;
185
186 void StartQuery();
187
Mark D. Roth290d35e2018-05-17 14:15:36 -0700188 GrpcLbClientStats* client_stats() const { return client_stats_.get(); }
189
Mark D. Rothc8875492018-02-20 08:33:48 -0800190 bool seen_initial_response() const { return seen_initial_response_; }
191
192 private:
Mark D. Roth9635a042018-04-20 10:44:17 -0700193 // So Delete() can access our private dtor.
194 template <typename T>
195 friend void grpc_core::Delete(T*);
196
Mark D. Rothc8875492018-02-20 08:33:48 -0800197 ~BalancerCallState();
198
199 GrpcLb* grpclb_policy() const {
Vijay Pai7fed69b2018-03-05 09:58:05 -0800200 return static_cast<GrpcLb*>(grpclb_policy_.get());
Mark D. Rothc8875492018-02-20 08:33:48 -0800201 }
202
203 void ScheduleNextClientLoadReportLocked();
204 void SendClientLoadReportLocked();
205
206 static bool LoadReportCountersAreZero(grpc_grpclb_request* request);
207
208 static void MaybeSendClientLoadReportLocked(void* arg, grpc_error* error);
209 static void ClientLoadReportDoneLocked(void* arg, grpc_error* error);
210 static void OnInitialRequestSentLocked(void* arg, grpc_error* error);
211 static void OnBalancerMessageReceivedLocked(void* arg, grpc_error* error);
212 static void OnBalancerStatusReceivedLocked(void* arg, grpc_error* error);
213
214 // The owning LB policy.
215 RefCountedPtr<LoadBalancingPolicy> grpclb_policy_;
216
217 // The streaming call to the LB server. Always non-NULL.
218 grpc_call* lb_call_ = nullptr;
219
220 // recv_initial_metadata
221 grpc_metadata_array lb_initial_metadata_recv_;
222
223 // send_message
224 grpc_byte_buffer* send_message_payload_ = nullptr;
225 grpc_closure lb_on_initial_request_sent_;
226
227 // recv_message
228 grpc_byte_buffer* recv_message_payload_ = nullptr;
229 grpc_closure lb_on_balancer_message_received_;
230 bool seen_initial_response_ = false;
231
232 // recv_trailing_metadata
233 grpc_closure lb_on_balancer_status_received_;
234 grpc_metadata_array lb_trailing_metadata_recv_;
235 grpc_status_code lb_call_status_;
236 grpc_slice lb_call_status_details_;
237
238 // The stats for client-side load reporting associated with this LB call.
239 // Created after the first serverlist is received.
Mark D. Roth290d35e2018-05-17 14:15:36 -0700240 RefCountedPtr<GrpcLbClientStats> client_stats_;
Mark D. Rothc8875492018-02-20 08:33:48 -0800241 grpc_millis client_stats_report_interval_ = 0;
242 grpc_timer client_load_report_timer_;
243 bool client_load_report_timer_callback_pending_ = false;
244 bool last_client_load_report_counters_were_zero_ = false;
245 bool client_load_report_is_due_ = false;
246 // The closure used for either the load report timer or the callback for
247 // completion of sending the load report.
248 grpc_closure client_load_report_closure_;
249 };
250
251 ~GrpcLb();
252
253 void ShutdownLocked() override;
254
255 // Helper function used in ctor and UpdateLocked().
256 void ProcessChannelArgsLocked(const grpc_channel_args& args);
257
258 // Methods for dealing with the balancer channel and call.
259 void StartPickingLocked();
260 void StartBalancerCallLocked();
261 static void OnFallbackTimerLocked(void* arg, grpc_error* error);
262 void StartBalancerCallRetryTimerLocked();
263 static void OnBalancerCallRetryTimerLocked(void* arg, grpc_error* error);
264 static void OnBalancerChannelConnectivityChangedLocked(void* arg,
265 grpc_error* error);
266
267 // Pending pick methods.
268 static void PendingPickSetMetadataAndContext(PendingPick* pp);
269 PendingPick* PendingPickCreate(PickState* pick);
270 void AddPendingPick(PendingPick* pp);
271 static void OnPendingPickComplete(void* arg, grpc_error* error);
272
273 // Pending ping methods.
274 void AddPendingPing(grpc_closure* on_initiate, grpc_closure* on_ack);
275
276 // Methods for dealing with the RR policy.
277 void CreateOrUpdateRoundRobinPolicyLocked();
278 grpc_channel_args* CreateRoundRobinPolicyArgsLocked();
279 void CreateRoundRobinPolicyLocked(const Args& args);
280 bool PickFromRoundRobinPolicyLocked(bool force_async, PendingPick* pp);
281 void UpdateConnectivityStateFromRoundRobinPolicyLocked(
282 grpc_error* rr_state_error);
283 static void OnRoundRobinConnectivityChangedLocked(void* arg,
284 grpc_error* error);
285 static void OnRoundRobinRequestReresolutionLocked(void* arg,
286 grpc_error* error);
287
288 // Who the client is trying to communicate with.
289 const char* server_name_ = nullptr;
290
291 // Current channel args from the resolver.
292 grpc_channel_args* args_ = nullptr;
293
294 // Internal state.
295 bool started_picking_ = false;
296 bool shutting_down_ = false;
297 grpc_connectivity_state_tracker state_tracker_;
298
299 // The channel for communicating with the LB server.
300 grpc_channel* lb_channel_ = nullptr;
301 grpc_connectivity_state lb_channel_connectivity_;
302 grpc_closure lb_channel_on_connectivity_changed_;
303 // Are we already watching the LB channel's connectivity?
304 bool watching_lb_channel_ = false;
305 // Response generator to inject address updates into lb_channel_.
306 RefCountedPtr<FakeResolverResponseGenerator> response_generator_;
307
308 // The data associated with the current LB call. It holds a ref to this LB
309 // policy. It's initialized every time we query for backends. It's reset to
310 // NULL whenever the current LB call is no longer needed (e.g., the LB policy
311 // is shutting down, or the LB call has ended). A non-NULL lb_calld_ always
312 // contains a non-NULL lb_call_.
313 OrphanablePtr<BalancerCallState> lb_calld_;
314 // Timeout in milliseconds for the LB call. 0 means no deadline.
315 int lb_call_timeout_ms_ = 0;
316 // Balancer call retry state.
317 BackOff lb_call_backoff_;
318 bool retry_timer_callback_pending_ = false;
319 grpc_timer lb_call_retry_timer_;
320 grpc_closure lb_on_call_retry_;
321
322 // The deserialized response from the balancer. May be nullptr until one
323 // such response has arrived.
324 grpc_grpclb_serverlist* serverlist_ = nullptr;
325 // Index into serverlist for next pick.
326 // If the server at this index is a drop, we return a drop.
327 // Otherwise, we delegate to the RR policy.
328 size_t serverlist_index_ = 0;
329
330 // Timeout in milliseconds for before using fallback backend addresses.
331 // 0 means not using fallback.
332 int lb_fallback_timeout_ms_ = 0;
333 // The backend addresses from the resolver.
334 grpc_lb_addresses* fallback_backend_addresses_ = nullptr;
335 // Fallback timer.
336 bool fallback_timer_callback_pending_ = false;
337 grpc_timer lb_fallback_timer_;
338 grpc_closure lb_on_fallback_;
339
340 // Pending picks and pings that are waiting on the RR policy's connectivity.
341 PendingPick* pending_picks_ = nullptr;
342 PendingPing* pending_pings_ = nullptr;
343
344 // The RR policy to use for the backends.
345 OrphanablePtr<LoadBalancingPolicy> rr_policy_;
346 grpc_connectivity_state rr_connectivity_state_;
347 grpc_closure on_rr_connectivity_changed_;
348 grpc_closure on_rr_request_reresolution_;
Vijay Pai849bd732018-01-02 23:30:47 +0000349};
Mark D. Rothc0febd32018-01-09 10:25:24 -0800350
Mark D. Rothc8875492018-02-20 08:33:48 -0800351//
352// serverlist parsing code
353//
Mark D. Rothc0febd32018-01-09 10:25:24 -0800354
Mark D. Rothc8875492018-02-20 08:33:48 -0800355// vtable for LB tokens in grpc_lb_addresses
356void* lb_token_copy(void* token) {
357 return token == nullptr
358 ? nullptr
359 : (void*)GRPC_MDELEM_REF(grpc_mdelem{(uintptr_t)token}).payload;
360}
361void lb_token_destroy(void* token) {
362 if (token != nullptr) {
363 GRPC_MDELEM_UNREF(grpc_mdelem{(uintptr_t)token});
Juanli Shen8e4c9d32018-01-23 16:26:39 -0800364 }
365}
Mark D. Rothc8875492018-02-20 08:33:48 -0800366int lb_token_cmp(void* token1, void* token2) {
367 if (token1 > token2) return 1;
368 if (token1 < token2) return -1;
369 return 0;
Juanli Shen8e4c9d32018-01-23 16:26:39 -0800370}
Mark D. Rothc8875492018-02-20 08:33:48 -0800371const grpc_lb_user_data_vtable lb_token_vtable = {
372 lb_token_copy, lb_token_destroy, lb_token_cmp};
Juanli Shen8e4c9d32018-01-23 16:26:39 -0800373
Mark D. Rothc8875492018-02-20 08:33:48 -0800374// Returns the backend addresses extracted from the given addresses.
375grpc_lb_addresses* ExtractBackendAddresses(const grpc_lb_addresses* addresses) {
376 // First pass: count the number of backend addresses.
377 size_t num_backends = 0;
378 for (size_t i = 0; i < addresses->num_addresses; ++i) {
379 if (!addresses->addresses[i].is_balancer) {
380 ++num_backends;
Mark D. Roth83d5cd62018-01-11 08:56:53 -0800381 }
Mark D. Rothc0febd32018-01-09 10:25:24 -0800382 }
Mark D. Rothc8875492018-02-20 08:33:48 -0800383 // Second pass: actually populate the addresses and (empty) LB tokens.
384 grpc_lb_addresses* backend_addresses =
385 grpc_lb_addresses_create(num_backends, &lb_token_vtable);
386 size_t num_copied = 0;
387 for (size_t i = 0; i < addresses->num_addresses; ++i) {
388 if (addresses->addresses[i].is_balancer) continue;
389 const grpc_resolved_address* addr = &addresses->addresses[i].address;
390 grpc_lb_addresses_set_address(backend_addresses, num_copied, &addr->addr,
391 addr->len, false /* is_balancer */,
392 nullptr /* balancer_name */,
393 (void*)GRPC_MDELEM_LB_TOKEN_EMPTY.payload);
394 ++num_copied;
395 }
396 return backend_addresses;
Mark D. Rothc0febd32018-01-09 10:25:24 -0800397}
398
Mark D. Rothc8875492018-02-20 08:33:48 -0800399bool IsServerValid(const grpc_grpclb_server* server, size_t idx, bool log) {
Mark D. Rothe7751802017-07-27 12:31:45 -0700400 if (server->drop) return false;
Craig Tillerbaa14a92017-11-03 09:09:36 -0700401 const grpc_grpclb_ip_address* ip = &server->ip_address;
Yash Tibrewal7f51ba82018-04-12 13:21:20 -0700402 if (GPR_UNLIKELY(server->port >> 16 != 0)) {
David Garcia Quintas35c2aba2016-09-13 15:28:09 -0700403 if (log) {
404 gpr_log(GPR_ERROR,
Jan Tattermusch2b398082016-10-07 14:40:30 +0200405 "Invalid port '%d' at index %lu of serverlist. Ignoring.",
Mark D. Rothc8875492018-02-20 08:33:48 -0800406 server->port, (unsigned long)idx);
David Garcia Quintas35c2aba2016-09-13 15:28:09 -0700407 }
408 return false;
409 }
Yash Tibrewal7f51ba82018-04-12 13:21:20 -0700410 if (GPR_UNLIKELY(ip->size != 4 && ip->size != 16)) {
David Garcia Quintas35c2aba2016-09-13 15:28:09 -0700411 if (log) {
412 gpr_log(GPR_ERROR,
Jan Tattermusch2b398082016-10-07 14:40:30 +0200413 "Expected IP to be 4 or 16 bytes, got %d at index %lu of "
David Garcia Quintas35c2aba2016-09-13 15:28:09 -0700414 "serverlist. Ignoring",
Mark D. Rothc8875492018-02-20 08:33:48 -0800415 ip->size, (unsigned long)idx);
David Garcia Quintas35c2aba2016-09-13 15:28:09 -0700416 }
417 return false;
418 }
419 return true;
420}
421
Mark D. Rothc8875492018-02-20 08:33:48 -0800422void ParseServer(const grpc_grpclb_server* server,
423 grpc_resolved_address* addr) {
Mark D. Rothd7389b42017-05-17 12:22:17 -0700424 memset(addr, 0, sizeof(*addr));
Mark D. Rothe7751802017-07-27 12:31:45 -0700425 if (server->drop) return;
kpayson64539f5062018-03-12 19:16:30 -0700426 const uint16_t netorder_port = grpc_htons((uint16_t)server->port);
David Garcia Quintas7ec29132016-11-01 04:09:05 +0100427 /* the addresses are given in binary format (a in(6)_addr struct) in
428 * server->ip_address.bytes. */
Craig Tillerbaa14a92017-11-03 09:09:36 -0700429 const grpc_grpclb_ip_address* ip = &server->ip_address;
David Garcia Quintas7ec29132016-11-01 04:09:05 +0100430 if (ip->size == 4) {
Yash Tibrewal44a15882018-03-14 18:41:33 -0700431 addr->len = static_cast<socklen_t>(sizeof(grpc_sockaddr_in));
kpayson64539f5062018-03-12 19:16:30 -0700432 grpc_sockaddr_in* addr4 = reinterpret_cast<grpc_sockaddr_in*>(&addr->addr);
433 addr4->sin_family = GRPC_AF_INET;
David Garcia Quintas7ec29132016-11-01 04:09:05 +0100434 memcpy(&addr4->sin_addr, ip->bytes, ip->size);
435 addr4->sin_port = netorder_port;
436 } else if (ip->size == 16) {
Yash Tibrewal44a15882018-03-14 18:41:33 -0700437 addr->len = static_cast<socklen_t>(sizeof(grpc_sockaddr_in6));
kpayson64539f5062018-03-12 19:16:30 -0700438 grpc_sockaddr_in6* addr6 = (grpc_sockaddr_in6*)&addr->addr;
439 addr6->sin6_family = GRPC_AF_INET6;
David Garcia Quintas7ec29132016-11-01 04:09:05 +0100440 memcpy(&addr6->sin6_addr, ip->bytes, ip->size);
441 addr6->sin6_port = netorder_port;
442 }
443}
444
Mark D. Rothc8875492018-02-20 08:33:48 -0800445// Returns addresses extracted from \a serverlist.
446grpc_lb_addresses* ProcessServerlist(const grpc_grpclb_serverlist* serverlist) {
David Garcia Quintas331b9c02016-09-12 18:37:05 -0700447 size_t num_valid = 0;
448 /* first pass: count how many are valid in order to allocate the necessary
449 * memory in a single block */
450 for (size_t i = 0; i < serverlist->num_servers; ++i) {
Mark D. Rothc8875492018-02-20 08:33:48 -0800451 if (IsServerValid(serverlist->servers[i], i, true)) ++num_valid;
David Garcia Quintasb8b384a2016-08-23 21:10:29 -0700452 }
Craig Tillerbaa14a92017-11-03 09:09:36 -0700453 grpc_lb_addresses* lb_addresses =
Mark D. Roth16883a32016-10-21 10:30:58 -0700454 grpc_lb_addresses_create(num_valid, &lb_token_vtable);
David Garcia Quintas331b9c02016-09-12 18:37:05 -0700455 /* second pass: actually populate the addresses and LB tokens (aka user data
David Garcia Quintas35c2aba2016-09-13 15:28:09 -0700456 * to the outside world) to be read by the RR policy during its creation.
457 * Given that the validity tests are very cheap, they are performed again
458 * instead of marking the valid ones during the first pass, as this would
459 * incurr in an allocation due to the arbitrary number of server */
David Garcia Quintasf47d6fb2016-09-14 12:59:17 -0700460 size_t addr_idx = 0;
461 for (size_t sl_idx = 0; sl_idx < serverlist->num_servers; ++sl_idx) {
Craig Tillerbaa14a92017-11-03 09:09:36 -0700462 const grpc_grpclb_server* server = serverlist->servers[sl_idx];
Mark D. Rothc8875492018-02-20 08:33:48 -0800463 if (!IsServerValid(serverlist->servers[sl_idx], sl_idx, false)) continue;
David Garcia Quintasc22c65b2017-07-25 14:22:20 -0700464 GPR_ASSERT(addr_idx < num_valid);
David Garcia Quintas331b9c02016-09-12 18:37:05 -0700465 /* address processing */
Mark D. Rothc5c38782016-09-16 08:51:01 -0700466 grpc_resolved_address addr;
Mark D. Rothc8875492018-02-20 08:33:48 -0800467 ParseServer(server, &addr);
David Garcia Quintasf47d6fb2016-09-14 12:59:17 -0700468 /* lb token processing */
Craig Tillerbaa14a92017-11-03 09:09:36 -0700469 void* user_data;
David Garcia Quintasf47d6fb2016-09-14 12:59:17 -0700470 if (server->has_load_balance_token) {
David Garcia Quintas0baf1dc2016-10-28 04:44:01 +0200471 const size_t lb_token_max_length =
472 GPR_ARRAY_SIZE(server->load_balance_token);
473 const size_t lb_token_length =
474 strnlen(server->load_balance_token, lb_token_max_length);
Craig Tiller7c70b6c2017-01-23 07:48:42 -0800475 grpc_slice lb_token_mdstr = grpc_slice_from_copied_buffer(
476 server->load_balance_token, lb_token_length);
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800477 user_data =
478 (void*)grpc_mdelem_from_slices(GRPC_MDSTR_LB_TOKEN, lb_token_mdstr)
479 .payload;
David Garcia Quintasf47d6fb2016-09-14 12:59:17 -0700480 } else {
Craig Tillerbaa14a92017-11-03 09:09:36 -0700481 char* uri = grpc_sockaddr_to_uri(&addr);
David Garcia Quintas850cbaa2016-11-15 15:13:35 -0800482 gpr_log(GPR_INFO,
David Garcia Quintasf47d6fb2016-09-14 12:59:17 -0700483 "Missing LB token for backend address '%s'. The empty token will "
484 "be used instead",
David Garcia Quintas850cbaa2016-11-15 15:13:35 -0800485 uri);
486 gpr_free(uri);
Craig Tillerbaa14a92017-11-03 09:09:36 -0700487 user_data = (void*)GRPC_MDELEM_LB_TOKEN_EMPTY.payload;
David Garcia Quintasf47d6fb2016-09-14 12:59:17 -0700488 }
Mark D. Roth64f1f8d2016-09-16 09:00:09 -0700489 grpc_lb_addresses_set_address(lb_addresses, addr_idx, &addr.addr, addr.len,
490 false /* is_balancer */,
Noah Eisen882dfed2017-11-14 14:58:20 -0800491 nullptr /* balancer_name */, user_data);
David Garcia Quintasf47d6fb2016-09-14 12:59:17 -0700492 ++addr_idx;
David Garcia Quintas331b9c02016-09-12 18:37:05 -0700493 }
David Garcia Quintasf47d6fb2016-09-14 12:59:17 -0700494 GPR_ASSERT(addr_idx == num_valid);
Mark D. Rothc5c38782016-09-16 08:51:01 -0700495 return lb_addresses;
496}
497
Mark D. Rothc8875492018-02-20 08:33:48 -0800498//
499// GrpcLb::BalancerCallState
500//
501
502GrpcLb::BalancerCallState::BalancerCallState(
503 RefCountedPtr<LoadBalancingPolicy> parent_grpclb_policy)
504 : InternallyRefCountedWithTracing<BalancerCallState>(&grpc_lb_glb_trace),
505 grpclb_policy_(std::move(parent_grpclb_policy)) {
506 GPR_ASSERT(grpclb_policy_ != nullptr);
507 GPR_ASSERT(!grpclb_policy()->shutting_down_);
508 // Init the LB call. Note that the LB call will progress every time there's
509 // activity in grpclb_policy_->interested_parties(), which is comprised of
510 // the polling entities from client_channel.
511 GPR_ASSERT(grpclb_policy()->server_name_ != nullptr);
512 GPR_ASSERT(grpclb_policy()->server_name_[0] != '\0');
David Garcia Quintasc7c0d692018-03-10 17:27:15 -0800513 const grpc_millis deadline =
Mark D. Rothc8875492018-02-20 08:33:48 -0800514 grpclb_policy()->lb_call_timeout_ms_ == 0
515 ? GRPC_MILLIS_INF_FUTURE
516 : ExecCtx::Get()->Now() + grpclb_policy()->lb_call_timeout_ms_;
517 lb_call_ = grpc_channel_create_pollset_set_call(
518 grpclb_policy()->lb_channel_, nullptr, GRPC_PROPAGATE_DEFAULTS,
519 grpclb_policy_->interested_parties(),
520 GRPC_MDSTR_SLASH_GRPC_DOT_LB_DOT_V1_DOT_LOADBALANCER_SLASH_BALANCELOAD,
David Garcia Quintasc7c0d692018-03-10 17:27:15 -0800521 nullptr, deadline, nullptr);
Mark D. Rothc8875492018-02-20 08:33:48 -0800522 // Init the LB call request payload.
523 grpc_grpclb_request* request =
524 grpc_grpclb_request_create(grpclb_policy()->server_name_);
525 grpc_slice request_payload_slice = grpc_grpclb_request_encode(request);
526 send_message_payload_ =
527 grpc_raw_byte_buffer_create(&request_payload_slice, 1);
528 grpc_slice_unref_internal(request_payload_slice);
529 grpc_grpclb_request_destroy(request);
530 // Init other data associated with the LB call.
531 grpc_metadata_array_init(&lb_initial_metadata_recv_);
532 grpc_metadata_array_init(&lb_trailing_metadata_recv_);
533 GRPC_CLOSURE_INIT(&lb_on_initial_request_sent_, OnInitialRequestSentLocked,
534 this, grpc_combiner_scheduler(grpclb_policy()->combiner()));
535 GRPC_CLOSURE_INIT(&lb_on_balancer_message_received_,
536 OnBalancerMessageReceivedLocked, this,
537 grpc_combiner_scheduler(grpclb_policy()->combiner()));
538 GRPC_CLOSURE_INIT(&lb_on_balancer_status_received_,
539 OnBalancerStatusReceivedLocked, this,
540 grpc_combiner_scheduler(grpclb_policy()->combiner()));
Juanli Shenfe408152017-09-27 12:27:20 -0700541}
542
Mark D. Rothc8875492018-02-20 08:33:48 -0800543GrpcLb::BalancerCallState::~BalancerCallState() {
544 GPR_ASSERT(lb_call_ != nullptr);
545 grpc_call_unref(lb_call_);
546 grpc_metadata_array_destroy(&lb_initial_metadata_recv_);
547 grpc_metadata_array_destroy(&lb_trailing_metadata_recv_);
548 grpc_byte_buffer_destroy(send_message_payload_);
549 grpc_byte_buffer_destroy(recv_message_payload_);
550 grpc_slice_unref_internal(lb_call_status_details_);
Mark D. Rothc8875492018-02-20 08:33:48 -0800551}
552
553void GrpcLb::BalancerCallState::Orphan() {
554 GPR_ASSERT(lb_call_ != nullptr);
555 // If we are here because grpclb_policy wants to cancel the call,
556 // lb_on_balancer_status_received_ will complete the cancellation and clean
557 // up. Otherwise, we are here because grpclb_policy has to orphan a failed
558 // call, then the following cancellation will be a no-op.
559 grpc_call_cancel(lb_call_, nullptr);
560 if (client_load_report_timer_callback_pending_) {
561 grpc_timer_cancel(&client_load_report_timer_);
562 }
563 // Note that the initial ref is hold by lb_on_balancer_status_received_
564 // instead of the caller of this function. So the corresponding unref happens
565 // in lb_on_balancer_status_received_ instead of here.
566}
567
568void GrpcLb::BalancerCallState::StartQuery() {
569 GPR_ASSERT(lb_call_ != nullptr);
570 if (grpc_lb_glb_trace.enabled()) {
571 gpr_log(GPR_INFO,
572 "[grpclb %p] Starting LB call (lb_calld: %p, lb_call: %p)",
573 grpclb_policy_.get(), this, lb_call_);
574 }
575 // Create the ops.
576 grpc_call_error call_error;
577 grpc_op ops[3];
578 memset(ops, 0, sizeof(ops));
579 // Op: send initial metadata.
580 grpc_op* op = ops;
581 op->op = GRPC_OP_SEND_INITIAL_METADATA;
582 op->data.send_initial_metadata.count = 0;
583 op->flags = 0;
584 op->reserved = nullptr;
585 op++;
586 // Op: send request message.
587 GPR_ASSERT(send_message_payload_ != nullptr);
588 op->op = GRPC_OP_SEND_MESSAGE;
589 op->data.send_message.send_message = send_message_payload_;
590 op->flags = 0;
591 op->reserved = nullptr;
592 op++;
593 // TODO(roth): We currently track this ref manually. Once the
594 // ClosureRef API is ready, we should pass the RefCountedPtr<> along
595 // with the callback.
596 auto self = Ref(DEBUG_LOCATION, "on_initial_request_sent");
597 self.release();
598 call_error = grpc_call_start_batch_and_execute(
599 lb_call_, ops, (size_t)(op - ops), &lb_on_initial_request_sent_);
600 GPR_ASSERT(GRPC_CALL_OK == call_error);
601 // Op: recv initial metadata.
602 op = ops;
603 op->op = GRPC_OP_RECV_INITIAL_METADATA;
604 op->data.recv_initial_metadata.recv_initial_metadata =
605 &lb_initial_metadata_recv_;
606 op->flags = 0;
607 op->reserved = nullptr;
608 op++;
609 // Op: recv response.
610 op->op = GRPC_OP_RECV_MESSAGE;
611 op->data.recv_message.recv_message = &recv_message_payload_;
612 op->flags = 0;
613 op->reserved = nullptr;
614 op++;
615 // TODO(roth): We currently track this ref manually. Once the
616 // ClosureRef API is ready, we should pass the RefCountedPtr<> along
617 // with the callback.
618 self = Ref(DEBUG_LOCATION, "on_message_received");
619 self.release();
620 call_error = grpc_call_start_batch_and_execute(
621 lb_call_, ops, (size_t)(op - ops), &lb_on_balancer_message_received_);
622 GPR_ASSERT(GRPC_CALL_OK == call_error);
623 // Op: recv server status.
624 op = ops;
625 op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;
626 op->data.recv_status_on_client.trailing_metadata =
627 &lb_trailing_metadata_recv_;
628 op->data.recv_status_on_client.status = &lb_call_status_;
629 op->data.recv_status_on_client.status_details = &lb_call_status_details_;
630 op->flags = 0;
631 op->reserved = nullptr;
632 op++;
633 // This callback signals the end of the LB call, so it relies on the initial
634 // ref instead of a new ref. When it's invoked, it's the initial ref that is
635 // unreffed.
636 call_error = grpc_call_start_batch_and_execute(
637 lb_call_, ops, (size_t)(op - ops), &lb_on_balancer_status_received_);
638 GPR_ASSERT(GRPC_CALL_OK == call_error);
639};
640
641void GrpcLb::BalancerCallState::ScheduleNextClientLoadReportLocked() {
642 const grpc_millis next_client_load_report_time =
643 ExecCtx::Get()->Now() + client_stats_report_interval_;
644 GRPC_CLOSURE_INIT(&client_load_report_closure_,
645 MaybeSendClientLoadReportLocked, this,
646 grpc_combiner_scheduler(grpclb_policy()->combiner()));
647 grpc_timer_init(&client_load_report_timer_, next_client_load_report_time,
648 &client_load_report_closure_);
649 client_load_report_timer_callback_pending_ = true;
650}
651
652void GrpcLb::BalancerCallState::MaybeSendClientLoadReportLocked(
653 void* arg, grpc_error* error) {
Vijay Pai7fed69b2018-03-05 09:58:05 -0800654 BalancerCallState* lb_calld = static_cast<BalancerCallState*>(arg);
Mark D. Rothc8875492018-02-20 08:33:48 -0800655 GrpcLb* grpclb_policy = lb_calld->grpclb_policy();
656 lb_calld->client_load_report_timer_callback_pending_ = false;
657 if (error != GRPC_ERROR_NONE || lb_calld != grpclb_policy->lb_calld_.get()) {
658 lb_calld->Unref(DEBUG_LOCATION, "client_load_report");
659 return;
660 }
661 // If we've already sent the initial request, then we can go ahead and send
662 // the load report. Otherwise, we need to wait until the initial request has
663 // been sent to send this (see OnInitialRequestSentLocked()).
664 if (lb_calld->send_message_payload_ == nullptr) {
665 lb_calld->SendClientLoadReportLocked();
666 } else {
667 lb_calld->client_load_report_is_due_ = true;
668 }
669}
670
671bool GrpcLb::BalancerCallState::LoadReportCountersAreZero(
672 grpc_grpclb_request* request) {
Mark D. Roth290d35e2018-05-17 14:15:36 -0700673 GrpcLbClientStats::DroppedCallCounts* drop_entries =
674 static_cast<GrpcLbClientStats::DroppedCallCounts*>(
Mark D. Rothc8875492018-02-20 08:33:48 -0800675 request->client_stats.calls_finished_with_drop.arg);
676 return request->client_stats.num_calls_started == 0 &&
677 request->client_stats.num_calls_finished == 0 &&
678 request->client_stats.num_calls_finished_with_client_failed_to_send ==
679 0 &&
680 request->client_stats.num_calls_finished_known_received == 0 &&
Mark D. Roth290d35e2018-05-17 14:15:36 -0700681 (drop_entries == nullptr || drop_entries->size() == 0);
Mark D. Rothc8875492018-02-20 08:33:48 -0800682}
683
684void GrpcLb::BalancerCallState::SendClientLoadReportLocked() {
685 // Construct message payload.
686 GPR_ASSERT(send_message_payload_ == nullptr);
687 grpc_grpclb_request* request =
Mark D. Roth290d35e2018-05-17 14:15:36 -0700688 grpc_grpclb_load_report_request_create_locked(client_stats_.get());
Mark D. Rothc8875492018-02-20 08:33:48 -0800689 // Skip client load report if the counters were all zero in the last
690 // report and they are still zero in this one.
691 if (LoadReportCountersAreZero(request)) {
692 if (last_client_load_report_counters_were_zero_) {
693 grpc_grpclb_request_destroy(request);
694 ScheduleNextClientLoadReportLocked();
695 return;
696 }
697 last_client_load_report_counters_were_zero_ = true;
698 } else {
699 last_client_load_report_counters_were_zero_ = false;
700 }
701 grpc_slice request_payload_slice = grpc_grpclb_request_encode(request);
702 send_message_payload_ =
703 grpc_raw_byte_buffer_create(&request_payload_slice, 1);
704 grpc_slice_unref_internal(request_payload_slice);
705 grpc_grpclb_request_destroy(request);
706 // Send the report.
707 grpc_op op;
708 memset(&op, 0, sizeof(op));
709 op.op = GRPC_OP_SEND_MESSAGE;
710 op.data.send_message.send_message = send_message_payload_;
711 GRPC_CLOSURE_INIT(&client_load_report_closure_, ClientLoadReportDoneLocked,
712 this, grpc_combiner_scheduler(grpclb_policy()->combiner()));
713 grpc_call_error call_error = grpc_call_start_batch_and_execute(
714 lb_call_, &op, 1, &client_load_report_closure_);
Yash Tibrewal7f51ba82018-04-12 13:21:20 -0700715 if (GPR_UNLIKELY(call_error != GRPC_CALL_OK)) {
Mark D. Rothc8875492018-02-20 08:33:48 -0800716 gpr_log(GPR_ERROR, "[grpclb %p] call_error=%d", grpclb_policy_.get(),
717 call_error);
718 GPR_ASSERT(GRPC_CALL_OK == call_error);
719 }
720}
721
722void GrpcLb::BalancerCallState::ClientLoadReportDoneLocked(void* arg,
723 grpc_error* error) {
Vijay Pai7fed69b2018-03-05 09:58:05 -0800724 BalancerCallState* lb_calld = static_cast<BalancerCallState*>(arg);
Mark D. Rothc8875492018-02-20 08:33:48 -0800725 GrpcLb* grpclb_policy = lb_calld->grpclb_policy();
726 grpc_byte_buffer_destroy(lb_calld->send_message_payload_);
727 lb_calld->send_message_payload_ = nullptr;
728 if (error != GRPC_ERROR_NONE || lb_calld != grpclb_policy->lb_calld_.get()) {
729 lb_calld->Unref(DEBUG_LOCATION, "client_load_report");
730 return;
731 }
732 lb_calld->ScheduleNextClientLoadReportLocked();
733}
734
735void GrpcLb::BalancerCallState::OnInitialRequestSentLocked(void* arg,
736 grpc_error* error) {
Vijay Pai7fed69b2018-03-05 09:58:05 -0800737 BalancerCallState* lb_calld = static_cast<BalancerCallState*>(arg);
Mark D. Rothc8875492018-02-20 08:33:48 -0800738 grpc_byte_buffer_destroy(lb_calld->send_message_payload_);
739 lb_calld->send_message_payload_ = nullptr;
740 // If we attempted to send a client load report before the initial request was
741 // sent (and this lb_calld is still in use), send the load report now.
742 if (lb_calld->client_load_report_is_due_ &&
743 lb_calld == lb_calld->grpclb_policy()->lb_calld_.get()) {
744 lb_calld->SendClientLoadReportLocked();
745 lb_calld->client_load_report_is_due_ = false;
746 }
747 lb_calld->Unref(DEBUG_LOCATION, "on_initial_request_sent");
748}
749
750void GrpcLb::BalancerCallState::OnBalancerMessageReceivedLocked(
751 void* arg, grpc_error* error) {
Vijay Pai7fed69b2018-03-05 09:58:05 -0800752 BalancerCallState* lb_calld = static_cast<BalancerCallState*>(arg);
Mark D. Rothc8875492018-02-20 08:33:48 -0800753 GrpcLb* grpclb_policy = lb_calld->grpclb_policy();
754 // Empty payload means the LB call was cancelled.
755 if (lb_calld != grpclb_policy->lb_calld_.get() ||
756 lb_calld->recv_message_payload_ == nullptr) {
757 lb_calld->Unref(DEBUG_LOCATION, "on_message_received");
758 return;
759 }
760 grpc_byte_buffer_reader bbr;
761 grpc_byte_buffer_reader_init(&bbr, lb_calld->recv_message_payload_);
762 grpc_slice response_slice = grpc_byte_buffer_reader_readall(&bbr);
763 grpc_byte_buffer_reader_destroy(&bbr);
764 grpc_byte_buffer_destroy(lb_calld->recv_message_payload_);
765 lb_calld->recv_message_payload_ = nullptr;
766 grpc_grpclb_initial_response* initial_response;
767 grpc_grpclb_serverlist* serverlist;
768 if (!lb_calld->seen_initial_response_ &&
769 (initial_response = grpc_grpclb_initial_response_parse(response_slice)) !=
770 nullptr) {
771 // Have NOT seen initial response, look for initial response.
772 if (initial_response->has_client_stats_report_interval) {
773 lb_calld->client_stats_report_interval_ = GPR_MAX(
774 GPR_MS_PER_SEC, grpc_grpclb_duration_to_millis(
775 &initial_response->client_stats_report_interval));
776 if (grpc_lb_glb_trace.enabled()) {
777 gpr_log(GPR_INFO,
778 "[grpclb %p] Received initial LB response message; "
Sree Kuchibhotla1dd12c02018-04-11 18:05:48 -0700779 "client load reporting interval = %" PRId64 " milliseconds",
Mark D. Rothc8875492018-02-20 08:33:48 -0800780 grpclb_policy, lb_calld->client_stats_report_interval_);
781 }
782 } else if (grpc_lb_glb_trace.enabled()) {
783 gpr_log(GPR_INFO,
784 "[grpclb %p] Received initial LB response message; client load "
785 "reporting NOT enabled",
786 grpclb_policy);
787 }
788 grpc_grpclb_initial_response_destroy(initial_response);
789 lb_calld->seen_initial_response_ = true;
790 } else if ((serverlist = grpc_grpclb_response_parse_serverlist(
791 response_slice)) != nullptr) {
792 // Have seen initial response, look for serverlist.
793 GPR_ASSERT(lb_calld->lb_call_ != nullptr);
794 if (grpc_lb_glb_trace.enabled()) {
795 gpr_log(GPR_INFO,
796 "[grpclb %p] Serverlist with %" PRIuPTR " servers received",
797 grpclb_policy, serverlist->num_servers);
798 for (size_t i = 0; i < serverlist->num_servers; ++i) {
799 grpc_resolved_address addr;
800 ParseServer(serverlist->servers[i], &addr);
801 char* ipport;
802 grpc_sockaddr_to_string(&ipport, &addr, false);
803 gpr_log(GPR_INFO, "[grpclb %p] Serverlist[%" PRIuPTR "]: %s",
804 grpclb_policy, i, ipport);
805 gpr_free(ipport);
806 }
807 }
808 /* update serverlist */
809 if (serverlist->num_servers > 0) {
810 // Start sending client load report only after we start using the
811 // serverlist returned from the current LB call.
812 if (lb_calld->client_stats_report_interval_ > 0 &&
813 lb_calld->client_stats_ == nullptr) {
Mark D. Roth290d35e2018-05-17 14:15:36 -0700814 lb_calld->client_stats_.reset(New<GrpcLbClientStats>());
Mark D. Rothc8875492018-02-20 08:33:48 -0800815 // TODO(roth): We currently track this ref manually. Once the
816 // ClosureRef API is ready, we should pass the RefCountedPtr<> along
817 // with the callback.
818 auto self = lb_calld->Ref(DEBUG_LOCATION, "client_load_report");
819 self.release();
820 lb_calld->ScheduleNextClientLoadReportLocked();
821 }
822 if (grpc_grpclb_serverlist_equals(grpclb_policy->serverlist_,
823 serverlist)) {
824 if (grpc_lb_glb_trace.enabled()) {
825 gpr_log(GPR_INFO,
826 "[grpclb %p] Incoming server list identical to current, "
827 "ignoring.",
828 grpclb_policy);
829 }
830 grpc_grpclb_destroy_serverlist(serverlist);
831 } else { /* new serverlist */
832 if (grpclb_policy->serverlist_ != nullptr) {
833 /* dispose of the old serverlist */
834 grpc_grpclb_destroy_serverlist(grpclb_policy->serverlist_);
835 } else {
836 /* or dispose of the fallback */
837 grpc_lb_addresses_destroy(grpclb_policy->fallback_backend_addresses_);
838 grpclb_policy->fallback_backend_addresses_ = nullptr;
839 if (grpclb_policy->fallback_timer_callback_pending_) {
840 grpc_timer_cancel(&grpclb_policy->lb_fallback_timer_);
841 }
842 }
843 // and update the copy in the GrpcLb instance. This
844 // serverlist instance will be destroyed either upon the next
845 // update or when the GrpcLb instance is destroyed.
846 grpclb_policy->serverlist_ = serverlist;
847 grpclb_policy->serverlist_index_ = 0;
848 grpclb_policy->CreateOrUpdateRoundRobinPolicyLocked();
849 }
850 } else {
851 if (grpc_lb_glb_trace.enabled()) {
852 gpr_log(GPR_INFO, "[grpclb %p] Received empty server list, ignoring.",
853 grpclb_policy);
854 }
855 grpc_grpclb_destroy_serverlist(serverlist);
856 }
857 } else {
858 // No valid initial response or serverlist found.
859 gpr_log(GPR_ERROR,
860 "[grpclb %p] Invalid LB response received: '%s'. Ignoring.",
861 grpclb_policy,
862 grpc_dump_slice(response_slice, GPR_DUMP_ASCII | GPR_DUMP_HEX));
863 }
864 grpc_slice_unref_internal(response_slice);
865 if (!grpclb_policy->shutting_down_) {
866 // Keep listening for serverlist updates.
867 grpc_op op;
868 memset(&op, 0, sizeof(op));
869 op.op = GRPC_OP_RECV_MESSAGE;
870 op.data.recv_message.recv_message = &lb_calld->recv_message_payload_;
871 op.flags = 0;
872 op.reserved = nullptr;
873 // Reuse the "OnBalancerMessageReceivedLocked" ref taken in StartQuery().
874 const grpc_call_error call_error = grpc_call_start_batch_and_execute(
875 lb_calld->lb_call_, &op, 1,
876 &lb_calld->lb_on_balancer_message_received_);
877 GPR_ASSERT(GRPC_CALL_OK == call_error);
878 } else {
879 lb_calld->Unref(DEBUG_LOCATION, "on_message_received+grpclb_shutdown");
880 }
881}
882
883void GrpcLb::BalancerCallState::OnBalancerStatusReceivedLocked(
884 void* arg, grpc_error* error) {
Vijay Pai7fed69b2018-03-05 09:58:05 -0800885 BalancerCallState* lb_calld = static_cast<BalancerCallState*>(arg);
Mark D. Rothc8875492018-02-20 08:33:48 -0800886 GrpcLb* grpclb_policy = lb_calld->grpclb_policy();
887 GPR_ASSERT(lb_calld->lb_call_ != nullptr);
888 if (grpc_lb_glb_trace.enabled()) {
889 char* status_details =
890 grpc_slice_to_c_string(lb_calld->lb_call_status_details_);
891 gpr_log(GPR_INFO,
892 "[grpclb %p] Status from LB server received. Status = %d, details "
893 "= '%s', (lb_calld: %p, lb_call: %p), error '%s'",
894 grpclb_policy, lb_calld->lb_call_status_, status_details, lb_calld,
895 lb_calld->lb_call_, grpc_error_string(error));
896 gpr_free(status_details);
897 }
898 grpclb_policy->TryReresolutionLocked(&grpc_lb_glb_trace, GRPC_ERROR_NONE);
899 // If this lb_calld is still in use, this call ended because of a failure so
900 // we want to retry connecting. Otherwise, we have deliberately ended this
901 // call and no further action is required.
902 if (lb_calld == grpclb_policy->lb_calld_.get()) {
903 grpclb_policy->lb_calld_.reset();
904 GPR_ASSERT(!grpclb_policy->shutting_down_);
905 if (lb_calld->seen_initial_response_) {
906 // If we lose connection to the LB server, reset the backoff and restart
907 // the LB call immediately.
908 grpclb_policy->lb_call_backoff_.Reset();
909 grpclb_policy->StartBalancerCallLocked();
910 } else {
911 // If this LB call fails establishing any connection to the LB server,
912 // retry later.
913 grpclb_policy->StartBalancerCallRetryTimerLocked();
914 }
915 }
916 lb_calld->Unref(DEBUG_LOCATION, "lb_call_ended");
917}
918
919//
920// helper code for creating balancer channel
921//
922
Mark D. Rothbd0f1512018-02-20 10:28:22 -0800923grpc_lb_addresses* ExtractBalancerAddresses(
924 const grpc_lb_addresses* addresses) {
925 size_t num_grpclb_addrs = 0;
926 for (size_t i = 0; i < addresses->num_addresses; ++i) {
927 if (addresses->addresses[i].is_balancer) ++num_grpclb_addrs;
928 }
929 // There must be at least one balancer address, or else the
930 // client_channel would not have chosen this LB policy.
931 GPR_ASSERT(num_grpclb_addrs > 0);
932 grpc_lb_addresses* lb_addresses =
933 grpc_lb_addresses_create(num_grpclb_addrs, nullptr);
934 size_t lb_addresses_idx = 0;
935 for (size_t i = 0; i < addresses->num_addresses; ++i) {
936 if (!addresses->addresses[i].is_balancer) continue;
Yash Tibrewal7f51ba82018-04-12 13:21:20 -0700937 if (GPR_UNLIKELY(addresses->addresses[i].user_data != nullptr)) {
Mark D. Rothbd0f1512018-02-20 10:28:22 -0800938 gpr_log(GPR_ERROR,
939 "This LB policy doesn't support user data. It will be ignored");
940 }
941 grpc_lb_addresses_set_address(
942 lb_addresses, lb_addresses_idx++, addresses->addresses[i].address.addr,
943 addresses->addresses[i].address.len, false /* is balancer */,
944 addresses->addresses[i].balancer_name, nullptr /* user data */);
945 }
946 GPR_ASSERT(num_grpclb_addrs == lb_addresses_idx);
947 return lb_addresses;
Mark D. Rothc8875492018-02-20 08:33:48 -0800948}
949
950/* Returns the channel args for the LB channel, used to create a bidirectional
951 * stream for the reception of load balancing updates.
952 *
953 * Inputs:
954 * - \a addresses: corresponding to the balancers.
955 * - \a response_generator: in order to propagate updates from the resolver
956 * above the grpclb policy.
957 * - \a args: other args inherited from the grpclb policy. */
958grpc_channel_args* BuildBalancerChannelArgs(
959 const grpc_lb_addresses* addresses,
960 FakeResolverResponseGenerator* response_generator,
961 const grpc_channel_args* args) {
Mark D. Rothbd0f1512018-02-20 10:28:22 -0800962 grpc_lb_addresses* lb_addresses = ExtractBalancerAddresses(addresses);
963 // Channel args to remove.
964 static const char* args_to_remove[] = {
965 // LB policy name, since we want to use the default (pick_first) in
966 // the LB channel.
967 GRPC_ARG_LB_POLICY_NAME,
968 // The channel arg for the server URI, since that will be different for
969 // the LB channel than for the parent channel. The client channel
970 // factory will re-add this arg with the right value.
971 GRPC_ARG_SERVER_URI,
972 // The resolved addresses, which will be generated by the name resolver
973 // used in the LB channel. Note that the LB channel will use the fake
974 // resolver, so this won't actually generate a query to DNS (or some
975 // other name service). However, the addresses returned by the fake
976 // resolver will have is_balancer=false, whereas our own addresses have
977 // is_balancer=true. We need the LB channel to return addresses with
978 // is_balancer=false so that it does not wind up recursively using the
979 // grpclb LB policy, as per the special case logic in client_channel.c.
980 GRPC_ARG_LB_ADDRESSES,
981 // The fake resolver response generator, because we are replacing it
982 // with the one from the grpclb policy, used to propagate updates to
983 // the LB channel.
984 GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
David Garcia Quintasc7c0d692018-03-10 17:27:15 -0800985 // The LB channel should use the authority indicated by the target
986 // authority table (see \a grpc_lb_policy_grpclb_modify_lb_channel_args),
987 // as opposed to the authority from the parent channel.
988 GRPC_ARG_DEFAULT_AUTHORITY,
David Garcia Quintas7b84b3d2018-03-12 12:08:30 -0700989 // Just as for \a GRPC_ARG_DEFAULT_AUTHORITY, the LB channel should be
990 // treated as a stand-alone channel and not inherit this argument from the
991 // args of the parent channel.
992 GRPC_SSL_TARGET_NAME_OVERRIDE_ARG,
Mark D. Rothbd0f1512018-02-20 10:28:22 -0800993 };
994 // Channel args to add.
995 const grpc_arg args_to_add[] = {
996 // New LB addresses.
997 // Note that we pass these in both when creating the LB channel
998 // and via the fake resolver. The latter is what actually gets used.
999 grpc_lb_addresses_create_channel_arg(lb_addresses),
1000 // The fake resolver response generator, which we use to inject
1001 // address updates into the LB channel.
1002 grpc_core::FakeResolverResponseGenerator::MakeChannelArg(
1003 response_generator),
Yihua Zhang392dad72018-05-03 20:12:20 -07001004 // A channel arg indicating the target is a grpclb load balancer.
1005 grpc_channel_arg_integer_create(
1006 const_cast<char*>(GRPC_ARG_ADDRESS_IS_GRPCLB_LOAD_BALANCER), 1),
ncteisen97066fd2018-07-13 14:05:27 -07001007 // A channel arg indicating the target is a grpclb load balancer.
1008 grpc_channel_arg_integer_create(
1009 const_cast<char*>(GRPC_ARG_CHANNELZ_CHANNEL_IS_INTERNAL_CHANNEL), 1),
Mark D. Rothbd0f1512018-02-20 10:28:22 -08001010 };
1011 // Construct channel args.
1012 grpc_channel_args* new_args = grpc_channel_args_copy_and_add_and_remove(
1013 args, args_to_remove, GPR_ARRAY_SIZE(args_to_remove), args_to_add,
1014 GPR_ARRAY_SIZE(args_to_add));
1015 // Make any necessary modifications for security.
1016 new_args = grpc_lb_policy_grpclb_modify_lb_channel_args(new_args);
1017 // Clean up.
Mark D. Rothc8875492018-02-20 08:33:48 -08001018 grpc_lb_addresses_destroy(lb_addresses);
Mark D. Rothbd0f1512018-02-20 10:28:22 -08001019 return new_args;
Mark D. Rothc8875492018-02-20 08:33:48 -08001020}
1021
1022//
1023// ctor and dtor
1024//
1025
1026GrpcLb::GrpcLb(const grpc_lb_addresses* addresses,
1027 const LoadBalancingPolicy::Args& args)
1028 : LoadBalancingPolicy(args),
1029 response_generator_(MakeRefCounted<FakeResolverResponseGenerator>()),
1030 lb_call_backoff_(
1031 BackOff::Options()
1032 .set_initial_backoff(GRPC_GRPCLB_INITIAL_CONNECT_BACKOFF_SECONDS *
1033 1000)
1034 .set_multiplier(GRPC_GRPCLB_RECONNECT_BACKOFF_MULTIPLIER)
1035 .set_jitter(GRPC_GRPCLB_RECONNECT_JITTER)
1036 .set_max_backoff(GRPC_GRPCLB_RECONNECT_MAX_BACKOFF_SECONDS *
1037 1000)) {
1038 // Initialization.
1039 grpc_subchannel_index_ref();
1040 GRPC_CLOSURE_INIT(&lb_channel_on_connectivity_changed_,
1041 &GrpcLb::OnBalancerChannelConnectivityChangedLocked, this,
1042 grpc_combiner_scheduler(args.combiner));
1043 GRPC_CLOSURE_INIT(&on_rr_connectivity_changed_,
1044 &GrpcLb::OnRoundRobinConnectivityChangedLocked, this,
1045 grpc_combiner_scheduler(args.combiner));
1046 GRPC_CLOSURE_INIT(&on_rr_request_reresolution_,
1047 &GrpcLb::OnRoundRobinRequestReresolutionLocked, this,
1048 grpc_combiner_scheduler(args.combiner));
1049 grpc_connectivity_state_init(&state_tracker_, GRPC_CHANNEL_IDLE, "grpclb");
1050 // Record server name.
Noah Eisen7ea8a602018-06-14 11:43:18 -04001051 const grpc_arg* arg = grpc_channel_args_find(args.args, GRPC_ARG_SERVER_URI);
1052 const char* server_uri = grpc_channel_arg_get_string(arg);
Mark D. Rothc8875492018-02-20 08:33:48 -08001053 GPR_ASSERT(server_uri != nullptr);
1054 grpc_uri* uri = grpc_uri_parse(server_uri, true);
1055 GPR_ASSERT(uri->path[0] != '\0');
1056 server_name_ = gpr_strdup(uri->path[0] == '/' ? uri->path + 1 : uri->path);
1057 if (grpc_lb_glb_trace.enabled()) {
1058 gpr_log(GPR_INFO,
1059 "[grpclb %p] Will use '%s' as the server name for LB request.",
1060 this, server_name_);
1061 }
1062 grpc_uri_destroy(uri);
1063 // Record LB call timeout.
Noah Eisen7ea8a602018-06-14 11:43:18 -04001064 arg = grpc_channel_args_find(args.args, GRPC_ARG_GRPCLB_CALL_TIMEOUT_MS);
1065 lb_call_timeout_ms_ = grpc_channel_arg_get_integer(arg, {0, 0, INT_MAX});
Mark D. Rothc8875492018-02-20 08:33:48 -08001066 // Record fallback timeout.
Noah Eisen7ea8a602018-06-14 11:43:18 -04001067 arg = grpc_channel_args_find(args.args, GRPC_ARG_GRPCLB_FALLBACK_TIMEOUT_MS);
1068 lb_fallback_timeout_ms_ = grpc_channel_arg_get_integer(
1069 arg, {GRPC_GRPCLB_DEFAULT_FALLBACK_TIMEOUT_MS, 0, INT_MAX});
Mark D. Rothc8875492018-02-20 08:33:48 -08001070 // Process channel args.
1071 ProcessChannelArgsLocked(*args.args);
1072}
1073
1074GrpcLb::~GrpcLb() {
1075 GPR_ASSERT(pending_picks_ == nullptr);
1076 GPR_ASSERT(pending_pings_ == nullptr);
1077 gpr_free((void*)server_name_);
1078 grpc_channel_args_destroy(args_);
1079 grpc_connectivity_state_destroy(&state_tracker_);
1080 if (serverlist_ != nullptr) {
1081 grpc_grpclb_destroy_serverlist(serverlist_);
1082 }
1083 if (fallback_backend_addresses_ != nullptr) {
1084 grpc_lb_addresses_destroy(fallback_backend_addresses_);
1085 }
1086 grpc_subchannel_index_unref();
1087}
1088
1089void GrpcLb::ShutdownLocked() {
1090 grpc_error* error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Channel shutdown");
1091 shutting_down_ = true;
1092 lb_calld_.reset();
1093 if (retry_timer_callback_pending_) {
1094 grpc_timer_cancel(&lb_call_retry_timer_);
1095 }
1096 if (fallback_timer_callback_pending_) {
1097 grpc_timer_cancel(&lb_fallback_timer_);
1098 }
1099 rr_policy_.reset();
1100 TryReresolutionLocked(&grpc_lb_glb_trace, GRPC_ERROR_CANCELLED);
1101 // We destroy the LB channel here instead of in our destructor because
1102 // destroying the channel triggers a last callback to
1103 // OnBalancerChannelConnectivityChangedLocked(), and we need to be
1104 // alive when that callback is invoked.
1105 if (lb_channel_ != nullptr) {
1106 grpc_channel_destroy(lb_channel_);
1107 lb_channel_ = nullptr;
1108 }
1109 grpc_connectivity_state_set(&state_tracker_, GRPC_CHANNEL_SHUTDOWN,
1110 GRPC_ERROR_REF(error), "grpclb_shutdown");
1111 // Clear pending picks.
1112 PendingPick* pp;
1113 while ((pp = pending_picks_) != nullptr) {
1114 pending_picks_ = pp->next;
1115 pp->pick->connected_subchannel.reset();
1116 // Note: pp is deleted in this callback.
1117 GRPC_CLOSURE_SCHED(&pp->on_complete, GRPC_ERROR_REF(error));
1118 }
1119 // Clear pending pings.
1120 PendingPing* pping;
1121 while ((pping = pending_pings_) != nullptr) {
1122 pending_pings_ = pping->next;
1123 GRPC_CLOSURE_SCHED(pping->on_initiate, GRPC_ERROR_REF(error));
1124 GRPC_CLOSURE_SCHED(pping->on_ack, GRPC_ERROR_REF(error));
1125 Delete(pping);
1126 }
1127 GRPC_ERROR_UNREF(error);
1128}
1129
1130//
1131// public methods
1132//
1133
1134void GrpcLb::HandOffPendingPicksLocked(LoadBalancingPolicy* new_policy) {
1135 PendingPick* pp;
1136 while ((pp = pending_picks_) != nullptr) {
1137 pending_picks_ = pp->next;
1138 pp->pick->on_complete = pp->original_on_complete;
1139 pp->pick->user_data = nullptr;
1140 if (new_policy->PickLocked(pp->pick)) {
1141 // Synchronous return; schedule closure.
1142 GRPC_CLOSURE_SCHED(pp->pick->on_complete, GRPC_ERROR_NONE);
1143 }
1144 Delete(pp);
1145 }
1146}
1147
1148// Cancel a specific pending pick.
1149//
1150// A grpclb pick progresses as follows:
1151// - If there's a Round Robin policy (rr_policy_) available, it'll be
1152// handed over to the RR policy (in CreateRoundRobinPolicyLocked()). From
1153// that point onwards, it'll be RR's responsibility. For cancellations, that
1154// implies the pick needs also be cancelled by the RR instance.
1155// - Otherwise, without an RR instance, picks stay pending at this policy's
1156// level (grpclb), inside the pending_picks_ list. To cancel these,
1157// we invoke the completion closure and set the pick's connected
1158// subchannel to nullptr right here.
1159void GrpcLb::CancelPickLocked(PickState* pick, grpc_error* error) {
1160 PendingPick* pp = pending_picks_;
1161 pending_picks_ = nullptr;
1162 while (pp != nullptr) {
1163 PendingPick* next = pp->next;
1164 if (pp->pick == pick) {
1165 pick->connected_subchannel.reset();
1166 // Note: pp is deleted in this callback.
1167 GRPC_CLOSURE_SCHED(&pp->on_complete,
1168 GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
1169 "Pick Cancelled", &error, 1));
1170 } else {
1171 pp->next = pending_picks_;
1172 pending_picks_ = pp;
1173 }
1174 pp = next;
1175 }
1176 if (rr_policy_ != nullptr) {
1177 rr_policy_->CancelPickLocked(pick, GRPC_ERROR_REF(error));
1178 }
1179 GRPC_ERROR_UNREF(error);
1180}
1181
1182// Cancel all pending picks.
1183//
1184// A grpclb pick progresses as follows:
1185// - If there's a Round Robin policy (rr_policy_) available, it'll be
1186// handed over to the RR policy (in CreateRoundRobinPolicyLocked()). From
1187// that point onwards, it'll be RR's responsibility. For cancellations, that
1188// implies the pick needs also be cancelled by the RR instance.
1189// - Otherwise, without an RR instance, picks stay pending at this policy's
1190// level (grpclb), inside the pending_picks_ list. To cancel these,
1191// we invoke the completion closure and set the pick's connected
1192// subchannel to nullptr right here.
1193void GrpcLb::CancelMatchingPicksLocked(uint32_t initial_metadata_flags_mask,
1194 uint32_t initial_metadata_flags_eq,
1195 grpc_error* error) {
1196 PendingPick* pp = pending_picks_;
1197 pending_picks_ = nullptr;
1198 while (pp != nullptr) {
1199 PendingPick* next = pp->next;
1200 if ((pp->pick->initial_metadata_flags & initial_metadata_flags_mask) ==
1201 initial_metadata_flags_eq) {
1202 // Note: pp is deleted in this callback.
1203 GRPC_CLOSURE_SCHED(&pp->on_complete,
1204 GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
1205 "Pick Cancelled", &error, 1));
1206 } else {
1207 pp->next = pending_picks_;
1208 pending_picks_ = pp;
1209 }
1210 pp = next;
1211 }
1212 if (rr_policy_ != nullptr) {
1213 rr_policy_->CancelMatchingPicksLocked(initial_metadata_flags_mask,
1214 initial_metadata_flags_eq,
1215 GRPC_ERROR_REF(error));
1216 }
1217 GRPC_ERROR_UNREF(error);
1218}
1219
1220void GrpcLb::ExitIdleLocked() {
1221 if (!started_picking_) {
1222 StartPickingLocked();
1223 }
1224}
1225
1226bool GrpcLb::PickLocked(PickState* pick) {
1227 PendingPick* pp = PendingPickCreate(pick);
1228 bool pick_done = false;
1229 if (rr_policy_ != nullptr) {
1230 const grpc_connectivity_state rr_connectivity_state =
1231 rr_policy_->CheckConnectivityLocked(nullptr);
1232 // The RR policy may have transitioned to SHUTDOWN but the callback
1233 // registered to capture this event (on_rr_connectivity_changed_) may not
1234 // have been invoked yet. We need to make sure we aren't trying to pick
1235 // from an RR policy instance that's in shutdown.
1236 if (rr_connectivity_state == GRPC_CHANNEL_SHUTDOWN) {
1237 if (grpc_lb_glb_trace.enabled()) {
1238 gpr_log(GPR_INFO,
1239 "[grpclb %p] NOT picking from from RR %p: RR conn state=%s",
1240 this, rr_policy_.get(),
1241 grpc_connectivity_state_name(rr_connectivity_state));
1242 }
1243 AddPendingPick(pp);
1244 pick_done = false;
1245 } else { // RR not in shutdown
1246 if (grpc_lb_glb_trace.enabled()) {
1247 gpr_log(GPR_INFO, "[grpclb %p] about to PICK from RR %p", this,
1248 rr_policy_.get());
1249 }
1250 pick_done = PickFromRoundRobinPolicyLocked(false /* force_async */, pp);
1251 }
1252 } else { // rr_policy_ == NULL
1253 if (grpc_lb_glb_trace.enabled()) {
Mark D. Roth48854d22018-04-25 13:05:26 -07001254 gpr_log(GPR_INFO,
Mark D. Rothc8875492018-02-20 08:33:48 -08001255 "[grpclb %p] No RR policy. Adding to grpclb's pending picks",
1256 this);
1257 }
1258 AddPendingPick(pp);
1259 if (!started_picking_) {
1260 StartPickingLocked();
1261 }
1262 pick_done = false;
1263 }
1264 return pick_done;
1265}
1266
1267void GrpcLb::PingOneLocked(grpc_closure* on_initiate, grpc_closure* on_ack) {
1268 if (rr_policy_ != nullptr) {
1269 rr_policy_->PingOneLocked(on_initiate, on_ack);
1270 } else {
1271 AddPendingPing(on_initiate, on_ack);
1272 if (!started_picking_) {
1273 StartPickingLocked();
1274 }
1275 }
1276}
1277
1278grpc_connectivity_state GrpcLb::CheckConnectivityLocked(
1279 grpc_error** connectivity_error) {
1280 return grpc_connectivity_state_get(&state_tracker_, connectivity_error);
1281}
1282
1283void GrpcLb::NotifyOnStateChangeLocked(grpc_connectivity_state* current,
1284 grpc_closure* notify) {
1285 grpc_connectivity_state_notify_on_state_change(&state_tracker_, current,
1286 notify);
1287}
1288
1289void GrpcLb::ProcessChannelArgsLocked(const grpc_channel_args& args) {
Noah Eisen7ea8a602018-06-14 11:43:18 -04001290 const grpc_arg* arg = grpc_channel_args_find(&args, GRPC_ARG_LB_ADDRESSES);
1291 if (GPR_UNLIKELY(arg == nullptr || arg->type != GRPC_ARG_POINTER)) {
Mark D. Rothc8875492018-02-20 08:33:48 -08001292 // Ignore this update.
1293 gpr_log(
1294 GPR_ERROR,
1295 "[grpclb %p] No valid LB addresses channel arg in update, ignoring.",
1296 this);
1297 return;
1298 }
Noah Eisen7ea8a602018-06-14 11:43:18 -04001299 const grpc_lb_addresses* addresses =
1300 static_cast<const grpc_lb_addresses*>(arg->value.pointer.p);
Mark D. Rothc8875492018-02-20 08:33:48 -08001301 // Update fallback address list.
1302 if (fallback_backend_addresses_ != nullptr) {
1303 grpc_lb_addresses_destroy(fallback_backend_addresses_);
1304 }
1305 fallback_backend_addresses_ = ExtractBackendAddresses(addresses);
1306 // Make sure that GRPC_ARG_LB_POLICY_NAME is set in channel args,
1307 // since we use this to trigger the client_load_reporting filter.
1308 static const char* args_to_remove[] = {GRPC_ARG_LB_POLICY_NAME};
1309 grpc_arg new_arg = grpc_channel_arg_string_create(
1310 (char*)GRPC_ARG_LB_POLICY_NAME, (char*)"grpclb");
1311 grpc_channel_args_destroy(args_);
1312 args_ = grpc_channel_args_copy_and_add_and_remove(
1313 &args, args_to_remove, GPR_ARRAY_SIZE(args_to_remove), &new_arg, 1);
1314 // Construct args for balancer channel.
1315 grpc_channel_args* lb_channel_args =
1316 BuildBalancerChannelArgs(addresses, response_generator_.get(), &args);
1317 // Create balancer channel if needed.
1318 if (lb_channel_ == nullptr) {
1319 char* uri_str;
1320 gpr_asprintf(&uri_str, "fake:///%s", server_name_);
Mark D. Rothbd0f1512018-02-20 10:28:22 -08001321 lb_channel_ = grpc_client_channel_factory_create_channel(
1322 client_channel_factory(), uri_str,
1323 GRPC_CLIENT_CHANNEL_TYPE_LOAD_BALANCING, lb_channel_args);
Mark D. Rothc8875492018-02-20 08:33:48 -08001324 GPR_ASSERT(lb_channel_ != nullptr);
1325 gpr_free(uri_str);
1326 }
1327 // Propagate updates to the LB channel (pick_first) through the fake
1328 // resolver.
1329 response_generator_->SetResponse(lb_channel_args);
1330 grpc_channel_args_destroy(lb_channel_args);
1331}
1332
1333void GrpcLb::UpdateLocked(const grpc_channel_args& args) {
1334 ProcessChannelArgsLocked(args);
1335 // If fallback is configured and the RR policy already exists, update
1336 // it with the new fallback addresses.
1337 if (lb_fallback_timeout_ms_ > 0 && rr_policy_ != nullptr) {
1338 CreateOrUpdateRoundRobinPolicyLocked();
1339 }
1340 // Start watching the LB channel connectivity for connection, if not
1341 // already doing so.
1342 if (!watching_lb_channel_) {
1343 lb_channel_connectivity_ = grpc_channel_check_connectivity_state(
1344 lb_channel_, true /* try to connect */);
1345 grpc_channel_element* client_channel_elem = grpc_channel_stack_last_element(
1346 grpc_channel_get_channel_stack(lb_channel_));
1347 GPR_ASSERT(client_channel_elem->filter == &grpc_client_channel_filter);
1348 watching_lb_channel_ = true;
1349 // TODO(roth): We currently track this ref manually. Once the
1350 // ClosureRef API is ready, we should pass the RefCountedPtr<> along
1351 // with the callback.
1352 auto self = Ref(DEBUG_LOCATION, "watch_lb_channel_connectivity");
1353 self.release();
1354 grpc_client_channel_watch_connectivity_state(
1355 client_channel_elem,
1356 grpc_polling_entity_create_from_pollset_set(interested_parties()),
1357 &lb_channel_connectivity_, &lb_channel_on_connectivity_changed_,
1358 nullptr);
1359 }
1360}
1361
1362//
1363// code for balancer channel and call
1364//
1365
1366void GrpcLb::StartPickingLocked() {
1367 // Start a timer to fall back.
1368 if (lb_fallback_timeout_ms_ > 0 && serverlist_ == nullptr &&
1369 !fallback_timer_callback_pending_) {
1370 grpc_millis deadline = ExecCtx::Get()->Now() + lb_fallback_timeout_ms_;
1371 // TODO(roth): We currently track this ref manually. Once the
1372 // ClosureRef API is ready, we should pass the RefCountedPtr<> along
1373 // with the callback.
1374 auto self = Ref(DEBUG_LOCATION, "on_fallback_timer");
1375 self.release();
1376 GRPC_CLOSURE_INIT(&lb_on_fallback_, &GrpcLb::OnFallbackTimerLocked, this,
1377 grpc_combiner_scheduler(combiner()));
1378 fallback_timer_callback_pending_ = true;
1379 grpc_timer_init(&lb_fallback_timer_, deadline, &lb_on_fallback_);
1380 }
1381 started_picking_ = true;
1382 StartBalancerCallLocked();
1383}
1384
1385void GrpcLb::StartBalancerCallLocked() {
1386 GPR_ASSERT(lb_channel_ != nullptr);
1387 if (shutting_down_) return;
1388 // Init the LB call data.
1389 GPR_ASSERT(lb_calld_ == nullptr);
1390 lb_calld_ = MakeOrphanable<BalancerCallState>(Ref());
1391 if (grpc_lb_glb_trace.enabled()) {
1392 gpr_log(GPR_INFO,
1393 "[grpclb %p] Query for backends (lb_channel: %p, lb_calld: %p)",
1394 this, lb_channel_, lb_calld_.get());
1395 }
1396 lb_calld_->StartQuery();
1397}
1398
1399void GrpcLb::OnFallbackTimerLocked(void* arg, grpc_error* error) {
1400 GrpcLb* grpclb_policy = static_cast<GrpcLb*>(arg);
1401 grpclb_policy->fallback_timer_callback_pending_ = false;
1402 // If we receive a serverlist after the timer fires but before this callback
1403 // actually runs, don't fall back.
1404 if (grpclb_policy->serverlist_ == nullptr && !grpclb_policy->shutting_down_ &&
1405 error == GRPC_ERROR_NONE) {
1406 if (grpc_lb_glb_trace.enabled()) {
1407 gpr_log(GPR_INFO,
1408 "[grpclb %p] Falling back to use backends from resolver",
1409 grpclb_policy);
1410 }
1411 GPR_ASSERT(grpclb_policy->fallback_backend_addresses_ != nullptr);
1412 grpclb_policy->CreateOrUpdateRoundRobinPolicyLocked();
1413 }
1414 grpclb_policy->Unref(DEBUG_LOCATION, "on_fallback_timer");
1415}
1416
1417void GrpcLb::StartBalancerCallRetryTimerLocked() {
1418 grpc_millis next_try = lb_call_backoff_.NextAttemptTime();
1419 if (grpc_lb_glb_trace.enabled()) {
Mark D. Roth48854d22018-04-25 13:05:26 -07001420 gpr_log(GPR_INFO, "[grpclb %p] Connection to LB server lost...", this);
Mark D. Rothc8875492018-02-20 08:33:48 -08001421 grpc_millis timeout = next_try - ExecCtx::Get()->Now();
1422 if (timeout > 0) {
Sree Kuchibhotla6d5c2c22018-05-08 10:24:30 -07001423 gpr_log(GPR_INFO, "[grpclb %p] ... retry_timer_active in %" PRId64 "ms.",
Mark D. Roth48854d22018-04-25 13:05:26 -07001424 this, timeout);
Mark D. Rothc8875492018-02-20 08:33:48 -08001425 } else {
Mark D. Roth48854d22018-04-25 13:05:26 -07001426 gpr_log(GPR_INFO, "[grpclb %p] ... retry_timer_active immediately.",
Mark D. Rothc8875492018-02-20 08:33:48 -08001427 this);
1428 }
1429 }
1430 // TODO(roth): We currently track this ref manually. Once the
1431 // ClosureRef API is ready, we should pass the RefCountedPtr<> along
1432 // with the callback.
1433 auto self = Ref(DEBUG_LOCATION, "on_balancer_call_retry_timer");
1434 self.release();
1435 GRPC_CLOSURE_INIT(&lb_on_call_retry_, &GrpcLb::OnBalancerCallRetryTimerLocked,
1436 this, grpc_combiner_scheduler(combiner()));
1437 retry_timer_callback_pending_ = true;
1438 grpc_timer_init(&lb_call_retry_timer_, next_try, &lb_on_call_retry_);
1439}
1440
1441void GrpcLb::OnBalancerCallRetryTimerLocked(void* arg, grpc_error* error) {
Vijay Pai7fed69b2018-03-05 09:58:05 -08001442 GrpcLb* grpclb_policy = static_cast<GrpcLb*>(arg);
Mark D. Rothc8875492018-02-20 08:33:48 -08001443 grpclb_policy->retry_timer_callback_pending_ = false;
1444 if (!grpclb_policy->shutting_down_ && error == GRPC_ERROR_NONE &&
1445 grpclb_policy->lb_calld_ == nullptr) {
1446 if (grpc_lb_glb_trace.enabled()) {
1447 gpr_log(GPR_INFO, "[grpclb %p] Restarting call to LB server",
1448 grpclb_policy);
1449 }
1450 grpclb_policy->StartBalancerCallLocked();
1451 }
1452 grpclb_policy->Unref(DEBUG_LOCATION, "on_balancer_call_retry_timer");
1453}
1454
1455// Invoked as part of the update process. It continues watching the LB channel
1456// until it shuts down or becomes READY. It's invoked even if the LB channel
1457// stayed READY throughout the update (for example if the update is identical).
1458void GrpcLb::OnBalancerChannelConnectivityChangedLocked(void* arg,
1459 grpc_error* error) {
1460 GrpcLb* grpclb_policy = static_cast<GrpcLb*>(arg);
1461 if (grpclb_policy->shutting_down_) goto done;
1462 // Re-initialize the lb_call. This should also take care of updating the
1463 // embedded RR policy. Note that the current RR policy, if any, will stay in
1464 // effect until an update from the new lb_call is received.
1465 switch (grpclb_policy->lb_channel_connectivity_) {
1466 case GRPC_CHANNEL_CONNECTING:
1467 case GRPC_CHANNEL_TRANSIENT_FAILURE: {
1468 // Keep watching the LB channel.
1469 grpc_channel_element* client_channel_elem =
1470 grpc_channel_stack_last_element(
1471 grpc_channel_get_channel_stack(grpclb_policy->lb_channel_));
1472 GPR_ASSERT(client_channel_elem->filter == &grpc_client_channel_filter);
1473 grpc_client_channel_watch_connectivity_state(
1474 client_channel_elem,
1475 grpc_polling_entity_create_from_pollset_set(
1476 grpclb_policy->interested_parties()),
1477 &grpclb_policy->lb_channel_connectivity_,
1478 &grpclb_policy->lb_channel_on_connectivity_changed_, nullptr);
1479 break;
1480 }
1481 // The LB channel may be IDLE because it's shut down before the update.
1482 // Restart the LB call to kick the LB channel into gear.
1483 case GRPC_CHANNEL_IDLE:
1484 case GRPC_CHANNEL_READY:
1485 grpclb_policy->lb_calld_.reset();
1486 if (grpclb_policy->started_picking_) {
1487 if (grpclb_policy->retry_timer_callback_pending_) {
1488 grpc_timer_cancel(&grpclb_policy->lb_call_retry_timer_);
1489 }
1490 grpclb_policy->lb_call_backoff_.Reset();
1491 grpclb_policy->StartBalancerCallLocked();
1492 }
1493 // Fall through.
1494 case GRPC_CHANNEL_SHUTDOWN:
1495 done:
1496 grpclb_policy->watching_lb_channel_ = false;
1497 grpclb_policy->Unref(DEBUG_LOCATION,
1498 "watch_lb_channel_connectivity_cb_shutdown");
1499 }
1500}
1501
1502//
1503// PendingPick
1504//
1505
1506// Adds lb_token of selected subchannel (address) to the call's initial
1507// metadata.
1508grpc_error* AddLbTokenToInitialMetadata(
1509 grpc_mdelem lb_token, grpc_linked_mdelem* lb_token_mdelem_storage,
1510 grpc_metadata_batch* initial_metadata) {
1511 GPR_ASSERT(lb_token_mdelem_storage != nullptr);
1512 GPR_ASSERT(!GRPC_MDISNULL(lb_token));
1513 return grpc_metadata_batch_add_tail(initial_metadata, lb_token_mdelem_storage,
1514 lb_token);
1515}
1516
1517// Destroy function used when embedding client stats in call context.
1518void DestroyClientStats(void* arg) {
Mark D. Roth290d35e2018-05-17 14:15:36 -07001519 static_cast<GrpcLbClientStats*>(arg)->Unref();
Mark D. Rothc8875492018-02-20 08:33:48 -08001520}
1521
1522void GrpcLb::PendingPickSetMetadataAndContext(PendingPick* pp) {
1523 /* if connected_subchannel is nullptr, no pick has been made by the RR
1524 * policy (e.g., all addresses failed to connect). There won't be any
1525 * user_data/token available */
1526 if (pp->pick->connected_subchannel != nullptr) {
Yash Tibrewal7f51ba82018-04-12 13:21:20 -07001527 if (GPR_LIKELY(!GRPC_MDISNULL(pp->lb_token))) {
Mark D. Rothc8875492018-02-20 08:33:48 -08001528 AddLbTokenToInitialMetadata(GRPC_MDELEM_REF(pp->lb_token),
1529 &pp->pick->lb_token_mdelem_storage,
1530 pp->pick->initial_metadata);
1531 } else {
1532 gpr_log(GPR_ERROR,
1533 "[grpclb %p] No LB token for connected subchannel pick %p",
1534 pp->grpclb_policy, pp->pick);
1535 abort();
1536 }
1537 // Pass on client stats via context. Passes ownership of the reference.
1538 if (pp->client_stats != nullptr) {
1539 pp->pick->subchannel_call_context[GRPC_GRPCLB_CLIENT_STATS].value =
Mark D. Roth290d35e2018-05-17 14:15:36 -07001540 pp->client_stats.release();
Mark D. Rothc8875492018-02-20 08:33:48 -08001541 pp->pick->subchannel_call_context[GRPC_GRPCLB_CLIENT_STATS].destroy =
1542 DestroyClientStats;
1543 }
1544 } else {
Mark D. Roth290d35e2018-05-17 14:15:36 -07001545 pp->client_stats.reset();
Mark D. Rothc8875492018-02-20 08:33:48 -08001546 }
1547}
1548
1549/* The \a on_complete closure passed as part of the pick requires keeping a
1550 * reference to its associated round robin instance. We wrap this closure in
1551 * order to unref the round robin instance upon its invocation */
1552void GrpcLb::OnPendingPickComplete(void* arg, grpc_error* error) {
Vijay Pai7fed69b2018-03-05 09:58:05 -08001553 PendingPick* pp = static_cast<PendingPick*>(arg);
Mark D. Rothc8875492018-02-20 08:33:48 -08001554 PendingPickSetMetadataAndContext(pp);
1555 GRPC_CLOSURE_SCHED(pp->original_on_complete, GRPC_ERROR_REF(error));
1556 Delete(pp);
1557}
1558
1559GrpcLb::PendingPick* GrpcLb::PendingPickCreate(PickState* pick) {
1560 PendingPick* pp = New<PendingPick>();
1561 pp->grpclb_policy = this;
1562 pp->pick = pick;
1563 GRPC_CLOSURE_INIT(&pp->on_complete, &GrpcLb::OnPendingPickComplete, pp,
1564 grpc_schedule_on_exec_ctx);
1565 pp->original_on_complete = pick->on_complete;
1566 pick->on_complete = &pp->on_complete;
1567 return pp;
1568}
1569
1570void GrpcLb::AddPendingPick(PendingPick* pp) {
1571 pp->next = pending_picks_;
1572 pending_picks_ = pp;
1573}
1574
1575//
1576// PendingPing
1577//
1578
1579void GrpcLb::AddPendingPing(grpc_closure* on_initiate, grpc_closure* on_ack) {
1580 PendingPing* pping = New<PendingPing>();
1581 pping->on_initiate = on_initiate;
1582 pping->on_ack = on_ack;
1583 pping->next = pending_pings_;
1584 pending_pings_ = pping;
1585}
1586
1587//
1588// code for interacting with the RR policy
1589//
1590
1591// Performs a pick over \a rr_policy_. Given that a pick can return
1592// immediately (ignoring its completion callback), we need to perform the
1593// cleanups this callback would otherwise be responsible for.
1594// If \a force_async is true, then we will manually schedule the
1595// completion callback even if the pick is available immediately.
1596bool GrpcLb::PickFromRoundRobinPolicyLocked(bool force_async, PendingPick* pp) {
1597 // Check for drops if we are not using fallback backend addresses.
1598 if (serverlist_ != nullptr) {
1599 // Look at the index into the serverlist to see if we should drop this call.
1600 grpc_grpclb_server* server = serverlist_->servers[serverlist_index_++];
1601 if (serverlist_index_ == serverlist_->num_servers) {
1602 serverlist_index_ = 0; // Wrap-around.
1603 }
1604 if (server->drop) {
1605 // Update client load reporting stats to indicate the number of
1606 // dropped calls. Note that we have to do this here instead of in
1607 // the client_load_reporting filter, because we do not create a
1608 // subchannel call (and therefore no client_load_reporting filter)
1609 // for dropped calls.
1610 if (lb_calld_ != nullptr && lb_calld_->client_stats() != nullptr) {
Mark D. Roth290d35e2018-05-17 14:15:36 -07001611 lb_calld_->client_stats()->AddCallDroppedLocked(
1612 server->load_balance_token);
Mark D. Rothc8875492018-02-20 08:33:48 -08001613 }
1614 if (force_async) {
1615 GRPC_CLOSURE_SCHED(pp->original_on_complete, GRPC_ERROR_NONE);
1616 Delete(pp);
1617 return false;
1618 }
1619 Delete(pp);
1620 return true;
1621 }
1622 }
1623 // Set client_stats and user_data.
1624 if (lb_calld_ != nullptr && lb_calld_->client_stats() != nullptr) {
Mark D. Roth290d35e2018-05-17 14:15:36 -07001625 pp->client_stats = lb_calld_->client_stats()->Ref();
Mark D. Rothc8875492018-02-20 08:33:48 -08001626 }
1627 GPR_ASSERT(pp->pick->user_data == nullptr);
1628 pp->pick->user_data = (void**)&pp->lb_token;
1629 // Pick via the RR policy.
1630 bool pick_done = rr_policy_->PickLocked(pp->pick);
1631 if (pick_done) {
1632 PendingPickSetMetadataAndContext(pp);
1633 if (force_async) {
1634 GRPC_CLOSURE_SCHED(pp->original_on_complete, GRPC_ERROR_NONE);
1635 pick_done = false;
1636 }
1637 Delete(pp);
1638 }
1639 // else, the pending pick will be registered and taken care of by the
1640 // pending pick list inside the RR policy. Eventually,
1641 // OnPendingPickComplete() will be called, which will (among other
1642 // things) add the LB token to the call's initial metadata.
1643 return pick_done;
1644}
1645
1646void GrpcLb::CreateRoundRobinPolicyLocked(const Args& args) {
1647 GPR_ASSERT(rr_policy_ == nullptr);
1648 rr_policy_ = LoadBalancingPolicyRegistry::CreateLoadBalancingPolicy(
1649 "round_robin", args);
Yash Tibrewal7f51ba82018-04-12 13:21:20 -07001650 if (GPR_UNLIKELY(rr_policy_ == nullptr)) {
Mark D. Rothc8875492018-02-20 08:33:48 -08001651 gpr_log(GPR_ERROR, "[grpclb %p] Failure creating a RoundRobin policy",
1652 this);
1653 return;
1654 }
1655 // TODO(roth): We currently track this ref manually. Once the new
1656 // ClosureRef API is done, pass the RefCountedPtr<> along with the closure.
1657 auto self = Ref(DEBUG_LOCATION, "on_rr_reresolution_requested");
1658 self.release();
1659 rr_policy_->SetReresolutionClosureLocked(&on_rr_request_reresolution_);
1660 grpc_error* rr_state_error = nullptr;
1661 rr_connectivity_state_ = rr_policy_->CheckConnectivityLocked(&rr_state_error);
1662 // Connectivity state is a function of the RR policy updated/created.
1663 UpdateConnectivityStateFromRoundRobinPolicyLocked(rr_state_error);
1664 // Add the gRPC LB's interested_parties pollset_set to that of the newly
1665 // created RR policy. This will make the RR policy progress upon activity on
1666 // gRPC LB, which in turn is tied to the application's call.
1667 grpc_pollset_set_add_pollset_set(rr_policy_->interested_parties(),
1668 interested_parties());
1669 // Subscribe to changes to the connectivity of the new RR.
1670 // TODO(roth): We currently track this ref manually. Once the new
1671 // ClosureRef API is done, pass the RefCountedPtr<> along with the closure.
1672 self = Ref(DEBUG_LOCATION, "on_rr_connectivity_changed");
1673 self.release();
1674 rr_policy_->NotifyOnStateChangeLocked(&rr_connectivity_state_,
1675 &on_rr_connectivity_changed_);
1676 rr_policy_->ExitIdleLocked();
1677 // Send pending picks to RR policy.
1678 PendingPick* pp;
1679 while ((pp = pending_picks_)) {
1680 pending_picks_ = pp->next;
1681 if (grpc_lb_glb_trace.enabled()) {
1682 gpr_log(GPR_INFO,
1683 "[grpclb %p] Pending pick about to (async) PICK from RR %p", this,
1684 rr_policy_.get());
1685 }
1686 PickFromRoundRobinPolicyLocked(true /* force_async */, pp);
1687 }
1688 // Send pending pings to RR policy.
1689 PendingPing* pping;
1690 while ((pping = pending_pings_)) {
1691 pending_pings_ = pping->next;
1692 if (grpc_lb_glb_trace.enabled()) {
1693 gpr_log(GPR_INFO, "[grpclb %p] Pending ping about to PING from RR %p",
1694 this, rr_policy_.get());
1695 }
1696 rr_policy_->PingOneLocked(pping->on_initiate, pping->on_ack);
1697 Delete(pping);
1698 }
1699}
1700
1701grpc_channel_args* GrpcLb::CreateRoundRobinPolicyArgsLocked() {
1702 grpc_lb_addresses* addresses;
Yihua Zhang392dad72018-05-03 20:12:20 -07001703 bool is_backend_from_grpclb_load_balancer = false;
Mark D. Rothc8875492018-02-20 08:33:48 -08001704 if (serverlist_ != nullptr) {
1705 GPR_ASSERT(serverlist_->num_servers > 0);
1706 addresses = ProcessServerlist(serverlist_);
Yihua Zhang392dad72018-05-03 20:12:20 -07001707 is_backend_from_grpclb_load_balancer = true;
Mark D. Rothc8875492018-02-20 08:33:48 -08001708 } else {
1709 // If CreateOrUpdateRoundRobinPolicyLocked() is invoked when we haven't
1710 // received any serverlist from the balancer, we use the fallback backends
1711 // returned by the resolver. Note that the fallback backend list may be
1712 // empty, in which case the new round_robin policy will keep the requested
1713 // picks pending.
1714 GPR_ASSERT(fallback_backend_addresses_ != nullptr);
1715 addresses = grpc_lb_addresses_copy(fallback_backend_addresses_);
1716 }
1717 GPR_ASSERT(addresses != nullptr);
1718 // Replace the LB addresses in the channel args that we pass down to
1719 // the subchannel.
1720 static const char* keys_to_remove[] = {GRPC_ARG_LB_ADDRESSES};
Yihua Zhang392dad72018-05-03 20:12:20 -07001721 const grpc_arg args_to_add[] = {
1722 grpc_lb_addresses_create_channel_arg(addresses),
1723 // A channel arg indicating if the target is a backend inferred from a
1724 // grpclb load balancer.
1725 grpc_channel_arg_integer_create(
1726 const_cast<char*>(
1727 GRPC_ARG_ADDRESS_IS_BACKEND_FROM_GRPCLB_LOAD_BALANCER),
1728 is_backend_from_grpclb_load_balancer),
1729 };
Mark D. Rothc8875492018-02-20 08:33:48 -08001730 grpc_channel_args* args = grpc_channel_args_copy_and_add_and_remove(
Yihua Zhang392dad72018-05-03 20:12:20 -07001731 args_, keys_to_remove, GPR_ARRAY_SIZE(keys_to_remove), args_to_add,
1732 GPR_ARRAY_SIZE(args_to_add));
Mark D. Rothc8875492018-02-20 08:33:48 -08001733 grpc_lb_addresses_destroy(addresses);
1734 return args;
1735}
1736
1737void GrpcLb::CreateOrUpdateRoundRobinPolicyLocked() {
1738 if (shutting_down_) return;
1739 grpc_channel_args* args = CreateRoundRobinPolicyArgsLocked();
1740 GPR_ASSERT(args != nullptr);
1741 if (rr_policy_ != nullptr) {
1742 if (grpc_lb_glb_trace.enabled()) {
Mark D. Roth48854d22018-04-25 13:05:26 -07001743 gpr_log(GPR_INFO, "[grpclb %p] Updating RR policy %p", this,
Mark D. Rothc8875492018-02-20 08:33:48 -08001744 rr_policy_.get());
1745 }
1746 rr_policy_->UpdateLocked(*args);
1747 } else {
1748 LoadBalancingPolicy::Args lb_policy_args;
1749 lb_policy_args.combiner = combiner();
1750 lb_policy_args.client_channel_factory = client_channel_factory();
1751 lb_policy_args.args = args;
1752 CreateRoundRobinPolicyLocked(lb_policy_args);
1753 if (grpc_lb_glb_trace.enabled()) {
Mark D. Roth48854d22018-04-25 13:05:26 -07001754 gpr_log(GPR_INFO, "[grpclb %p] Created new RR policy %p", this,
Mark D. Rothc8875492018-02-20 08:33:48 -08001755 rr_policy_.get());
1756 }
1757 }
1758 grpc_channel_args_destroy(args);
1759}
1760
1761void GrpcLb::OnRoundRobinRequestReresolutionLocked(void* arg,
1762 grpc_error* error) {
Vijay Pai7fed69b2018-03-05 09:58:05 -08001763 GrpcLb* grpclb_policy = static_cast<GrpcLb*>(arg);
Mark D. Rothc8875492018-02-20 08:33:48 -08001764 if (grpclb_policy->shutting_down_ || error != GRPC_ERROR_NONE) {
1765 grpclb_policy->Unref(DEBUG_LOCATION, "on_rr_reresolution_requested");
1766 return;
1767 }
1768 if (grpc_lb_glb_trace.enabled()) {
1769 gpr_log(
Mark D. Roth48854d22018-04-25 13:05:26 -07001770 GPR_INFO,
Mark D. Rothc8875492018-02-20 08:33:48 -08001771 "[grpclb %p] Re-resolution requested from the internal RR policy (%p).",
1772 grpclb_policy, grpclb_policy->rr_policy_.get());
1773 }
1774 // If we are talking to a balancer, we expect to get updated addresses form
1775 // the balancer, so we can ignore the re-resolution request from the RR
1776 // policy. Otherwise, handle the re-resolution request using the
1777 // grpclb policy's original re-resolution closure.
1778 if (grpclb_policy->lb_calld_ == nullptr ||
1779 !grpclb_policy->lb_calld_->seen_initial_response()) {
1780 grpclb_policy->TryReresolutionLocked(&grpc_lb_glb_trace, GRPC_ERROR_NONE);
1781 }
1782 // Give back the wrapper closure to the RR policy.
1783 grpclb_policy->rr_policy_->SetReresolutionClosureLocked(
1784 &grpclb_policy->on_rr_request_reresolution_);
1785}
1786
1787void GrpcLb::UpdateConnectivityStateFromRoundRobinPolicyLocked(
1788 grpc_error* rr_state_error) {
Craig Tiller613dafa2017-02-09 12:00:43 -08001789 const grpc_connectivity_state curr_glb_state =
Mark D. Rothc8875492018-02-20 08:33:48 -08001790 grpc_connectivity_state_check(&state_tracker_);
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001791 /* The new connectivity status is a function of the previous one and the new
1792 * input coming from the status of the RR policy.
1793 *
David Garcia Quintas4283a262016-11-18 10:43:56 -08001794 * current state (grpclb's)
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001795 * |
1796 * v || I | C | R | TF | SD | <- new state (RR's)
1797 * ===++====+=====+=====+======+======+
David Garcia Quintas4283a262016-11-18 10:43:56 -08001798 * I || I | C | R | [I] | [I] |
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001799 * ---++----+-----+-----+------+------+
David Garcia Quintas4283a262016-11-18 10:43:56 -08001800 * C || I | C | R | [C] | [C] |
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001801 * ---++----+-----+-----+------+------+
David Garcia Quintas4283a262016-11-18 10:43:56 -08001802 * R || I | C | R | [R] | [R] |
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001803 * ---++----+-----+-----+------+------+
David Garcia Quintas4283a262016-11-18 10:43:56 -08001804 * TF || I | C | R | [TF] | [TF] |
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001805 * ---++----+-----+-----+------+------+
1806 * SD || NA | NA | NA | NA | NA | (*)
1807 * ---++----+-----+-----+------+------+
1808 *
David Garcia Quintas4283a262016-11-18 10:43:56 -08001809 * A [STATE] indicates that the old RR policy is kept. In those cases, STATE
1810 * is the current state of grpclb, which is left untouched.
1811 *
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001812 * In summary, if the new state is TRANSIENT_FAILURE or SHUTDOWN, stick to
1813 * the previous RR instance.
1814 *
1815 * Note that the status is never updated to SHUTDOWN as a result of calling
1816 * this function. Only glb_shutdown() has the power to set that state.
1817 *
1818 * (*) This function mustn't be called during shutting down. */
1819 GPR_ASSERT(curr_glb_state != GRPC_CHANNEL_SHUTDOWN);
Mark D. Rothc8875492018-02-20 08:33:48 -08001820 switch (rr_connectivity_state_) {
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001821 case GRPC_CHANNEL_TRANSIENT_FAILURE:
1822 case GRPC_CHANNEL_SHUTDOWN:
David Garcia Quintas87d5a312017-06-06 19:45:58 -07001823 GPR_ASSERT(rr_state_error != GRPC_ERROR_NONE);
1824 break;
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001825 case GRPC_CHANNEL_IDLE:
1826 case GRPC_CHANNEL_CONNECTING:
1827 case GRPC_CHANNEL_READY:
David Garcia Quintas87d5a312017-06-06 19:45:58 -07001828 GPR_ASSERT(rr_state_error == GRPC_ERROR_NONE);
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001829 }
Craig Tiller6014e8a2017-10-16 13:50:29 -07001830 if (grpc_lb_glb_trace.enabled()) {
David Garcia Quintas87d5a312017-06-06 19:45:58 -07001831 gpr_log(
David Garcia Quintasa1c65902017-11-09 10:37:35 -08001832 GPR_INFO,
1833 "[grpclb %p] Setting grpclb's state to %s from new RR policy %p state.",
Mark D. Rothc8875492018-02-20 08:33:48 -08001834 this, grpc_connectivity_state_name(rr_connectivity_state_),
1835 rr_policy_.get());
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001836 }
Mark D. Rothc8875492018-02-20 08:33:48 -08001837 grpc_connectivity_state_set(&state_tracker_, rr_connectivity_state_,
1838 rr_state_error,
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001839 "update_lb_connectivity_status_locked");
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001840}
1841
Mark D. Rothc8875492018-02-20 08:33:48 -08001842void GrpcLb::OnRoundRobinConnectivityChangedLocked(void* arg,
1843 grpc_error* error) {
Vijay Pai7fed69b2018-03-05 09:58:05 -08001844 GrpcLb* grpclb_policy = static_cast<GrpcLb*>(arg);
Mark D. Rothc8875492018-02-20 08:33:48 -08001845 if (grpclb_policy->shutting_down_) {
1846 grpclb_policy->Unref(DEBUG_LOCATION, "on_rr_connectivity_changed");
Juanli Shen87c65042018-02-15 09:42:45 -08001847 return;
1848 }
Mark D. Rothc8875492018-02-20 08:33:48 -08001849 grpclb_policy->UpdateConnectivityStateFromRoundRobinPolicyLocked(
1850 GRPC_ERROR_REF(error));
1851 // Resubscribe. Reuse the "on_rr_connectivity_changed" ref.
1852 grpclb_policy->rr_policy_->NotifyOnStateChangeLocked(
1853 &grpclb_policy->rr_connectivity_state_,
1854 &grpclb_policy->on_rr_connectivity_changed_);
Juanli Shen87c65042018-02-15 09:42:45 -08001855}
1856
David Garcia Quintasc22c65b2017-07-25 14:22:20 -07001857//
Mark D. Rothc8875492018-02-20 08:33:48 -08001858// factory
David Garcia Quintasc22c65b2017-07-25 14:22:20 -07001859//
Mark D. Rothc8875492018-02-20 08:33:48 -08001860
1861class GrpcLbFactory : public LoadBalancingPolicyFactory {
1862 public:
1863 OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
1864 const LoadBalancingPolicy::Args& args) const override {
1865 /* Count the number of gRPC-LB addresses. There must be at least one. */
Noah Eisen7ea8a602018-06-14 11:43:18 -04001866 const grpc_arg* arg =
1867 grpc_channel_args_find(args.args, GRPC_ARG_LB_ADDRESSES);
1868 if (arg == nullptr || arg->type != GRPC_ARG_POINTER) {
Mark D. Rothc8875492018-02-20 08:33:48 -08001869 return nullptr;
David Garcia Quintas65318262016-07-29 13:43:38 -07001870 }
Noah Eisen7ea8a602018-06-14 11:43:18 -04001871 grpc_lb_addresses* addresses =
1872 static_cast<grpc_lb_addresses*>(arg->value.pointer.p);
Mark D. Rothc8875492018-02-20 08:33:48 -08001873 size_t num_grpclb_addrs = 0;
1874 for (size_t i = 0; i < addresses->num_addresses; ++i) {
1875 if (addresses->addresses[i].is_balancer) ++num_grpclb_addrs;
David Garcia Quintas65318262016-07-29 13:43:38 -07001876 }
Mark D. Rothc8875492018-02-20 08:33:48 -08001877 if (num_grpclb_addrs == 0) return nullptr;
1878 return OrphanablePtr<LoadBalancingPolicy>(New<GrpcLb>(addresses, args));
David Garcia Quintas65318262016-07-29 13:43:38 -07001879 }
David Garcia Quintas8d489112016-07-29 15:20:42 -07001880
Mark D. Rothc8875492018-02-20 08:33:48 -08001881 const char* name() const override { return "grpclb"; }
1882};
David Garcia Quintas8d489112016-07-29 15:20:42 -07001883
Mark D. Rothc8875492018-02-20 08:33:48 -08001884} // namespace
David Garcia Quintas8d489112016-07-29 15:20:42 -07001885
Mark D. Rothc8875492018-02-20 08:33:48 -08001886} // namespace grpc_core
David Garcia Quintas65318262016-07-29 13:43:38 -07001887
Mark D. Rothc8875492018-02-20 08:33:48 -08001888//
1889// Plugin registration
1890//
Mark D. Rotha4792f52017-09-26 09:06:35 -07001891
Mark D. Rothc8875492018-02-20 08:33:48 -08001892namespace {
Mark D. Roth09e458c2017-05-02 08:13:26 -07001893
1894// Only add client_load_reporting filter if the grpclb LB policy is used.
Mark D. Rothc8875492018-02-20 08:33:48 -08001895bool maybe_add_client_load_reporting_filter(grpc_channel_stack_builder* builder,
1896 void* arg) {
Craig Tillerbaa14a92017-11-03 09:09:36 -07001897 const grpc_channel_args* args =
Mark D. Roth09e458c2017-05-02 08:13:26 -07001898 grpc_channel_stack_builder_get_channel_arguments(builder);
Noah Eisen7ea8a602018-06-14 11:43:18 -04001899 const grpc_arg* channel_arg =
1900 grpc_channel_args_find(args, GRPC_ARG_LB_POLICY_NAME);
1901 if (channel_arg != nullptr && channel_arg->type == GRPC_ARG_STRING &&
1902 strcmp(channel_arg->value.string, "grpclb") == 0) {
Mark D. Roth09e458c2017-05-02 08:13:26 -07001903 return grpc_channel_stack_builder_append_filter(
Mark D. Rothc8875492018-02-20 08:33:48 -08001904 builder, (const grpc_channel_filter*)arg, nullptr, nullptr);
Mark D. Roth09e458c2017-05-02 08:13:26 -07001905 }
1906 return true;
1907}
1908
Mark D. Rothc8875492018-02-20 08:33:48 -08001909} // namespace
1910
ncteisenadbfbd52017-11-16 15:35:45 -08001911void grpc_lb_policy_grpclb_init() {
Mark D. Rothc8875492018-02-20 08:33:48 -08001912 grpc_core::LoadBalancingPolicyRegistry::Builder::
1913 RegisterLoadBalancingPolicyFactory(
1914 grpc_core::UniquePtr<grpc_core::LoadBalancingPolicyFactory>(
1915 grpc_core::New<grpc_core::GrpcLbFactory>()));
Mark D. Roth09e458c2017-05-02 08:13:26 -07001916 grpc_channel_init_register_stage(GRPC_CLIENT_SUBCHANNEL,
1917 GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
1918 maybe_add_client_load_reporting_filter,
Craig Tillerbaa14a92017-11-03 09:09:36 -07001919 (void*)&grpc_client_load_reporting_filter);
David Garcia Quintas3fb8f732016-06-15 22:53:08 -07001920}
1921
ncteisenadbfbd52017-11-16 15:35:45 -08001922void grpc_lb_policy_grpclb_shutdown() {}