blob: 79deb0ab833429eead684868f47f3dc8efd5f64e [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"
Craig Tiller9eb0fde2017-03-31 16:59:30 -070079#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h"
Mark D. Roth09e458c2017-05-02 08:13:26 -070080#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h"
Craig Tiller9eb0fde2017-03-31 16:59:30 -070081#include "src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.h"
Craig Tillerd52e22f2017-04-02 16:22:52 -070082#include "src/core/ext/filters/client_channel/lb_policy_factory.h"
83#include "src/core/ext/filters/client_channel/lb_policy_registry.h"
84#include "src/core/ext/filters/client_channel/parse_address.h"
David Garcia Quintas87d5a312017-06-06 19:45:58 -070085#include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
Juanli Shen6502ecc2017-09-13 13:10:54 -070086#include "src/core/ext/filters/client_channel/subchannel_index.h"
Craig Tillerc0df1c02017-07-17 16:12:33 -070087#include "src/core/lib/backoff/backoff.h"
Mark D. Roth046cf762016-09-26 11:13:51 -070088#include "src/core/lib/channel/channel_args.h"
Mark D. Roth09e458c2017-05-02 08:13:26 -070089#include "src/core/lib/channel/channel_stack.h"
Vijay Paiae376bf2018-01-25 22:54:02 -080090#include "src/core/lib/gpr/host_port.h"
Mark D. Rothdbdf4952018-01-18 11:21:12 -080091#include "src/core/lib/gpr/string.h"
Mark D. Roth4f2b0fd2018-01-19 12:12:23 -080092#include "src/core/lib/gprpp/manual_constructor.h"
Mark D. Rothc8875492018-02-20 08:33:48 -080093#include "src/core/lib/gprpp/memory.h"
94#include "src/core/lib/gprpp/orphanable.h"
Mark D. Roth209f6442018-02-08 10:26:46 -080095#include "src/core/lib/gprpp/ref_counted_ptr.h"
Craig Tiller2400bf52017-02-09 16:25:19 -080096#include "src/core/lib/iomgr/combiner.h"
David Garcia Quintas98da61b2016-10-29 08:46:31 +020097#include "src/core/lib/iomgr/sockaddr.h"
David Garcia Quintas3fb8f732016-06-15 22:53:08 -070098#include "src/core/lib/iomgr/sockaddr_utils.h"
David Garcia Quintas98da61b2016-10-29 08:46:31 +020099#include "src/core/lib/iomgr/timer.h"
David Garcia Quintas01291502017-02-07 13:26:41 -0800100#include "src/core/lib/slice/slice_hash_table.h"
Craig Tiller18b4ba32016-11-09 15:23:42 -0800101#include "src/core/lib/slice/slice_internal.h"
Craig Tiller0f310802016-10-26 16:25:56 -0700102#include "src/core/lib/slice/slice_string_helpers.h"
David Garcia Quintas3fb8f732016-06-15 22:53:08 -0700103#include "src/core/lib/surface/call.h"
104#include "src/core/lib/surface/channel.h"
Mark D. Roth09e458c2017-05-02 08:13:26 -0700105#include "src/core/lib/surface/channel_init.h"
David Garcia Quintas331b9c02016-09-12 18:37:05 -0700106#include "src/core/lib/transport/static_metadata.h"
David Garcia Quintas3fb8f732016-06-15 22:53:08 -0700107
David Garcia Quintas1edfb952016-11-22 17:15:34 -0800108#define GRPC_GRPCLB_INITIAL_CONNECT_BACKOFF_SECONDS 1
109#define GRPC_GRPCLB_RECONNECT_BACKOFF_MULTIPLIER 1.6
110#define GRPC_GRPCLB_RECONNECT_MAX_BACKOFF_SECONDS 120
111#define GRPC_GRPCLB_RECONNECT_JITTER 0.2
Juanli Shenfe408152017-09-27 12:27:20 -0700112#define GRPC_GRPCLB_DEFAULT_FALLBACK_TIMEOUT_MS 10000
David Garcia Quintas98da61b2016-10-29 08:46:31 +0200113
Mark D. Rothc8875492018-02-20 08:33:48 -0800114namespace grpc_core {
David Garcia Quintas3fb8f732016-06-15 22:53:08 -0700115
Mark D. Rothc8875492018-02-20 08:33:48 -0800116TraceFlag grpc_lb_glb_trace(false, "glb");
David Garcia Quintas3fb8f732016-06-15 22:53:08 -0700117
Vijay Pai849bd732018-01-02 23:30:47 +0000118namespace {
Mark D. Rothc0febd32018-01-09 10:25:24 -0800119
Mark D. Rothc8875492018-02-20 08:33:48 -0800120class GrpcLb : public LoadBalancingPolicy {
121 public:
122 GrpcLb(const grpc_lb_addresses* addresses, const Args& args);
123
124 void UpdateLocked(const grpc_channel_args& args) override;
125 bool PickLocked(PickState* pick) override;
126 void CancelPickLocked(PickState* pick, grpc_error* error) override;
127 void CancelMatchingPicksLocked(uint32_t initial_metadata_flags_mask,
128 uint32_t initial_metadata_flags_eq,
129 grpc_error* error) override;
130 void NotifyOnStateChangeLocked(grpc_connectivity_state* state,
131 grpc_closure* closure) override;
132 grpc_connectivity_state CheckConnectivityLocked(
133 grpc_error** connectivity_error) override;
134 void HandOffPendingPicksLocked(LoadBalancingPolicy* new_policy) override;
135 void PingOneLocked(grpc_closure* on_initiate, grpc_closure* on_ack) override;
136 void ExitIdleLocked() override;
137
138 private:
139 /// Linked list of pending pick requests. It stores all information needed to
140 /// eventually call (Round Robin's) pick() on them. They mainly stay pending
141 /// waiting for the RR policy to be created.
142 ///
143 /// Note that when a pick is sent to the RR policy, we inject our own
144 /// on_complete callback, so that we can intercept the result before
145 /// invoking the original on_complete callback. This allows us to set the
146 /// LB token metadata and add client_stats to the call context.
147 /// See \a pending_pick_complete() for details.
148 struct PendingPick {
149 // The grpclb instance that created the wrapping. This instance is not
150 // owned; reference counts are untouched. It's used only for logging
151 // purposes.
152 GrpcLb* grpclb_policy;
153 // The original pick.
154 PickState* pick;
155 // Our on_complete closure and the original one.
156 grpc_closure on_complete;
157 grpc_closure* original_on_complete;
158 // The LB token associated with the pick. This is set via user_data in
159 // the pick.
160 grpc_mdelem lb_token;
161 // Stats for client-side load reporting. Note that this holds a
162 // reference, which must be either passed on via context or unreffed.
163 grpc_grpclb_client_stats* client_stats = nullptr;
164 // 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
188 grpc_grpclb_client_stats* client_stats() const { return client_stats_; }
189 bool seen_initial_response() const { return seen_initial_response_; }
190
191 private:
192 ~BalancerCallState();
193
194 GrpcLb* grpclb_policy() const {
Vijay Pai7fed69b2018-03-05 09:58:05 -0800195 return static_cast<GrpcLb*>(grpclb_policy_.get());
Mark D. Rothc8875492018-02-20 08:33:48 -0800196 }
197
198 void ScheduleNextClientLoadReportLocked();
199 void SendClientLoadReportLocked();
200
201 static bool LoadReportCountersAreZero(grpc_grpclb_request* request);
202
203 static void MaybeSendClientLoadReportLocked(void* arg, grpc_error* error);
204 static void ClientLoadReportDoneLocked(void* arg, grpc_error* error);
205 static void OnInitialRequestSentLocked(void* arg, grpc_error* error);
206 static void OnBalancerMessageReceivedLocked(void* arg, grpc_error* error);
207 static void OnBalancerStatusReceivedLocked(void* arg, grpc_error* error);
208
209 // The owning LB policy.
210 RefCountedPtr<LoadBalancingPolicy> grpclb_policy_;
211
212 // The streaming call to the LB server. Always non-NULL.
213 grpc_call* lb_call_ = nullptr;
214
215 // recv_initial_metadata
216 grpc_metadata_array lb_initial_metadata_recv_;
217
218 // send_message
219 grpc_byte_buffer* send_message_payload_ = nullptr;
220 grpc_closure lb_on_initial_request_sent_;
221
222 // recv_message
223 grpc_byte_buffer* recv_message_payload_ = nullptr;
224 grpc_closure lb_on_balancer_message_received_;
225 bool seen_initial_response_ = false;
226
227 // recv_trailing_metadata
228 grpc_closure lb_on_balancer_status_received_;
229 grpc_metadata_array lb_trailing_metadata_recv_;
230 grpc_status_code lb_call_status_;
231 grpc_slice lb_call_status_details_;
232
233 // The stats for client-side load reporting associated with this LB call.
234 // Created after the first serverlist is received.
235 grpc_grpclb_client_stats* client_stats_ = nullptr;
236 grpc_millis client_stats_report_interval_ = 0;
237 grpc_timer client_load_report_timer_;
238 bool client_load_report_timer_callback_pending_ = false;
239 bool last_client_load_report_counters_were_zero_ = false;
240 bool client_load_report_is_due_ = false;
241 // The closure used for either the load report timer or the callback for
242 // completion of sending the load report.
243 grpc_closure client_load_report_closure_;
244 };
245
246 ~GrpcLb();
247
248 void ShutdownLocked() override;
249
250 // Helper function used in ctor and UpdateLocked().
251 void ProcessChannelArgsLocked(const grpc_channel_args& args);
252
253 // Methods for dealing with the balancer channel and call.
254 void StartPickingLocked();
255 void StartBalancerCallLocked();
256 static void OnFallbackTimerLocked(void* arg, grpc_error* error);
257 void StartBalancerCallRetryTimerLocked();
258 static void OnBalancerCallRetryTimerLocked(void* arg, grpc_error* error);
259 static void OnBalancerChannelConnectivityChangedLocked(void* arg,
260 grpc_error* error);
261
262 // Pending pick methods.
263 static void PendingPickSetMetadataAndContext(PendingPick* pp);
264 PendingPick* PendingPickCreate(PickState* pick);
265 void AddPendingPick(PendingPick* pp);
266 static void OnPendingPickComplete(void* arg, grpc_error* error);
267
268 // Pending ping methods.
269 void AddPendingPing(grpc_closure* on_initiate, grpc_closure* on_ack);
270
271 // Methods for dealing with the RR policy.
272 void CreateOrUpdateRoundRobinPolicyLocked();
273 grpc_channel_args* CreateRoundRobinPolicyArgsLocked();
274 void CreateRoundRobinPolicyLocked(const Args& args);
275 bool PickFromRoundRobinPolicyLocked(bool force_async, PendingPick* pp);
276 void UpdateConnectivityStateFromRoundRobinPolicyLocked(
277 grpc_error* rr_state_error);
278 static void OnRoundRobinConnectivityChangedLocked(void* arg,
279 grpc_error* error);
280 static void OnRoundRobinRequestReresolutionLocked(void* arg,
281 grpc_error* error);
282
283 // Who the client is trying to communicate with.
284 const char* server_name_ = nullptr;
285
286 // Current channel args from the resolver.
287 grpc_channel_args* args_ = nullptr;
288
289 // Internal state.
290 bool started_picking_ = false;
291 bool shutting_down_ = false;
292 grpc_connectivity_state_tracker state_tracker_;
293
294 // The channel for communicating with the LB server.
295 grpc_channel* lb_channel_ = nullptr;
296 grpc_connectivity_state lb_channel_connectivity_;
297 grpc_closure lb_channel_on_connectivity_changed_;
298 // Are we already watching the LB channel's connectivity?
299 bool watching_lb_channel_ = false;
300 // Response generator to inject address updates into lb_channel_.
301 RefCountedPtr<FakeResolverResponseGenerator> response_generator_;
302
303 // The data associated with the current LB call. It holds a ref to this LB
304 // policy. It's initialized every time we query for backends. It's reset to
305 // NULL whenever the current LB call is no longer needed (e.g., the LB policy
306 // is shutting down, or the LB call has ended). A non-NULL lb_calld_ always
307 // contains a non-NULL lb_call_.
308 OrphanablePtr<BalancerCallState> lb_calld_;
309 // Timeout in milliseconds for the LB call. 0 means no deadline.
310 int lb_call_timeout_ms_ = 0;
311 // Balancer call retry state.
312 BackOff lb_call_backoff_;
313 bool retry_timer_callback_pending_ = false;
314 grpc_timer lb_call_retry_timer_;
315 grpc_closure lb_on_call_retry_;
316
317 // The deserialized response from the balancer. May be nullptr until one
318 // such response has arrived.
319 grpc_grpclb_serverlist* serverlist_ = nullptr;
320 // Index into serverlist for next pick.
321 // If the server at this index is a drop, we return a drop.
322 // Otherwise, we delegate to the RR policy.
323 size_t serverlist_index_ = 0;
324
325 // Timeout in milliseconds for before using fallback backend addresses.
326 // 0 means not using fallback.
327 int lb_fallback_timeout_ms_ = 0;
328 // The backend addresses from the resolver.
329 grpc_lb_addresses* fallback_backend_addresses_ = nullptr;
330 // Fallback timer.
331 bool fallback_timer_callback_pending_ = false;
332 grpc_timer lb_fallback_timer_;
333 grpc_closure lb_on_fallback_;
334
335 // Pending picks and pings that are waiting on the RR policy's connectivity.
336 PendingPick* pending_picks_ = nullptr;
337 PendingPing* pending_pings_ = nullptr;
338
339 // The RR policy to use for the backends.
340 OrphanablePtr<LoadBalancingPolicy> rr_policy_;
341 grpc_connectivity_state rr_connectivity_state_;
342 grpc_closure on_rr_connectivity_changed_;
343 grpc_closure on_rr_request_reresolution_;
Vijay Pai849bd732018-01-02 23:30:47 +0000344};
Mark D. Rothc0febd32018-01-09 10:25:24 -0800345
Mark D. Rothc8875492018-02-20 08:33:48 -0800346//
347// serverlist parsing code
348//
Mark D. Rothc0febd32018-01-09 10:25:24 -0800349
Mark D. Rothc8875492018-02-20 08:33:48 -0800350// vtable for LB tokens in grpc_lb_addresses
351void* lb_token_copy(void* token) {
352 return token == nullptr
353 ? nullptr
354 : (void*)GRPC_MDELEM_REF(grpc_mdelem{(uintptr_t)token}).payload;
355}
356void lb_token_destroy(void* token) {
357 if (token != nullptr) {
358 GRPC_MDELEM_UNREF(grpc_mdelem{(uintptr_t)token});
Juanli Shen8e4c9d32018-01-23 16:26:39 -0800359 }
360}
Mark D. Rothc8875492018-02-20 08:33:48 -0800361int lb_token_cmp(void* token1, void* token2) {
362 if (token1 > token2) return 1;
363 if (token1 < token2) return -1;
364 return 0;
Juanli Shen8e4c9d32018-01-23 16:26:39 -0800365}
Mark D. Rothc8875492018-02-20 08:33:48 -0800366const grpc_lb_user_data_vtable lb_token_vtable = {
367 lb_token_copy, lb_token_destroy, lb_token_cmp};
Juanli Shen8e4c9d32018-01-23 16:26:39 -0800368
Mark D. Rothc8875492018-02-20 08:33:48 -0800369// Returns the backend addresses extracted from the given addresses.
370grpc_lb_addresses* ExtractBackendAddresses(const grpc_lb_addresses* addresses) {
371 // First pass: count the number of backend addresses.
372 size_t num_backends = 0;
373 for (size_t i = 0; i < addresses->num_addresses; ++i) {
374 if (!addresses->addresses[i].is_balancer) {
375 ++num_backends;
Mark D. Roth83d5cd62018-01-11 08:56:53 -0800376 }
Mark D. Rothc0febd32018-01-09 10:25:24 -0800377 }
Mark D. Rothc8875492018-02-20 08:33:48 -0800378 // Second pass: actually populate the addresses and (empty) LB tokens.
379 grpc_lb_addresses* backend_addresses =
380 grpc_lb_addresses_create(num_backends, &lb_token_vtable);
381 size_t num_copied = 0;
382 for (size_t i = 0; i < addresses->num_addresses; ++i) {
383 if (addresses->addresses[i].is_balancer) continue;
384 const grpc_resolved_address* addr = &addresses->addresses[i].address;
385 grpc_lb_addresses_set_address(backend_addresses, num_copied, &addr->addr,
386 addr->len, false /* is_balancer */,
387 nullptr /* balancer_name */,
388 (void*)GRPC_MDELEM_LB_TOKEN_EMPTY.payload);
389 ++num_copied;
390 }
391 return backend_addresses;
Mark D. Rothc0febd32018-01-09 10:25:24 -0800392}
393
Mark D. Rothc8875492018-02-20 08:33:48 -0800394bool IsServerValid(const grpc_grpclb_server* server, size_t idx, bool log) {
Mark D. Rothe7751802017-07-27 12:31:45 -0700395 if (server->drop) return false;
Craig Tillerbaa14a92017-11-03 09:09:36 -0700396 const grpc_grpclb_ip_address* ip = &server->ip_address;
David Garcia Quintas35c2aba2016-09-13 15:28:09 -0700397 if (server->port >> 16 != 0) {
398 if (log) {
399 gpr_log(GPR_ERROR,
Jan Tattermusch2b398082016-10-07 14:40:30 +0200400 "Invalid port '%d' at index %lu of serverlist. Ignoring.",
Mark D. Rothc8875492018-02-20 08:33:48 -0800401 server->port, (unsigned long)idx);
David Garcia Quintas35c2aba2016-09-13 15:28:09 -0700402 }
403 return false;
404 }
David Garcia Quintas35c2aba2016-09-13 15:28:09 -0700405 if (ip->size != 4 && ip->size != 16) {
406 if (log) {
407 gpr_log(GPR_ERROR,
Jan Tattermusch2b398082016-10-07 14:40:30 +0200408 "Expected IP to be 4 or 16 bytes, got %d at index %lu of "
David Garcia Quintas35c2aba2016-09-13 15:28:09 -0700409 "serverlist. Ignoring",
Mark D. Rothc8875492018-02-20 08:33:48 -0800410 ip->size, (unsigned long)idx);
David Garcia Quintas35c2aba2016-09-13 15:28:09 -0700411 }
412 return false;
413 }
414 return true;
415}
416
Mark D. Rothc8875492018-02-20 08:33:48 -0800417void ParseServer(const grpc_grpclb_server* server,
418 grpc_resolved_address* addr) {
Mark D. Rothd7389b42017-05-17 12:22:17 -0700419 memset(addr, 0, sizeof(*addr));
Mark D. Rothe7751802017-07-27 12:31:45 -0700420 if (server->drop) return;
kpayson64539f5062018-03-12 19:16:30 -0700421 const uint16_t netorder_port = grpc_htons((uint16_t)server->port);
David Garcia Quintas7ec29132016-11-01 04:09:05 +0100422 /* the addresses are given in binary format (a in(6)_addr struct) in
423 * server->ip_address.bytes. */
Craig Tillerbaa14a92017-11-03 09:09:36 -0700424 const grpc_grpclb_ip_address* ip = &server->ip_address;
David Garcia Quintas7ec29132016-11-01 04:09:05 +0100425 if (ip->size == 4) {
Yash Tibrewal44a15882018-03-14 18:41:33 -0700426 addr->len = static_cast<socklen_t>(sizeof(grpc_sockaddr_in));
kpayson64539f5062018-03-12 19:16:30 -0700427 grpc_sockaddr_in* addr4 = reinterpret_cast<grpc_sockaddr_in*>(&addr->addr);
428 addr4->sin_family = GRPC_AF_INET;
David Garcia Quintas7ec29132016-11-01 04:09:05 +0100429 memcpy(&addr4->sin_addr, ip->bytes, ip->size);
430 addr4->sin_port = netorder_port;
431 } else if (ip->size == 16) {
Yash Tibrewal44a15882018-03-14 18:41:33 -0700432 addr->len = static_cast<socklen_t>(sizeof(grpc_sockaddr_in6));
kpayson64539f5062018-03-12 19:16:30 -0700433 grpc_sockaddr_in6* addr6 = (grpc_sockaddr_in6*)&addr->addr;
434 addr6->sin6_family = GRPC_AF_INET6;
David Garcia Quintas7ec29132016-11-01 04:09:05 +0100435 memcpy(&addr6->sin6_addr, ip->bytes, ip->size);
436 addr6->sin6_port = netorder_port;
437 }
438}
439
Mark D. Rothc8875492018-02-20 08:33:48 -0800440// Returns addresses extracted from \a serverlist.
441grpc_lb_addresses* ProcessServerlist(const grpc_grpclb_serverlist* serverlist) {
David Garcia Quintas331b9c02016-09-12 18:37:05 -0700442 size_t num_valid = 0;
443 /* first pass: count how many are valid in order to allocate the necessary
444 * memory in a single block */
445 for (size_t i = 0; i < serverlist->num_servers; ++i) {
Mark D. Rothc8875492018-02-20 08:33:48 -0800446 if (IsServerValid(serverlist->servers[i], i, true)) ++num_valid;
David Garcia Quintasb8b384a2016-08-23 21:10:29 -0700447 }
Craig Tillerbaa14a92017-11-03 09:09:36 -0700448 grpc_lb_addresses* lb_addresses =
Mark D. Roth16883a32016-10-21 10:30:58 -0700449 grpc_lb_addresses_create(num_valid, &lb_token_vtable);
David Garcia Quintas331b9c02016-09-12 18:37:05 -0700450 /* second pass: actually populate the addresses and LB tokens (aka user data
David Garcia Quintas35c2aba2016-09-13 15:28:09 -0700451 * to the outside world) to be read by the RR policy during its creation.
452 * Given that the validity tests are very cheap, they are performed again
453 * instead of marking the valid ones during the first pass, as this would
454 * incurr in an allocation due to the arbitrary number of server */
David Garcia Quintasf47d6fb2016-09-14 12:59:17 -0700455 size_t addr_idx = 0;
456 for (size_t sl_idx = 0; sl_idx < serverlist->num_servers; ++sl_idx) {
Craig Tillerbaa14a92017-11-03 09:09:36 -0700457 const grpc_grpclb_server* server = serverlist->servers[sl_idx];
Mark D. Rothc8875492018-02-20 08:33:48 -0800458 if (!IsServerValid(serverlist->servers[sl_idx], sl_idx, false)) continue;
David Garcia Quintasc22c65b2017-07-25 14:22:20 -0700459 GPR_ASSERT(addr_idx < num_valid);
David Garcia Quintas331b9c02016-09-12 18:37:05 -0700460 /* address processing */
Mark D. Rothc5c38782016-09-16 08:51:01 -0700461 grpc_resolved_address addr;
Mark D. Rothc8875492018-02-20 08:33:48 -0800462 ParseServer(server, &addr);
David Garcia Quintasf47d6fb2016-09-14 12:59:17 -0700463 /* lb token processing */
Craig Tillerbaa14a92017-11-03 09:09:36 -0700464 void* user_data;
David Garcia Quintasf47d6fb2016-09-14 12:59:17 -0700465 if (server->has_load_balance_token) {
David Garcia Quintas0baf1dc2016-10-28 04:44:01 +0200466 const size_t lb_token_max_length =
467 GPR_ARRAY_SIZE(server->load_balance_token);
468 const size_t lb_token_length =
469 strnlen(server->load_balance_token, lb_token_max_length);
Craig Tiller7c70b6c2017-01-23 07:48:42 -0800470 grpc_slice lb_token_mdstr = grpc_slice_from_copied_buffer(
471 server->load_balance_token, lb_token_length);
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800472 user_data =
473 (void*)grpc_mdelem_from_slices(GRPC_MDSTR_LB_TOKEN, lb_token_mdstr)
474 .payload;
David Garcia Quintasf47d6fb2016-09-14 12:59:17 -0700475 } else {
Craig Tillerbaa14a92017-11-03 09:09:36 -0700476 char* uri = grpc_sockaddr_to_uri(&addr);
David Garcia Quintas850cbaa2016-11-15 15:13:35 -0800477 gpr_log(GPR_INFO,
David Garcia Quintasf47d6fb2016-09-14 12:59:17 -0700478 "Missing LB token for backend address '%s'. The empty token will "
479 "be used instead",
David Garcia Quintas850cbaa2016-11-15 15:13:35 -0800480 uri);
481 gpr_free(uri);
Craig Tillerbaa14a92017-11-03 09:09:36 -0700482 user_data = (void*)GRPC_MDELEM_LB_TOKEN_EMPTY.payload;
David Garcia Quintasf47d6fb2016-09-14 12:59:17 -0700483 }
Mark D. Roth64f1f8d2016-09-16 09:00:09 -0700484 grpc_lb_addresses_set_address(lb_addresses, addr_idx, &addr.addr, addr.len,
485 false /* is_balancer */,
Noah Eisen882dfed2017-11-14 14:58:20 -0800486 nullptr /* balancer_name */, user_data);
David Garcia Quintasf47d6fb2016-09-14 12:59:17 -0700487 ++addr_idx;
David Garcia Quintas331b9c02016-09-12 18:37:05 -0700488 }
David Garcia Quintasf47d6fb2016-09-14 12:59:17 -0700489 GPR_ASSERT(addr_idx == num_valid);
Mark D. Rothc5c38782016-09-16 08:51:01 -0700490 return lb_addresses;
491}
492
Mark D. Rothc8875492018-02-20 08:33:48 -0800493//
494// GrpcLb::BalancerCallState
495//
496
497GrpcLb::BalancerCallState::BalancerCallState(
498 RefCountedPtr<LoadBalancingPolicy> parent_grpclb_policy)
499 : InternallyRefCountedWithTracing<BalancerCallState>(&grpc_lb_glb_trace),
500 grpclb_policy_(std::move(parent_grpclb_policy)) {
501 GPR_ASSERT(grpclb_policy_ != nullptr);
502 GPR_ASSERT(!grpclb_policy()->shutting_down_);
503 // Init the LB call. Note that the LB call will progress every time there's
504 // activity in grpclb_policy_->interested_parties(), which is comprised of
505 // the polling entities from client_channel.
506 GPR_ASSERT(grpclb_policy()->server_name_ != nullptr);
507 GPR_ASSERT(grpclb_policy()->server_name_[0] != '\0');
David Garcia Quintasc7c0d692018-03-10 17:27:15 -0800508 const grpc_millis deadline =
Mark D. Rothc8875492018-02-20 08:33:48 -0800509 grpclb_policy()->lb_call_timeout_ms_ == 0
510 ? GRPC_MILLIS_INF_FUTURE
511 : ExecCtx::Get()->Now() + grpclb_policy()->lb_call_timeout_ms_;
512 lb_call_ = grpc_channel_create_pollset_set_call(
513 grpclb_policy()->lb_channel_, nullptr, GRPC_PROPAGATE_DEFAULTS,
514 grpclb_policy_->interested_parties(),
515 GRPC_MDSTR_SLASH_GRPC_DOT_LB_DOT_V1_DOT_LOADBALANCER_SLASH_BALANCELOAD,
David Garcia Quintasc7c0d692018-03-10 17:27:15 -0800516 nullptr, deadline, nullptr);
Mark D. Rothc8875492018-02-20 08:33:48 -0800517 // Init the LB call request payload.
518 grpc_grpclb_request* request =
519 grpc_grpclb_request_create(grpclb_policy()->server_name_);
520 grpc_slice request_payload_slice = grpc_grpclb_request_encode(request);
521 send_message_payload_ =
522 grpc_raw_byte_buffer_create(&request_payload_slice, 1);
523 grpc_slice_unref_internal(request_payload_slice);
524 grpc_grpclb_request_destroy(request);
525 // Init other data associated with the LB call.
526 grpc_metadata_array_init(&lb_initial_metadata_recv_);
527 grpc_metadata_array_init(&lb_trailing_metadata_recv_);
528 GRPC_CLOSURE_INIT(&lb_on_initial_request_sent_, OnInitialRequestSentLocked,
529 this, grpc_combiner_scheduler(grpclb_policy()->combiner()));
530 GRPC_CLOSURE_INIT(&lb_on_balancer_message_received_,
531 OnBalancerMessageReceivedLocked, this,
532 grpc_combiner_scheduler(grpclb_policy()->combiner()));
533 GRPC_CLOSURE_INIT(&lb_on_balancer_status_received_,
534 OnBalancerStatusReceivedLocked, this,
535 grpc_combiner_scheduler(grpclb_policy()->combiner()));
Juanli Shenfe408152017-09-27 12:27:20 -0700536}
537
Mark D. Rothc8875492018-02-20 08:33:48 -0800538GrpcLb::BalancerCallState::~BalancerCallState() {
539 GPR_ASSERT(lb_call_ != nullptr);
540 grpc_call_unref(lb_call_);
541 grpc_metadata_array_destroy(&lb_initial_metadata_recv_);
542 grpc_metadata_array_destroy(&lb_trailing_metadata_recv_);
543 grpc_byte_buffer_destroy(send_message_payload_);
544 grpc_byte_buffer_destroy(recv_message_payload_);
545 grpc_slice_unref_internal(lb_call_status_details_);
546 if (client_stats_ != nullptr) {
547 grpc_grpclb_client_stats_unref(client_stats_);
548 }
549}
550
551void GrpcLb::BalancerCallState::Orphan() {
552 GPR_ASSERT(lb_call_ != nullptr);
553 // If we are here because grpclb_policy wants to cancel the call,
554 // lb_on_balancer_status_received_ will complete the cancellation and clean
555 // up. Otherwise, we are here because grpclb_policy has to orphan a failed
556 // call, then the following cancellation will be a no-op.
557 grpc_call_cancel(lb_call_, nullptr);
558 if (client_load_report_timer_callback_pending_) {
559 grpc_timer_cancel(&client_load_report_timer_);
560 }
561 // Note that the initial ref is hold by lb_on_balancer_status_received_
562 // instead of the caller of this function. So the corresponding unref happens
563 // in lb_on_balancer_status_received_ instead of here.
564}
565
566void GrpcLb::BalancerCallState::StartQuery() {
567 GPR_ASSERT(lb_call_ != nullptr);
568 if (grpc_lb_glb_trace.enabled()) {
569 gpr_log(GPR_INFO,
570 "[grpclb %p] Starting LB call (lb_calld: %p, lb_call: %p)",
571 grpclb_policy_.get(), this, lb_call_);
572 }
573 // Create the ops.
574 grpc_call_error call_error;
575 grpc_op ops[3];
576 memset(ops, 0, sizeof(ops));
577 // Op: send initial metadata.
578 grpc_op* op = ops;
579 op->op = GRPC_OP_SEND_INITIAL_METADATA;
580 op->data.send_initial_metadata.count = 0;
581 op->flags = 0;
582 op->reserved = nullptr;
583 op++;
584 // Op: send request message.
585 GPR_ASSERT(send_message_payload_ != nullptr);
586 op->op = GRPC_OP_SEND_MESSAGE;
587 op->data.send_message.send_message = send_message_payload_;
588 op->flags = 0;
589 op->reserved = nullptr;
590 op++;
591 // TODO(roth): We currently track this ref manually. Once the
592 // ClosureRef API is ready, we should pass the RefCountedPtr<> along
593 // with the callback.
594 auto self = Ref(DEBUG_LOCATION, "on_initial_request_sent");
595 self.release();
596 call_error = grpc_call_start_batch_and_execute(
597 lb_call_, ops, (size_t)(op - ops), &lb_on_initial_request_sent_);
598 GPR_ASSERT(GRPC_CALL_OK == call_error);
599 // Op: recv initial metadata.
600 op = ops;
601 op->op = GRPC_OP_RECV_INITIAL_METADATA;
602 op->data.recv_initial_metadata.recv_initial_metadata =
603 &lb_initial_metadata_recv_;
604 op->flags = 0;
605 op->reserved = nullptr;
606 op++;
607 // Op: recv response.
608 op->op = GRPC_OP_RECV_MESSAGE;
609 op->data.recv_message.recv_message = &recv_message_payload_;
610 op->flags = 0;
611 op->reserved = nullptr;
612 op++;
613 // TODO(roth): We currently track this ref manually. Once the
614 // ClosureRef API is ready, we should pass the RefCountedPtr<> along
615 // with the callback.
616 self = Ref(DEBUG_LOCATION, "on_message_received");
617 self.release();
618 call_error = grpc_call_start_batch_and_execute(
619 lb_call_, ops, (size_t)(op - ops), &lb_on_balancer_message_received_);
620 GPR_ASSERT(GRPC_CALL_OK == call_error);
621 // Op: recv server status.
622 op = ops;
623 op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;
624 op->data.recv_status_on_client.trailing_metadata =
625 &lb_trailing_metadata_recv_;
626 op->data.recv_status_on_client.status = &lb_call_status_;
627 op->data.recv_status_on_client.status_details = &lb_call_status_details_;
628 op->flags = 0;
629 op->reserved = nullptr;
630 op++;
631 // This callback signals the end of the LB call, so it relies on the initial
632 // ref instead of a new ref. When it's invoked, it's the initial ref that is
633 // unreffed.
634 call_error = grpc_call_start_batch_and_execute(
635 lb_call_, ops, (size_t)(op - ops), &lb_on_balancer_status_received_);
636 GPR_ASSERT(GRPC_CALL_OK == call_error);
637};
638
639void GrpcLb::BalancerCallState::ScheduleNextClientLoadReportLocked() {
640 const grpc_millis next_client_load_report_time =
641 ExecCtx::Get()->Now() + client_stats_report_interval_;
642 GRPC_CLOSURE_INIT(&client_load_report_closure_,
643 MaybeSendClientLoadReportLocked, this,
644 grpc_combiner_scheduler(grpclb_policy()->combiner()));
645 grpc_timer_init(&client_load_report_timer_, next_client_load_report_time,
646 &client_load_report_closure_);
647 client_load_report_timer_callback_pending_ = true;
648}
649
650void GrpcLb::BalancerCallState::MaybeSendClientLoadReportLocked(
651 void* arg, grpc_error* error) {
Vijay Pai7fed69b2018-03-05 09:58:05 -0800652 BalancerCallState* lb_calld = static_cast<BalancerCallState*>(arg);
Mark D. Rothc8875492018-02-20 08:33:48 -0800653 GrpcLb* grpclb_policy = lb_calld->grpclb_policy();
654 lb_calld->client_load_report_timer_callback_pending_ = false;
655 if (error != GRPC_ERROR_NONE || lb_calld != grpclb_policy->lb_calld_.get()) {
656 lb_calld->Unref(DEBUG_LOCATION, "client_load_report");
657 return;
658 }
659 // If we've already sent the initial request, then we can go ahead and send
660 // the load report. Otherwise, we need to wait until the initial request has
661 // been sent to send this (see OnInitialRequestSentLocked()).
662 if (lb_calld->send_message_payload_ == nullptr) {
663 lb_calld->SendClientLoadReportLocked();
664 } else {
665 lb_calld->client_load_report_is_due_ = true;
666 }
667}
668
669bool GrpcLb::BalancerCallState::LoadReportCountersAreZero(
670 grpc_grpclb_request* request) {
671 grpc_grpclb_dropped_call_counts* drop_entries =
672 static_cast<grpc_grpclb_dropped_call_counts*>(
673 request->client_stats.calls_finished_with_drop.arg);
674 return request->client_stats.num_calls_started == 0 &&
675 request->client_stats.num_calls_finished == 0 &&
676 request->client_stats.num_calls_finished_with_client_failed_to_send ==
677 0 &&
678 request->client_stats.num_calls_finished_known_received == 0 &&
679 (drop_entries == nullptr || drop_entries->num_entries == 0);
680}
681
682void GrpcLb::BalancerCallState::SendClientLoadReportLocked() {
683 // Construct message payload.
684 GPR_ASSERT(send_message_payload_ == nullptr);
685 grpc_grpclb_request* request =
686 grpc_grpclb_load_report_request_create_locked(client_stats_);
687 // Skip client load report if the counters were all zero in the last
688 // report and they are still zero in this one.
689 if (LoadReportCountersAreZero(request)) {
690 if (last_client_load_report_counters_were_zero_) {
691 grpc_grpclb_request_destroy(request);
692 ScheduleNextClientLoadReportLocked();
693 return;
694 }
695 last_client_load_report_counters_were_zero_ = true;
696 } else {
697 last_client_load_report_counters_were_zero_ = false;
698 }
699 grpc_slice request_payload_slice = grpc_grpclb_request_encode(request);
700 send_message_payload_ =
701 grpc_raw_byte_buffer_create(&request_payload_slice, 1);
702 grpc_slice_unref_internal(request_payload_slice);
703 grpc_grpclb_request_destroy(request);
704 // Send the report.
705 grpc_op op;
706 memset(&op, 0, sizeof(op));
707 op.op = GRPC_OP_SEND_MESSAGE;
708 op.data.send_message.send_message = send_message_payload_;
709 GRPC_CLOSURE_INIT(&client_load_report_closure_, ClientLoadReportDoneLocked,
710 this, grpc_combiner_scheduler(grpclb_policy()->combiner()));
711 grpc_call_error call_error = grpc_call_start_batch_and_execute(
712 lb_call_, &op, 1, &client_load_report_closure_);
713 if (call_error != GRPC_CALL_OK) {
714 gpr_log(GPR_ERROR, "[grpclb %p] call_error=%d", grpclb_policy_.get(),
715 call_error);
716 GPR_ASSERT(GRPC_CALL_OK == call_error);
717 }
718}
719
720void GrpcLb::BalancerCallState::ClientLoadReportDoneLocked(void* arg,
721 grpc_error* error) {
Vijay Pai7fed69b2018-03-05 09:58:05 -0800722 BalancerCallState* lb_calld = static_cast<BalancerCallState*>(arg);
Mark D. Rothc8875492018-02-20 08:33:48 -0800723 GrpcLb* grpclb_policy = lb_calld->grpclb_policy();
724 grpc_byte_buffer_destroy(lb_calld->send_message_payload_);
725 lb_calld->send_message_payload_ = nullptr;
726 if (error != GRPC_ERROR_NONE || lb_calld != grpclb_policy->lb_calld_.get()) {
727 lb_calld->Unref(DEBUG_LOCATION, "client_load_report");
728 return;
729 }
730 lb_calld->ScheduleNextClientLoadReportLocked();
731}
732
733void GrpcLb::BalancerCallState::OnInitialRequestSentLocked(void* arg,
734 grpc_error* error) {
Vijay Pai7fed69b2018-03-05 09:58:05 -0800735 BalancerCallState* lb_calld = static_cast<BalancerCallState*>(arg);
Mark D. Rothc8875492018-02-20 08:33:48 -0800736 grpc_byte_buffer_destroy(lb_calld->send_message_payload_);
737 lb_calld->send_message_payload_ = nullptr;
738 // If we attempted to send a client load report before the initial request was
739 // sent (and this lb_calld is still in use), send the load report now.
740 if (lb_calld->client_load_report_is_due_ &&
741 lb_calld == lb_calld->grpclb_policy()->lb_calld_.get()) {
742 lb_calld->SendClientLoadReportLocked();
743 lb_calld->client_load_report_is_due_ = false;
744 }
745 lb_calld->Unref(DEBUG_LOCATION, "on_initial_request_sent");
746}
747
748void GrpcLb::BalancerCallState::OnBalancerMessageReceivedLocked(
749 void* arg, grpc_error* error) {
Vijay Pai7fed69b2018-03-05 09:58:05 -0800750 BalancerCallState* lb_calld = static_cast<BalancerCallState*>(arg);
Mark D. Rothc8875492018-02-20 08:33:48 -0800751 GrpcLb* grpclb_policy = lb_calld->grpclb_policy();
752 // Empty payload means the LB call was cancelled.
753 if (lb_calld != grpclb_policy->lb_calld_.get() ||
754 lb_calld->recv_message_payload_ == nullptr) {
755 lb_calld->Unref(DEBUG_LOCATION, "on_message_received");
756 return;
757 }
758 grpc_byte_buffer_reader bbr;
759 grpc_byte_buffer_reader_init(&bbr, lb_calld->recv_message_payload_);
760 grpc_slice response_slice = grpc_byte_buffer_reader_readall(&bbr);
761 grpc_byte_buffer_reader_destroy(&bbr);
762 grpc_byte_buffer_destroy(lb_calld->recv_message_payload_);
763 lb_calld->recv_message_payload_ = nullptr;
764 grpc_grpclb_initial_response* initial_response;
765 grpc_grpclb_serverlist* serverlist;
766 if (!lb_calld->seen_initial_response_ &&
767 (initial_response = grpc_grpclb_initial_response_parse(response_slice)) !=
768 nullptr) {
769 // Have NOT seen initial response, look for initial response.
770 if (initial_response->has_client_stats_report_interval) {
771 lb_calld->client_stats_report_interval_ = GPR_MAX(
772 GPR_MS_PER_SEC, grpc_grpclb_duration_to_millis(
773 &initial_response->client_stats_report_interval));
774 if (grpc_lb_glb_trace.enabled()) {
775 gpr_log(GPR_INFO,
776 "[grpclb %p] Received initial LB response message; "
Sree Kuchibhotla1dd12c02018-04-11 18:05:48 -0700777 "client load reporting interval = %" PRId64 " milliseconds",
Mark D. Rothc8875492018-02-20 08:33:48 -0800778 grpclb_policy, lb_calld->client_stats_report_interval_);
779 }
780 } else if (grpc_lb_glb_trace.enabled()) {
781 gpr_log(GPR_INFO,
782 "[grpclb %p] Received initial LB response message; client load "
783 "reporting NOT enabled",
784 grpclb_policy);
785 }
786 grpc_grpclb_initial_response_destroy(initial_response);
787 lb_calld->seen_initial_response_ = true;
788 } else if ((serverlist = grpc_grpclb_response_parse_serverlist(
789 response_slice)) != nullptr) {
790 // Have seen initial response, look for serverlist.
791 GPR_ASSERT(lb_calld->lb_call_ != nullptr);
792 if (grpc_lb_glb_trace.enabled()) {
793 gpr_log(GPR_INFO,
794 "[grpclb %p] Serverlist with %" PRIuPTR " servers received",
795 grpclb_policy, serverlist->num_servers);
796 for (size_t i = 0; i < serverlist->num_servers; ++i) {
797 grpc_resolved_address addr;
798 ParseServer(serverlist->servers[i], &addr);
799 char* ipport;
800 grpc_sockaddr_to_string(&ipport, &addr, false);
801 gpr_log(GPR_INFO, "[grpclb %p] Serverlist[%" PRIuPTR "]: %s",
802 grpclb_policy, i, ipport);
803 gpr_free(ipport);
804 }
805 }
806 /* update serverlist */
807 if (serverlist->num_servers > 0) {
808 // Start sending client load report only after we start using the
809 // serverlist returned from the current LB call.
810 if (lb_calld->client_stats_report_interval_ > 0 &&
811 lb_calld->client_stats_ == nullptr) {
812 lb_calld->client_stats_ = grpc_grpclb_client_stats_create();
813 // TODO(roth): We currently track this ref manually. Once the
814 // ClosureRef API is ready, we should pass the RefCountedPtr<> along
815 // with the callback.
816 auto self = lb_calld->Ref(DEBUG_LOCATION, "client_load_report");
817 self.release();
818 lb_calld->ScheduleNextClientLoadReportLocked();
819 }
820 if (grpc_grpclb_serverlist_equals(grpclb_policy->serverlist_,
821 serverlist)) {
822 if (grpc_lb_glb_trace.enabled()) {
823 gpr_log(GPR_INFO,
824 "[grpclb %p] Incoming server list identical to current, "
825 "ignoring.",
826 grpclb_policy);
827 }
828 grpc_grpclb_destroy_serverlist(serverlist);
829 } else { /* new serverlist */
830 if (grpclb_policy->serverlist_ != nullptr) {
831 /* dispose of the old serverlist */
832 grpc_grpclb_destroy_serverlist(grpclb_policy->serverlist_);
833 } else {
834 /* or dispose of the fallback */
835 grpc_lb_addresses_destroy(grpclb_policy->fallback_backend_addresses_);
836 grpclb_policy->fallback_backend_addresses_ = nullptr;
837 if (grpclb_policy->fallback_timer_callback_pending_) {
838 grpc_timer_cancel(&grpclb_policy->lb_fallback_timer_);
839 }
840 }
841 // and update the copy in the GrpcLb instance. This
842 // serverlist instance will be destroyed either upon the next
843 // update or when the GrpcLb instance is destroyed.
844 grpclb_policy->serverlist_ = serverlist;
845 grpclb_policy->serverlist_index_ = 0;
846 grpclb_policy->CreateOrUpdateRoundRobinPolicyLocked();
847 }
848 } else {
849 if (grpc_lb_glb_trace.enabled()) {
850 gpr_log(GPR_INFO, "[grpclb %p] Received empty server list, ignoring.",
851 grpclb_policy);
852 }
853 grpc_grpclb_destroy_serverlist(serverlist);
854 }
855 } else {
856 // No valid initial response or serverlist found.
857 gpr_log(GPR_ERROR,
858 "[grpclb %p] Invalid LB response received: '%s'. Ignoring.",
859 grpclb_policy,
860 grpc_dump_slice(response_slice, GPR_DUMP_ASCII | GPR_DUMP_HEX));
861 }
862 grpc_slice_unref_internal(response_slice);
863 if (!grpclb_policy->shutting_down_) {
864 // Keep listening for serverlist updates.
865 grpc_op op;
866 memset(&op, 0, sizeof(op));
867 op.op = GRPC_OP_RECV_MESSAGE;
868 op.data.recv_message.recv_message = &lb_calld->recv_message_payload_;
869 op.flags = 0;
870 op.reserved = nullptr;
871 // Reuse the "OnBalancerMessageReceivedLocked" ref taken in StartQuery().
872 const grpc_call_error call_error = grpc_call_start_batch_and_execute(
873 lb_calld->lb_call_, &op, 1,
874 &lb_calld->lb_on_balancer_message_received_);
875 GPR_ASSERT(GRPC_CALL_OK == call_error);
876 } else {
877 lb_calld->Unref(DEBUG_LOCATION, "on_message_received+grpclb_shutdown");
878 }
879}
880
881void GrpcLb::BalancerCallState::OnBalancerStatusReceivedLocked(
882 void* arg, grpc_error* error) {
Vijay Pai7fed69b2018-03-05 09:58:05 -0800883 BalancerCallState* lb_calld = static_cast<BalancerCallState*>(arg);
Mark D. Rothc8875492018-02-20 08:33:48 -0800884 GrpcLb* grpclb_policy = lb_calld->grpclb_policy();
885 GPR_ASSERT(lb_calld->lb_call_ != nullptr);
886 if (grpc_lb_glb_trace.enabled()) {
887 char* status_details =
888 grpc_slice_to_c_string(lb_calld->lb_call_status_details_);
889 gpr_log(GPR_INFO,
890 "[grpclb %p] Status from LB server received. Status = %d, details "
891 "= '%s', (lb_calld: %p, lb_call: %p), error '%s'",
892 grpclb_policy, lb_calld->lb_call_status_, status_details, lb_calld,
893 lb_calld->lb_call_, grpc_error_string(error));
894 gpr_free(status_details);
895 }
896 grpclb_policy->TryReresolutionLocked(&grpc_lb_glb_trace, GRPC_ERROR_NONE);
897 // If this lb_calld is still in use, this call ended because of a failure so
898 // we want to retry connecting. Otherwise, we have deliberately ended this
899 // call and no further action is required.
900 if (lb_calld == grpclb_policy->lb_calld_.get()) {
901 grpclb_policy->lb_calld_.reset();
902 GPR_ASSERT(!grpclb_policy->shutting_down_);
903 if (lb_calld->seen_initial_response_) {
904 // If we lose connection to the LB server, reset the backoff and restart
905 // the LB call immediately.
906 grpclb_policy->lb_call_backoff_.Reset();
907 grpclb_policy->StartBalancerCallLocked();
908 } else {
909 // If this LB call fails establishing any connection to the LB server,
910 // retry later.
911 grpclb_policy->StartBalancerCallRetryTimerLocked();
912 }
913 }
914 lb_calld->Unref(DEBUG_LOCATION, "lb_call_ended");
915}
916
917//
918// helper code for creating balancer channel
919//
920
Mark D. Rothbd0f1512018-02-20 10:28:22 -0800921grpc_lb_addresses* ExtractBalancerAddresses(
922 const grpc_lb_addresses* addresses) {
923 size_t num_grpclb_addrs = 0;
924 for (size_t i = 0; i < addresses->num_addresses; ++i) {
925 if (addresses->addresses[i].is_balancer) ++num_grpclb_addrs;
926 }
927 // There must be at least one balancer address, or else the
928 // client_channel would not have chosen this LB policy.
929 GPR_ASSERT(num_grpclb_addrs > 0);
930 grpc_lb_addresses* lb_addresses =
931 grpc_lb_addresses_create(num_grpclb_addrs, nullptr);
932 size_t lb_addresses_idx = 0;
933 for (size_t i = 0; i < addresses->num_addresses; ++i) {
934 if (!addresses->addresses[i].is_balancer) continue;
935 if (addresses->addresses[i].user_data != nullptr) {
936 gpr_log(GPR_ERROR,
937 "This LB policy doesn't support user data. It will be ignored");
938 }
939 grpc_lb_addresses_set_address(
940 lb_addresses, lb_addresses_idx++, addresses->addresses[i].address.addr,
941 addresses->addresses[i].address.len, false /* is balancer */,
942 addresses->addresses[i].balancer_name, nullptr /* user data */);
943 }
944 GPR_ASSERT(num_grpclb_addrs == lb_addresses_idx);
945 return lb_addresses;
Mark D. Rothc8875492018-02-20 08:33:48 -0800946}
947
948/* Returns the channel args for the LB channel, used to create a bidirectional
949 * stream for the reception of load balancing updates.
950 *
951 * Inputs:
952 * - \a addresses: corresponding to the balancers.
953 * - \a response_generator: in order to propagate updates from the resolver
954 * above the grpclb policy.
955 * - \a args: other args inherited from the grpclb policy. */
956grpc_channel_args* BuildBalancerChannelArgs(
957 const grpc_lb_addresses* addresses,
958 FakeResolverResponseGenerator* response_generator,
959 const grpc_channel_args* args) {
Mark D. Rothbd0f1512018-02-20 10:28:22 -0800960 grpc_lb_addresses* lb_addresses = ExtractBalancerAddresses(addresses);
961 // Channel args to remove.
962 static const char* args_to_remove[] = {
963 // LB policy name, since we want to use the default (pick_first) in
964 // the LB channel.
965 GRPC_ARG_LB_POLICY_NAME,
966 // The channel arg for the server URI, since that will be different for
967 // the LB channel than for the parent channel. The client channel
968 // factory will re-add this arg with the right value.
969 GRPC_ARG_SERVER_URI,
970 // The resolved addresses, which will be generated by the name resolver
971 // used in the LB channel. Note that the LB channel will use the fake
972 // resolver, so this won't actually generate a query to DNS (or some
973 // other name service). However, the addresses returned by the fake
974 // resolver will have is_balancer=false, whereas our own addresses have
975 // is_balancer=true. We need the LB channel to return addresses with
976 // is_balancer=false so that it does not wind up recursively using the
977 // grpclb LB policy, as per the special case logic in client_channel.c.
978 GRPC_ARG_LB_ADDRESSES,
979 // The fake resolver response generator, because we are replacing it
980 // with the one from the grpclb policy, used to propagate updates to
981 // the LB channel.
982 GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
David Garcia Quintasc7c0d692018-03-10 17:27:15 -0800983 // The LB channel should use the authority indicated by the target
984 // authority table (see \a grpc_lb_policy_grpclb_modify_lb_channel_args),
985 // as opposed to the authority from the parent channel.
986 GRPC_ARG_DEFAULT_AUTHORITY,
David Garcia Quintas7b84b3d2018-03-12 12:08:30 -0700987 // Just as for \a GRPC_ARG_DEFAULT_AUTHORITY, the LB channel should be
988 // treated as a stand-alone channel and not inherit this argument from the
989 // args of the parent channel.
990 GRPC_SSL_TARGET_NAME_OVERRIDE_ARG,
Mark D. Rothbd0f1512018-02-20 10:28:22 -0800991 };
992 // Channel args to add.
993 const grpc_arg args_to_add[] = {
994 // New LB addresses.
995 // Note that we pass these in both when creating the LB channel
996 // and via the fake resolver. The latter is what actually gets used.
997 grpc_lb_addresses_create_channel_arg(lb_addresses),
998 // The fake resolver response generator, which we use to inject
999 // address updates into the LB channel.
1000 grpc_core::FakeResolverResponseGenerator::MakeChannelArg(
1001 response_generator),
1002 };
1003 // Construct channel args.
1004 grpc_channel_args* new_args = grpc_channel_args_copy_and_add_and_remove(
1005 args, args_to_remove, GPR_ARRAY_SIZE(args_to_remove), args_to_add,
1006 GPR_ARRAY_SIZE(args_to_add));
1007 // Make any necessary modifications for security.
1008 new_args = grpc_lb_policy_grpclb_modify_lb_channel_args(new_args);
1009 // Clean up.
Mark D. Rothc8875492018-02-20 08:33:48 -08001010 grpc_lb_addresses_destroy(lb_addresses);
Mark D. Rothbd0f1512018-02-20 10:28:22 -08001011 return new_args;
Mark D. Rothc8875492018-02-20 08:33:48 -08001012}
1013
1014//
1015// ctor and dtor
1016//
1017
1018GrpcLb::GrpcLb(const grpc_lb_addresses* addresses,
1019 const LoadBalancingPolicy::Args& args)
1020 : LoadBalancingPolicy(args),
1021 response_generator_(MakeRefCounted<FakeResolverResponseGenerator>()),
1022 lb_call_backoff_(
1023 BackOff::Options()
1024 .set_initial_backoff(GRPC_GRPCLB_INITIAL_CONNECT_BACKOFF_SECONDS *
1025 1000)
1026 .set_multiplier(GRPC_GRPCLB_RECONNECT_BACKOFF_MULTIPLIER)
1027 .set_jitter(GRPC_GRPCLB_RECONNECT_JITTER)
1028 .set_max_backoff(GRPC_GRPCLB_RECONNECT_MAX_BACKOFF_SECONDS *
1029 1000)) {
1030 // Initialization.
1031 grpc_subchannel_index_ref();
1032 GRPC_CLOSURE_INIT(&lb_channel_on_connectivity_changed_,
1033 &GrpcLb::OnBalancerChannelConnectivityChangedLocked, this,
1034 grpc_combiner_scheduler(args.combiner));
1035 GRPC_CLOSURE_INIT(&on_rr_connectivity_changed_,
1036 &GrpcLb::OnRoundRobinConnectivityChangedLocked, this,
1037 grpc_combiner_scheduler(args.combiner));
1038 GRPC_CLOSURE_INIT(&on_rr_request_reresolution_,
1039 &GrpcLb::OnRoundRobinRequestReresolutionLocked, this,
1040 grpc_combiner_scheduler(args.combiner));
1041 grpc_connectivity_state_init(&state_tracker_, GRPC_CHANNEL_IDLE, "grpclb");
1042 // Record server name.
1043 const grpc_arg* arg = grpc_channel_args_find(args.args, GRPC_ARG_SERVER_URI);
1044 const char* server_uri = grpc_channel_arg_get_string(arg);
1045 GPR_ASSERT(server_uri != nullptr);
1046 grpc_uri* uri = grpc_uri_parse(server_uri, true);
1047 GPR_ASSERT(uri->path[0] != '\0');
1048 server_name_ = gpr_strdup(uri->path[0] == '/' ? uri->path + 1 : uri->path);
1049 if (grpc_lb_glb_trace.enabled()) {
1050 gpr_log(GPR_INFO,
1051 "[grpclb %p] Will use '%s' as the server name for LB request.",
1052 this, server_name_);
1053 }
1054 grpc_uri_destroy(uri);
1055 // Record LB call timeout.
1056 arg = grpc_channel_args_find(args.args, GRPC_ARG_GRPCLB_CALL_TIMEOUT_MS);
1057 lb_call_timeout_ms_ = grpc_channel_arg_get_integer(arg, {0, 0, INT_MAX});
1058 // Record fallback timeout.
1059 arg = grpc_channel_args_find(args.args, GRPC_ARG_GRPCLB_FALLBACK_TIMEOUT_MS);
1060 lb_fallback_timeout_ms_ = grpc_channel_arg_get_integer(
1061 arg, {GRPC_GRPCLB_DEFAULT_FALLBACK_TIMEOUT_MS, 0, INT_MAX});
1062 // Process channel args.
1063 ProcessChannelArgsLocked(*args.args);
1064}
1065
1066GrpcLb::~GrpcLb() {
1067 GPR_ASSERT(pending_picks_ == nullptr);
1068 GPR_ASSERT(pending_pings_ == nullptr);
1069 gpr_free((void*)server_name_);
1070 grpc_channel_args_destroy(args_);
1071 grpc_connectivity_state_destroy(&state_tracker_);
1072 if (serverlist_ != nullptr) {
1073 grpc_grpclb_destroy_serverlist(serverlist_);
1074 }
1075 if (fallback_backend_addresses_ != nullptr) {
1076 grpc_lb_addresses_destroy(fallback_backend_addresses_);
1077 }
1078 grpc_subchannel_index_unref();
1079}
1080
1081void GrpcLb::ShutdownLocked() {
1082 grpc_error* error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Channel shutdown");
1083 shutting_down_ = true;
1084 lb_calld_.reset();
1085 if (retry_timer_callback_pending_) {
1086 grpc_timer_cancel(&lb_call_retry_timer_);
1087 }
1088 if (fallback_timer_callback_pending_) {
1089 grpc_timer_cancel(&lb_fallback_timer_);
1090 }
1091 rr_policy_.reset();
1092 TryReresolutionLocked(&grpc_lb_glb_trace, GRPC_ERROR_CANCELLED);
1093 // We destroy the LB channel here instead of in our destructor because
1094 // destroying the channel triggers a last callback to
1095 // OnBalancerChannelConnectivityChangedLocked(), and we need to be
1096 // alive when that callback is invoked.
1097 if (lb_channel_ != nullptr) {
1098 grpc_channel_destroy(lb_channel_);
1099 lb_channel_ = nullptr;
1100 }
1101 grpc_connectivity_state_set(&state_tracker_, GRPC_CHANNEL_SHUTDOWN,
1102 GRPC_ERROR_REF(error), "grpclb_shutdown");
1103 // Clear pending picks.
1104 PendingPick* pp;
1105 while ((pp = pending_picks_) != nullptr) {
1106 pending_picks_ = pp->next;
1107 pp->pick->connected_subchannel.reset();
1108 // Note: pp is deleted in this callback.
1109 GRPC_CLOSURE_SCHED(&pp->on_complete, GRPC_ERROR_REF(error));
1110 }
1111 // Clear pending pings.
1112 PendingPing* pping;
1113 while ((pping = pending_pings_) != nullptr) {
1114 pending_pings_ = pping->next;
1115 GRPC_CLOSURE_SCHED(pping->on_initiate, GRPC_ERROR_REF(error));
1116 GRPC_CLOSURE_SCHED(pping->on_ack, GRPC_ERROR_REF(error));
1117 Delete(pping);
1118 }
1119 GRPC_ERROR_UNREF(error);
1120}
1121
1122//
1123// public methods
1124//
1125
1126void GrpcLb::HandOffPendingPicksLocked(LoadBalancingPolicy* new_policy) {
1127 PendingPick* pp;
1128 while ((pp = pending_picks_) != nullptr) {
1129 pending_picks_ = pp->next;
1130 pp->pick->on_complete = pp->original_on_complete;
1131 pp->pick->user_data = nullptr;
1132 if (new_policy->PickLocked(pp->pick)) {
1133 // Synchronous return; schedule closure.
1134 GRPC_CLOSURE_SCHED(pp->pick->on_complete, GRPC_ERROR_NONE);
1135 }
1136 Delete(pp);
1137 }
1138}
1139
1140// Cancel a specific pending pick.
1141//
1142// A grpclb pick progresses as follows:
1143// - If there's a Round Robin policy (rr_policy_) available, it'll be
1144// handed over to the RR policy (in CreateRoundRobinPolicyLocked()). From
1145// that point onwards, it'll be RR's responsibility. For cancellations, that
1146// implies the pick needs also be cancelled by the RR instance.
1147// - Otherwise, without an RR instance, picks stay pending at this policy's
1148// level (grpclb), inside the pending_picks_ list. To cancel these,
1149// we invoke the completion closure and set the pick's connected
1150// subchannel to nullptr right here.
1151void GrpcLb::CancelPickLocked(PickState* pick, grpc_error* error) {
1152 PendingPick* pp = pending_picks_;
1153 pending_picks_ = nullptr;
1154 while (pp != nullptr) {
1155 PendingPick* next = pp->next;
1156 if (pp->pick == pick) {
1157 pick->connected_subchannel.reset();
1158 // Note: pp is deleted in this callback.
1159 GRPC_CLOSURE_SCHED(&pp->on_complete,
1160 GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
1161 "Pick Cancelled", &error, 1));
1162 } else {
1163 pp->next = pending_picks_;
1164 pending_picks_ = pp;
1165 }
1166 pp = next;
1167 }
1168 if (rr_policy_ != nullptr) {
1169 rr_policy_->CancelPickLocked(pick, GRPC_ERROR_REF(error));
1170 }
1171 GRPC_ERROR_UNREF(error);
1172}
1173
1174// Cancel all pending picks.
1175//
1176// A grpclb pick progresses as follows:
1177// - If there's a Round Robin policy (rr_policy_) available, it'll be
1178// handed over to the RR policy (in CreateRoundRobinPolicyLocked()). From
1179// that point onwards, it'll be RR's responsibility. For cancellations, that
1180// implies the pick needs also be cancelled by the RR instance.
1181// - Otherwise, without an RR instance, picks stay pending at this policy's
1182// level (grpclb), inside the pending_picks_ list. To cancel these,
1183// we invoke the completion closure and set the pick's connected
1184// subchannel to nullptr right here.
1185void GrpcLb::CancelMatchingPicksLocked(uint32_t initial_metadata_flags_mask,
1186 uint32_t initial_metadata_flags_eq,
1187 grpc_error* error) {
1188 PendingPick* pp = pending_picks_;
1189 pending_picks_ = nullptr;
1190 while (pp != nullptr) {
1191 PendingPick* next = pp->next;
1192 if ((pp->pick->initial_metadata_flags & initial_metadata_flags_mask) ==
1193 initial_metadata_flags_eq) {
1194 // Note: pp is deleted in this callback.
1195 GRPC_CLOSURE_SCHED(&pp->on_complete,
1196 GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
1197 "Pick Cancelled", &error, 1));
1198 } else {
1199 pp->next = pending_picks_;
1200 pending_picks_ = pp;
1201 }
1202 pp = next;
1203 }
1204 if (rr_policy_ != nullptr) {
1205 rr_policy_->CancelMatchingPicksLocked(initial_metadata_flags_mask,
1206 initial_metadata_flags_eq,
1207 GRPC_ERROR_REF(error));
1208 }
1209 GRPC_ERROR_UNREF(error);
1210}
1211
1212void GrpcLb::ExitIdleLocked() {
1213 if (!started_picking_) {
1214 StartPickingLocked();
1215 }
1216}
1217
1218bool GrpcLb::PickLocked(PickState* pick) {
1219 PendingPick* pp = PendingPickCreate(pick);
1220 bool pick_done = false;
1221 if (rr_policy_ != nullptr) {
1222 const grpc_connectivity_state rr_connectivity_state =
1223 rr_policy_->CheckConnectivityLocked(nullptr);
1224 // The RR policy may have transitioned to SHUTDOWN but the callback
1225 // registered to capture this event (on_rr_connectivity_changed_) may not
1226 // have been invoked yet. We need to make sure we aren't trying to pick
1227 // from an RR policy instance that's in shutdown.
1228 if (rr_connectivity_state == GRPC_CHANNEL_SHUTDOWN) {
1229 if (grpc_lb_glb_trace.enabled()) {
1230 gpr_log(GPR_INFO,
1231 "[grpclb %p] NOT picking from from RR %p: RR conn state=%s",
1232 this, rr_policy_.get(),
1233 grpc_connectivity_state_name(rr_connectivity_state));
1234 }
1235 AddPendingPick(pp);
1236 pick_done = false;
1237 } else { // RR not in shutdown
1238 if (grpc_lb_glb_trace.enabled()) {
1239 gpr_log(GPR_INFO, "[grpclb %p] about to PICK from RR %p", this,
1240 rr_policy_.get());
1241 }
1242 pick_done = PickFromRoundRobinPolicyLocked(false /* force_async */, pp);
1243 }
1244 } else { // rr_policy_ == NULL
1245 if (grpc_lb_glb_trace.enabled()) {
1246 gpr_log(GPR_DEBUG,
1247 "[grpclb %p] No RR policy. Adding to grpclb's pending picks",
1248 this);
1249 }
1250 AddPendingPick(pp);
1251 if (!started_picking_) {
1252 StartPickingLocked();
1253 }
1254 pick_done = false;
1255 }
1256 return pick_done;
1257}
1258
1259void GrpcLb::PingOneLocked(grpc_closure* on_initiate, grpc_closure* on_ack) {
1260 if (rr_policy_ != nullptr) {
1261 rr_policy_->PingOneLocked(on_initiate, on_ack);
1262 } else {
1263 AddPendingPing(on_initiate, on_ack);
1264 if (!started_picking_) {
1265 StartPickingLocked();
1266 }
1267 }
1268}
1269
1270grpc_connectivity_state GrpcLb::CheckConnectivityLocked(
1271 grpc_error** connectivity_error) {
1272 return grpc_connectivity_state_get(&state_tracker_, connectivity_error);
1273}
1274
1275void GrpcLb::NotifyOnStateChangeLocked(grpc_connectivity_state* current,
1276 grpc_closure* notify) {
1277 grpc_connectivity_state_notify_on_state_change(&state_tracker_, current,
1278 notify);
1279}
1280
1281void GrpcLb::ProcessChannelArgsLocked(const grpc_channel_args& args) {
1282 const grpc_arg* arg = grpc_channel_args_find(&args, GRPC_ARG_LB_ADDRESSES);
1283 if (arg == nullptr || arg->type != GRPC_ARG_POINTER) {
1284 // Ignore this update.
1285 gpr_log(
1286 GPR_ERROR,
1287 "[grpclb %p] No valid LB addresses channel arg in update, ignoring.",
1288 this);
1289 return;
1290 }
1291 const grpc_lb_addresses* addresses =
Vijay Pai7fed69b2018-03-05 09:58:05 -08001292 static_cast<const grpc_lb_addresses*>(arg->value.pointer.p);
Mark D. Rothc8875492018-02-20 08:33:48 -08001293 // Update fallback address list.
1294 if (fallback_backend_addresses_ != nullptr) {
1295 grpc_lb_addresses_destroy(fallback_backend_addresses_);
1296 }
1297 fallback_backend_addresses_ = ExtractBackendAddresses(addresses);
1298 // Make sure that GRPC_ARG_LB_POLICY_NAME is set in channel args,
1299 // since we use this to trigger the client_load_reporting filter.
1300 static const char* args_to_remove[] = {GRPC_ARG_LB_POLICY_NAME};
1301 grpc_arg new_arg = grpc_channel_arg_string_create(
1302 (char*)GRPC_ARG_LB_POLICY_NAME, (char*)"grpclb");
1303 grpc_channel_args_destroy(args_);
1304 args_ = grpc_channel_args_copy_and_add_and_remove(
1305 &args, args_to_remove, GPR_ARRAY_SIZE(args_to_remove), &new_arg, 1);
1306 // Construct args for balancer channel.
1307 grpc_channel_args* lb_channel_args =
1308 BuildBalancerChannelArgs(addresses, response_generator_.get(), &args);
1309 // Create balancer channel if needed.
1310 if (lb_channel_ == nullptr) {
1311 char* uri_str;
1312 gpr_asprintf(&uri_str, "fake:///%s", server_name_);
Mark D. Rothbd0f1512018-02-20 10:28:22 -08001313 lb_channel_ = grpc_client_channel_factory_create_channel(
1314 client_channel_factory(), uri_str,
1315 GRPC_CLIENT_CHANNEL_TYPE_LOAD_BALANCING, lb_channel_args);
Mark D. Rothc8875492018-02-20 08:33:48 -08001316 GPR_ASSERT(lb_channel_ != nullptr);
1317 gpr_free(uri_str);
1318 }
1319 // Propagate updates to the LB channel (pick_first) through the fake
1320 // resolver.
1321 response_generator_->SetResponse(lb_channel_args);
1322 grpc_channel_args_destroy(lb_channel_args);
1323}
1324
1325void GrpcLb::UpdateLocked(const grpc_channel_args& args) {
1326 ProcessChannelArgsLocked(args);
1327 // If fallback is configured and the RR policy already exists, update
1328 // it with the new fallback addresses.
1329 if (lb_fallback_timeout_ms_ > 0 && rr_policy_ != nullptr) {
1330 CreateOrUpdateRoundRobinPolicyLocked();
1331 }
1332 // Start watching the LB channel connectivity for connection, if not
1333 // already doing so.
1334 if (!watching_lb_channel_) {
1335 lb_channel_connectivity_ = grpc_channel_check_connectivity_state(
1336 lb_channel_, true /* try to connect */);
1337 grpc_channel_element* client_channel_elem = grpc_channel_stack_last_element(
1338 grpc_channel_get_channel_stack(lb_channel_));
1339 GPR_ASSERT(client_channel_elem->filter == &grpc_client_channel_filter);
1340 watching_lb_channel_ = true;
1341 // TODO(roth): We currently track this ref manually. Once the
1342 // ClosureRef API is ready, we should pass the RefCountedPtr<> along
1343 // with the callback.
1344 auto self = Ref(DEBUG_LOCATION, "watch_lb_channel_connectivity");
1345 self.release();
1346 grpc_client_channel_watch_connectivity_state(
1347 client_channel_elem,
1348 grpc_polling_entity_create_from_pollset_set(interested_parties()),
1349 &lb_channel_connectivity_, &lb_channel_on_connectivity_changed_,
1350 nullptr);
1351 }
1352}
1353
1354//
1355// code for balancer channel and call
1356//
1357
1358void GrpcLb::StartPickingLocked() {
1359 // Start a timer to fall back.
1360 if (lb_fallback_timeout_ms_ > 0 && serverlist_ == nullptr &&
1361 !fallback_timer_callback_pending_) {
1362 grpc_millis deadline = ExecCtx::Get()->Now() + lb_fallback_timeout_ms_;
1363 // TODO(roth): We currently track this ref manually. Once the
1364 // ClosureRef API is ready, we should pass the RefCountedPtr<> along
1365 // with the callback.
1366 auto self = Ref(DEBUG_LOCATION, "on_fallback_timer");
1367 self.release();
1368 GRPC_CLOSURE_INIT(&lb_on_fallback_, &GrpcLb::OnFallbackTimerLocked, this,
1369 grpc_combiner_scheduler(combiner()));
1370 fallback_timer_callback_pending_ = true;
1371 grpc_timer_init(&lb_fallback_timer_, deadline, &lb_on_fallback_);
1372 }
1373 started_picking_ = true;
1374 StartBalancerCallLocked();
1375}
1376
1377void GrpcLb::StartBalancerCallLocked() {
1378 GPR_ASSERT(lb_channel_ != nullptr);
1379 if (shutting_down_) return;
1380 // Init the LB call data.
1381 GPR_ASSERT(lb_calld_ == nullptr);
1382 lb_calld_ = MakeOrphanable<BalancerCallState>(Ref());
1383 if (grpc_lb_glb_trace.enabled()) {
1384 gpr_log(GPR_INFO,
1385 "[grpclb %p] Query for backends (lb_channel: %p, lb_calld: %p)",
1386 this, lb_channel_, lb_calld_.get());
1387 }
1388 lb_calld_->StartQuery();
1389}
1390
1391void GrpcLb::OnFallbackTimerLocked(void* arg, grpc_error* error) {
1392 GrpcLb* grpclb_policy = static_cast<GrpcLb*>(arg);
1393 grpclb_policy->fallback_timer_callback_pending_ = false;
1394 // If we receive a serverlist after the timer fires but before this callback
1395 // actually runs, don't fall back.
1396 if (grpclb_policy->serverlist_ == nullptr && !grpclb_policy->shutting_down_ &&
1397 error == GRPC_ERROR_NONE) {
1398 if (grpc_lb_glb_trace.enabled()) {
1399 gpr_log(GPR_INFO,
1400 "[grpclb %p] Falling back to use backends from resolver",
1401 grpclb_policy);
1402 }
1403 GPR_ASSERT(grpclb_policy->fallback_backend_addresses_ != nullptr);
1404 grpclb_policy->CreateOrUpdateRoundRobinPolicyLocked();
1405 }
1406 grpclb_policy->Unref(DEBUG_LOCATION, "on_fallback_timer");
1407}
1408
1409void GrpcLb::StartBalancerCallRetryTimerLocked() {
1410 grpc_millis next_try = lb_call_backoff_.NextAttemptTime();
1411 if (grpc_lb_glb_trace.enabled()) {
1412 gpr_log(GPR_DEBUG, "[grpclb %p] Connection to LB server lost...", this);
1413 grpc_millis timeout = next_try - ExecCtx::Get()->Now();
1414 if (timeout > 0) {
Sree Kuchibhotla1dd12c02018-04-11 18:05:48 -07001415 gpr_log(GPR_DEBUG, "[grpclb %p] ... retry_timer_active in %" PRId64 "ms.",
1416 this, timeout);
Mark D. Rothc8875492018-02-20 08:33:48 -08001417 } else {
1418 gpr_log(GPR_DEBUG, "[grpclb %p] ... retry_timer_active immediately.",
1419 this);
1420 }
1421 }
1422 // TODO(roth): We currently track this ref manually. Once the
1423 // ClosureRef API is ready, we should pass the RefCountedPtr<> along
1424 // with the callback.
1425 auto self = Ref(DEBUG_LOCATION, "on_balancer_call_retry_timer");
1426 self.release();
1427 GRPC_CLOSURE_INIT(&lb_on_call_retry_, &GrpcLb::OnBalancerCallRetryTimerLocked,
1428 this, grpc_combiner_scheduler(combiner()));
1429 retry_timer_callback_pending_ = true;
1430 grpc_timer_init(&lb_call_retry_timer_, next_try, &lb_on_call_retry_);
1431}
1432
1433void GrpcLb::OnBalancerCallRetryTimerLocked(void* arg, grpc_error* error) {
Vijay Pai7fed69b2018-03-05 09:58:05 -08001434 GrpcLb* grpclb_policy = static_cast<GrpcLb*>(arg);
Mark D. Rothc8875492018-02-20 08:33:48 -08001435 grpclb_policy->retry_timer_callback_pending_ = false;
1436 if (!grpclb_policy->shutting_down_ && error == GRPC_ERROR_NONE &&
1437 grpclb_policy->lb_calld_ == nullptr) {
1438 if (grpc_lb_glb_trace.enabled()) {
1439 gpr_log(GPR_INFO, "[grpclb %p] Restarting call to LB server",
1440 grpclb_policy);
1441 }
1442 grpclb_policy->StartBalancerCallLocked();
1443 }
1444 grpclb_policy->Unref(DEBUG_LOCATION, "on_balancer_call_retry_timer");
1445}
1446
1447// Invoked as part of the update process. It continues watching the LB channel
1448// until it shuts down or becomes READY. It's invoked even if the LB channel
1449// stayed READY throughout the update (for example if the update is identical).
1450void GrpcLb::OnBalancerChannelConnectivityChangedLocked(void* arg,
1451 grpc_error* error) {
1452 GrpcLb* grpclb_policy = static_cast<GrpcLb*>(arg);
1453 if (grpclb_policy->shutting_down_) goto done;
1454 // Re-initialize the lb_call. This should also take care of updating the
1455 // embedded RR policy. Note that the current RR policy, if any, will stay in
1456 // effect until an update from the new lb_call is received.
1457 switch (grpclb_policy->lb_channel_connectivity_) {
1458 case GRPC_CHANNEL_CONNECTING:
1459 case GRPC_CHANNEL_TRANSIENT_FAILURE: {
1460 // Keep watching the LB channel.
1461 grpc_channel_element* client_channel_elem =
1462 grpc_channel_stack_last_element(
1463 grpc_channel_get_channel_stack(grpclb_policy->lb_channel_));
1464 GPR_ASSERT(client_channel_elem->filter == &grpc_client_channel_filter);
1465 grpc_client_channel_watch_connectivity_state(
1466 client_channel_elem,
1467 grpc_polling_entity_create_from_pollset_set(
1468 grpclb_policy->interested_parties()),
1469 &grpclb_policy->lb_channel_connectivity_,
1470 &grpclb_policy->lb_channel_on_connectivity_changed_, nullptr);
1471 break;
1472 }
1473 // The LB channel may be IDLE because it's shut down before the update.
1474 // Restart the LB call to kick the LB channel into gear.
1475 case GRPC_CHANNEL_IDLE:
1476 case GRPC_CHANNEL_READY:
1477 grpclb_policy->lb_calld_.reset();
1478 if (grpclb_policy->started_picking_) {
1479 if (grpclb_policy->retry_timer_callback_pending_) {
1480 grpc_timer_cancel(&grpclb_policy->lb_call_retry_timer_);
1481 }
1482 grpclb_policy->lb_call_backoff_.Reset();
1483 grpclb_policy->StartBalancerCallLocked();
1484 }
1485 // Fall through.
1486 case GRPC_CHANNEL_SHUTDOWN:
1487 done:
1488 grpclb_policy->watching_lb_channel_ = false;
1489 grpclb_policy->Unref(DEBUG_LOCATION,
1490 "watch_lb_channel_connectivity_cb_shutdown");
1491 }
1492}
1493
1494//
1495// PendingPick
1496//
1497
1498// Adds lb_token of selected subchannel (address) to the call's initial
1499// metadata.
1500grpc_error* AddLbTokenToInitialMetadata(
1501 grpc_mdelem lb_token, grpc_linked_mdelem* lb_token_mdelem_storage,
1502 grpc_metadata_batch* initial_metadata) {
1503 GPR_ASSERT(lb_token_mdelem_storage != nullptr);
1504 GPR_ASSERT(!GRPC_MDISNULL(lb_token));
1505 return grpc_metadata_batch_add_tail(initial_metadata, lb_token_mdelem_storage,
1506 lb_token);
1507}
1508
1509// Destroy function used when embedding client stats in call context.
1510void DestroyClientStats(void* arg) {
Vijay Pai7fed69b2018-03-05 09:58:05 -08001511 grpc_grpclb_client_stats_unref(static_cast<grpc_grpclb_client_stats*>(arg));
Mark D. Rothc8875492018-02-20 08:33:48 -08001512}
1513
1514void GrpcLb::PendingPickSetMetadataAndContext(PendingPick* pp) {
1515 /* if connected_subchannel is nullptr, no pick has been made by the RR
1516 * policy (e.g., all addresses failed to connect). There won't be any
1517 * user_data/token available */
1518 if (pp->pick->connected_subchannel != nullptr) {
1519 if (!GRPC_MDISNULL(pp->lb_token)) {
1520 AddLbTokenToInitialMetadata(GRPC_MDELEM_REF(pp->lb_token),
1521 &pp->pick->lb_token_mdelem_storage,
1522 pp->pick->initial_metadata);
1523 } else {
1524 gpr_log(GPR_ERROR,
1525 "[grpclb %p] No LB token for connected subchannel pick %p",
1526 pp->grpclb_policy, pp->pick);
1527 abort();
1528 }
1529 // Pass on client stats via context. Passes ownership of the reference.
1530 if (pp->client_stats != nullptr) {
1531 pp->pick->subchannel_call_context[GRPC_GRPCLB_CLIENT_STATS].value =
1532 pp->client_stats;
1533 pp->pick->subchannel_call_context[GRPC_GRPCLB_CLIENT_STATS].destroy =
1534 DestroyClientStats;
1535 }
1536 } else {
1537 if (pp->client_stats != nullptr) {
1538 grpc_grpclb_client_stats_unref(pp->client_stats);
1539 }
1540 }
1541}
1542
1543/* The \a on_complete closure passed as part of the pick requires keeping a
1544 * reference to its associated round robin instance. We wrap this closure in
1545 * order to unref the round robin instance upon its invocation */
1546void GrpcLb::OnPendingPickComplete(void* arg, grpc_error* error) {
Vijay Pai7fed69b2018-03-05 09:58:05 -08001547 PendingPick* pp = static_cast<PendingPick*>(arg);
Mark D. Rothc8875492018-02-20 08:33:48 -08001548 PendingPickSetMetadataAndContext(pp);
1549 GRPC_CLOSURE_SCHED(pp->original_on_complete, GRPC_ERROR_REF(error));
1550 Delete(pp);
1551}
1552
1553GrpcLb::PendingPick* GrpcLb::PendingPickCreate(PickState* pick) {
1554 PendingPick* pp = New<PendingPick>();
1555 pp->grpclb_policy = this;
1556 pp->pick = pick;
1557 GRPC_CLOSURE_INIT(&pp->on_complete, &GrpcLb::OnPendingPickComplete, pp,
1558 grpc_schedule_on_exec_ctx);
1559 pp->original_on_complete = pick->on_complete;
1560 pick->on_complete = &pp->on_complete;
1561 return pp;
1562}
1563
1564void GrpcLb::AddPendingPick(PendingPick* pp) {
1565 pp->next = pending_picks_;
1566 pending_picks_ = pp;
1567}
1568
1569//
1570// PendingPing
1571//
1572
1573void GrpcLb::AddPendingPing(grpc_closure* on_initiate, grpc_closure* on_ack) {
1574 PendingPing* pping = New<PendingPing>();
1575 pping->on_initiate = on_initiate;
1576 pping->on_ack = on_ack;
1577 pping->next = pending_pings_;
1578 pending_pings_ = pping;
1579}
1580
1581//
1582// code for interacting with the RR policy
1583//
1584
1585// Performs a pick over \a rr_policy_. Given that a pick can return
1586// immediately (ignoring its completion callback), we need to perform the
1587// cleanups this callback would otherwise be responsible for.
1588// If \a force_async is true, then we will manually schedule the
1589// completion callback even if the pick is available immediately.
1590bool GrpcLb::PickFromRoundRobinPolicyLocked(bool force_async, PendingPick* pp) {
1591 // Check for drops if we are not using fallback backend addresses.
1592 if (serverlist_ != nullptr) {
1593 // Look at the index into the serverlist to see if we should drop this call.
1594 grpc_grpclb_server* server = serverlist_->servers[serverlist_index_++];
1595 if (serverlist_index_ == serverlist_->num_servers) {
1596 serverlist_index_ = 0; // Wrap-around.
1597 }
1598 if (server->drop) {
1599 // Update client load reporting stats to indicate the number of
1600 // dropped calls. Note that we have to do this here instead of in
1601 // the client_load_reporting filter, because we do not create a
1602 // subchannel call (and therefore no client_load_reporting filter)
1603 // for dropped calls.
1604 if (lb_calld_ != nullptr && lb_calld_->client_stats() != nullptr) {
1605 grpc_grpclb_client_stats_add_call_dropped_locked(
1606 server->load_balance_token, lb_calld_->client_stats());
1607 }
1608 if (force_async) {
1609 GRPC_CLOSURE_SCHED(pp->original_on_complete, GRPC_ERROR_NONE);
1610 Delete(pp);
1611 return false;
1612 }
1613 Delete(pp);
1614 return true;
1615 }
1616 }
1617 // Set client_stats and user_data.
1618 if (lb_calld_ != nullptr && lb_calld_->client_stats() != nullptr) {
1619 pp->client_stats = grpc_grpclb_client_stats_ref(lb_calld_->client_stats());
1620 }
1621 GPR_ASSERT(pp->pick->user_data == nullptr);
1622 pp->pick->user_data = (void**)&pp->lb_token;
1623 // Pick via the RR policy.
1624 bool pick_done = rr_policy_->PickLocked(pp->pick);
1625 if (pick_done) {
1626 PendingPickSetMetadataAndContext(pp);
1627 if (force_async) {
1628 GRPC_CLOSURE_SCHED(pp->original_on_complete, GRPC_ERROR_NONE);
1629 pick_done = false;
1630 }
1631 Delete(pp);
1632 }
1633 // else, the pending pick will be registered and taken care of by the
1634 // pending pick list inside the RR policy. Eventually,
1635 // OnPendingPickComplete() will be called, which will (among other
1636 // things) add the LB token to the call's initial metadata.
1637 return pick_done;
1638}
1639
1640void GrpcLb::CreateRoundRobinPolicyLocked(const Args& args) {
1641 GPR_ASSERT(rr_policy_ == nullptr);
1642 rr_policy_ = LoadBalancingPolicyRegistry::CreateLoadBalancingPolicy(
1643 "round_robin", args);
1644 if (rr_policy_ == nullptr) {
1645 gpr_log(GPR_ERROR, "[grpclb %p] Failure creating a RoundRobin policy",
1646 this);
1647 return;
1648 }
1649 // TODO(roth): We currently track this ref manually. Once the new
1650 // ClosureRef API is done, pass the RefCountedPtr<> along with the closure.
1651 auto self = Ref(DEBUG_LOCATION, "on_rr_reresolution_requested");
1652 self.release();
1653 rr_policy_->SetReresolutionClosureLocked(&on_rr_request_reresolution_);
1654 grpc_error* rr_state_error = nullptr;
1655 rr_connectivity_state_ = rr_policy_->CheckConnectivityLocked(&rr_state_error);
1656 // Connectivity state is a function of the RR policy updated/created.
1657 UpdateConnectivityStateFromRoundRobinPolicyLocked(rr_state_error);
1658 // Add the gRPC LB's interested_parties pollset_set to that of the newly
1659 // created RR policy. This will make the RR policy progress upon activity on
1660 // gRPC LB, which in turn is tied to the application's call.
1661 grpc_pollset_set_add_pollset_set(rr_policy_->interested_parties(),
1662 interested_parties());
1663 // Subscribe to changes to the connectivity of the new RR.
1664 // TODO(roth): We currently track this ref manually. Once the new
1665 // ClosureRef API is done, pass the RefCountedPtr<> along with the closure.
1666 self = Ref(DEBUG_LOCATION, "on_rr_connectivity_changed");
1667 self.release();
1668 rr_policy_->NotifyOnStateChangeLocked(&rr_connectivity_state_,
1669 &on_rr_connectivity_changed_);
1670 rr_policy_->ExitIdleLocked();
1671 // Send pending picks to RR policy.
1672 PendingPick* pp;
1673 while ((pp = pending_picks_)) {
1674 pending_picks_ = pp->next;
1675 if (grpc_lb_glb_trace.enabled()) {
1676 gpr_log(GPR_INFO,
1677 "[grpclb %p] Pending pick about to (async) PICK from RR %p", this,
1678 rr_policy_.get());
1679 }
1680 PickFromRoundRobinPolicyLocked(true /* force_async */, pp);
1681 }
1682 // Send pending pings to RR policy.
1683 PendingPing* pping;
1684 while ((pping = pending_pings_)) {
1685 pending_pings_ = pping->next;
1686 if (grpc_lb_glb_trace.enabled()) {
1687 gpr_log(GPR_INFO, "[grpclb %p] Pending ping about to PING from RR %p",
1688 this, rr_policy_.get());
1689 }
1690 rr_policy_->PingOneLocked(pping->on_initiate, pping->on_ack);
1691 Delete(pping);
1692 }
1693}
1694
1695grpc_channel_args* GrpcLb::CreateRoundRobinPolicyArgsLocked() {
1696 grpc_lb_addresses* addresses;
1697 if (serverlist_ != nullptr) {
1698 GPR_ASSERT(serverlist_->num_servers > 0);
1699 addresses = ProcessServerlist(serverlist_);
1700 } else {
1701 // If CreateOrUpdateRoundRobinPolicyLocked() is invoked when we haven't
1702 // received any serverlist from the balancer, we use the fallback backends
1703 // returned by the resolver. Note that the fallback backend list may be
1704 // empty, in which case the new round_robin policy will keep the requested
1705 // picks pending.
1706 GPR_ASSERT(fallback_backend_addresses_ != nullptr);
1707 addresses = grpc_lb_addresses_copy(fallback_backend_addresses_);
1708 }
1709 GPR_ASSERT(addresses != nullptr);
1710 // Replace the LB addresses in the channel args that we pass down to
1711 // the subchannel.
1712 static const char* keys_to_remove[] = {GRPC_ARG_LB_ADDRESSES};
1713 const grpc_arg arg = grpc_lb_addresses_create_channel_arg(addresses);
1714 grpc_channel_args* args = grpc_channel_args_copy_and_add_and_remove(
1715 args_, keys_to_remove, GPR_ARRAY_SIZE(keys_to_remove), &arg, 1);
1716 grpc_lb_addresses_destroy(addresses);
1717 return args;
1718}
1719
1720void GrpcLb::CreateOrUpdateRoundRobinPolicyLocked() {
1721 if (shutting_down_) return;
1722 grpc_channel_args* args = CreateRoundRobinPolicyArgsLocked();
1723 GPR_ASSERT(args != nullptr);
1724 if (rr_policy_ != nullptr) {
1725 if (grpc_lb_glb_trace.enabled()) {
1726 gpr_log(GPR_DEBUG, "[grpclb %p] Updating RR policy %p", this,
1727 rr_policy_.get());
1728 }
1729 rr_policy_->UpdateLocked(*args);
1730 } else {
1731 LoadBalancingPolicy::Args lb_policy_args;
1732 lb_policy_args.combiner = combiner();
1733 lb_policy_args.client_channel_factory = client_channel_factory();
1734 lb_policy_args.args = args;
1735 CreateRoundRobinPolicyLocked(lb_policy_args);
1736 if (grpc_lb_glb_trace.enabled()) {
1737 gpr_log(GPR_DEBUG, "[grpclb %p] Created new RR policy %p", this,
1738 rr_policy_.get());
1739 }
1740 }
1741 grpc_channel_args_destroy(args);
1742}
1743
1744void GrpcLb::OnRoundRobinRequestReresolutionLocked(void* arg,
1745 grpc_error* error) {
Vijay Pai7fed69b2018-03-05 09:58:05 -08001746 GrpcLb* grpclb_policy = static_cast<GrpcLb*>(arg);
Mark D. Rothc8875492018-02-20 08:33:48 -08001747 if (grpclb_policy->shutting_down_ || error != GRPC_ERROR_NONE) {
1748 grpclb_policy->Unref(DEBUG_LOCATION, "on_rr_reresolution_requested");
1749 return;
1750 }
1751 if (grpc_lb_glb_trace.enabled()) {
1752 gpr_log(
1753 GPR_DEBUG,
1754 "[grpclb %p] Re-resolution requested from the internal RR policy (%p).",
1755 grpclb_policy, grpclb_policy->rr_policy_.get());
1756 }
1757 // If we are talking to a balancer, we expect to get updated addresses form
1758 // the balancer, so we can ignore the re-resolution request from the RR
1759 // policy. Otherwise, handle the re-resolution request using the
1760 // grpclb policy's original re-resolution closure.
1761 if (grpclb_policy->lb_calld_ == nullptr ||
1762 !grpclb_policy->lb_calld_->seen_initial_response()) {
1763 grpclb_policy->TryReresolutionLocked(&grpc_lb_glb_trace, GRPC_ERROR_NONE);
1764 }
1765 // Give back the wrapper closure to the RR policy.
1766 grpclb_policy->rr_policy_->SetReresolutionClosureLocked(
1767 &grpclb_policy->on_rr_request_reresolution_);
1768}
1769
1770void GrpcLb::UpdateConnectivityStateFromRoundRobinPolicyLocked(
1771 grpc_error* rr_state_error) {
Craig Tiller613dafa2017-02-09 12:00:43 -08001772 const grpc_connectivity_state curr_glb_state =
Mark D. Rothc8875492018-02-20 08:33:48 -08001773 grpc_connectivity_state_check(&state_tracker_);
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001774 /* The new connectivity status is a function of the previous one and the new
1775 * input coming from the status of the RR policy.
1776 *
David Garcia Quintas4283a262016-11-18 10:43:56 -08001777 * current state (grpclb's)
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001778 * |
1779 * v || I | C | R | TF | SD | <- new state (RR's)
1780 * ===++====+=====+=====+======+======+
David Garcia Quintas4283a262016-11-18 10:43:56 -08001781 * I || I | C | R | [I] | [I] |
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001782 * ---++----+-----+-----+------+------+
David Garcia Quintas4283a262016-11-18 10:43:56 -08001783 * C || I | C | R | [C] | [C] |
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001784 * ---++----+-----+-----+------+------+
David Garcia Quintas4283a262016-11-18 10:43:56 -08001785 * R || I | C | R | [R] | [R] |
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001786 * ---++----+-----+-----+------+------+
David Garcia Quintas4283a262016-11-18 10:43:56 -08001787 * TF || I | C | R | [TF] | [TF] |
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001788 * ---++----+-----+-----+------+------+
1789 * SD || NA | NA | NA | NA | NA | (*)
1790 * ---++----+-----+-----+------+------+
1791 *
David Garcia Quintas4283a262016-11-18 10:43:56 -08001792 * A [STATE] indicates that the old RR policy is kept. In those cases, STATE
1793 * is the current state of grpclb, which is left untouched.
1794 *
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001795 * In summary, if the new state is TRANSIENT_FAILURE or SHUTDOWN, stick to
1796 * the previous RR instance.
1797 *
1798 * Note that the status is never updated to SHUTDOWN as a result of calling
1799 * this function. Only glb_shutdown() has the power to set that state.
1800 *
1801 * (*) This function mustn't be called during shutting down. */
1802 GPR_ASSERT(curr_glb_state != GRPC_CHANNEL_SHUTDOWN);
Mark D. Rothc8875492018-02-20 08:33:48 -08001803 switch (rr_connectivity_state_) {
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001804 case GRPC_CHANNEL_TRANSIENT_FAILURE:
1805 case GRPC_CHANNEL_SHUTDOWN:
David Garcia Quintas87d5a312017-06-06 19:45:58 -07001806 GPR_ASSERT(rr_state_error != GRPC_ERROR_NONE);
1807 break;
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001808 case GRPC_CHANNEL_IDLE:
1809 case GRPC_CHANNEL_CONNECTING:
1810 case GRPC_CHANNEL_READY:
David Garcia Quintas87d5a312017-06-06 19:45:58 -07001811 GPR_ASSERT(rr_state_error == GRPC_ERROR_NONE);
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001812 }
Craig Tiller6014e8a2017-10-16 13:50:29 -07001813 if (grpc_lb_glb_trace.enabled()) {
David Garcia Quintas87d5a312017-06-06 19:45:58 -07001814 gpr_log(
David Garcia Quintasa1c65902017-11-09 10:37:35 -08001815 GPR_INFO,
1816 "[grpclb %p] Setting grpclb's state to %s from new RR policy %p state.",
Mark D. Rothc8875492018-02-20 08:33:48 -08001817 this, grpc_connectivity_state_name(rr_connectivity_state_),
1818 rr_policy_.get());
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001819 }
Mark D. Rothc8875492018-02-20 08:33:48 -08001820 grpc_connectivity_state_set(&state_tracker_, rr_connectivity_state_,
1821 rr_state_error,
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001822 "update_lb_connectivity_status_locked");
David Garcia Quintas149f09d2016-11-17 20:43:10 -08001823}
1824
Mark D. Rothc8875492018-02-20 08:33:48 -08001825void GrpcLb::OnRoundRobinConnectivityChangedLocked(void* arg,
1826 grpc_error* error) {
Vijay Pai7fed69b2018-03-05 09:58:05 -08001827 GrpcLb* grpclb_policy = static_cast<GrpcLb*>(arg);
Mark D. Rothc8875492018-02-20 08:33:48 -08001828 if (grpclb_policy->shutting_down_) {
1829 grpclb_policy->Unref(DEBUG_LOCATION, "on_rr_connectivity_changed");
Juanli Shen87c65042018-02-15 09:42:45 -08001830 return;
1831 }
Mark D. Rothc8875492018-02-20 08:33:48 -08001832 grpclb_policy->UpdateConnectivityStateFromRoundRobinPolicyLocked(
1833 GRPC_ERROR_REF(error));
1834 // Resubscribe. Reuse the "on_rr_connectivity_changed" ref.
1835 grpclb_policy->rr_policy_->NotifyOnStateChangeLocked(
1836 &grpclb_policy->rr_connectivity_state_,
1837 &grpclb_policy->on_rr_connectivity_changed_);
Juanli Shen87c65042018-02-15 09:42:45 -08001838}
1839
David Garcia Quintasc22c65b2017-07-25 14:22:20 -07001840//
Mark D. Rothc8875492018-02-20 08:33:48 -08001841// factory
David Garcia Quintasc22c65b2017-07-25 14:22:20 -07001842//
Mark D. Rothc8875492018-02-20 08:33:48 -08001843
1844class GrpcLbFactory : public LoadBalancingPolicyFactory {
1845 public:
1846 OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
1847 const LoadBalancingPolicy::Args& args) const override {
1848 /* Count the number of gRPC-LB addresses. There must be at least one. */
1849 const grpc_arg* arg =
1850 grpc_channel_args_find(args.args, GRPC_ARG_LB_ADDRESSES);
1851 if (arg == nullptr || arg->type != GRPC_ARG_POINTER) {
1852 return nullptr;
David Garcia Quintas65318262016-07-29 13:43:38 -07001853 }
Mark D. Rothc8875492018-02-20 08:33:48 -08001854 grpc_lb_addresses* addresses =
Vijay Pai7fed69b2018-03-05 09:58:05 -08001855 static_cast<grpc_lb_addresses*>(arg->value.pointer.p);
Mark D. Rothc8875492018-02-20 08:33:48 -08001856 size_t num_grpclb_addrs = 0;
1857 for (size_t i = 0; i < addresses->num_addresses; ++i) {
1858 if (addresses->addresses[i].is_balancer) ++num_grpclb_addrs;
David Garcia Quintas65318262016-07-29 13:43:38 -07001859 }
Mark D. Rothc8875492018-02-20 08:33:48 -08001860 if (num_grpclb_addrs == 0) return nullptr;
1861 return OrphanablePtr<LoadBalancingPolicy>(New<GrpcLb>(addresses, args));
David Garcia Quintas65318262016-07-29 13:43:38 -07001862 }
David Garcia Quintas8d489112016-07-29 15:20:42 -07001863
Mark D. Rothc8875492018-02-20 08:33:48 -08001864 const char* name() const override { return "grpclb"; }
1865};
David Garcia Quintas8d489112016-07-29 15:20:42 -07001866
Mark D. Rothc8875492018-02-20 08:33:48 -08001867} // namespace
David Garcia Quintas8d489112016-07-29 15:20:42 -07001868
Mark D. Rothc8875492018-02-20 08:33:48 -08001869} // namespace grpc_core
David Garcia Quintas65318262016-07-29 13:43:38 -07001870
Mark D. Rothc8875492018-02-20 08:33:48 -08001871//
1872// Plugin registration
1873//
Mark D. Rotha4792f52017-09-26 09:06:35 -07001874
Mark D. Rothc8875492018-02-20 08:33:48 -08001875namespace {
Mark D. Roth09e458c2017-05-02 08:13:26 -07001876
1877// Only add client_load_reporting filter if the grpclb LB policy is used.
Mark D. Rothc8875492018-02-20 08:33:48 -08001878bool maybe_add_client_load_reporting_filter(grpc_channel_stack_builder* builder,
1879 void* arg) {
Craig Tillerbaa14a92017-11-03 09:09:36 -07001880 const grpc_channel_args* args =
Mark D. Roth09e458c2017-05-02 08:13:26 -07001881 grpc_channel_stack_builder_get_channel_arguments(builder);
Craig Tillerbaa14a92017-11-03 09:09:36 -07001882 const grpc_arg* channel_arg =
Mark D. Roth09e458c2017-05-02 08:13:26 -07001883 grpc_channel_args_find(args, GRPC_ARG_LB_POLICY_NAME);
Noah Eisen882dfed2017-11-14 14:58:20 -08001884 if (channel_arg != nullptr && channel_arg->type == GRPC_ARG_STRING &&
Mark D. Roth09e458c2017-05-02 08:13:26 -07001885 strcmp(channel_arg->value.string, "grpclb") == 0) {
1886 return grpc_channel_stack_builder_append_filter(
Mark D. Rothc8875492018-02-20 08:33:48 -08001887 builder, (const grpc_channel_filter*)arg, nullptr, nullptr);
Mark D. Roth09e458c2017-05-02 08:13:26 -07001888 }
1889 return true;
1890}
1891
Mark D. Rothc8875492018-02-20 08:33:48 -08001892} // namespace
1893
ncteisenadbfbd52017-11-16 15:35:45 -08001894void grpc_lb_policy_grpclb_init() {
Mark D. Rothc8875492018-02-20 08:33:48 -08001895 grpc_core::LoadBalancingPolicyRegistry::Builder::
1896 RegisterLoadBalancingPolicyFactory(
1897 grpc_core::UniquePtr<grpc_core::LoadBalancingPolicyFactory>(
1898 grpc_core::New<grpc_core::GrpcLbFactory>()));
Mark D. Roth09e458c2017-05-02 08:13:26 -07001899 grpc_channel_init_register_stage(GRPC_CLIENT_SUBCHANNEL,
1900 GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
1901 maybe_add_client_load_reporting_filter,
Craig Tillerbaa14a92017-11-03 09:09:36 -07001902 (void*)&grpc_client_load_reporting_filter);
David Garcia Quintas3fb8f732016-06-15 22:53:08 -07001903}
1904
ncteisenadbfbd52017-11-16 15:35:45 -08001905void grpc_lb_policy_grpclb_shutdown() {}