blob: 67dd3a1fa7ac8e3fd5a52ed5914b32cb5d3989af [file] [log] [blame]
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -08001/*
2 *
Jan Tattermusch7897ae92017-06-07 22:57:36 +02003 * Copyright 2015 gRPC authors.
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -08004 *
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
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -08008 *
Jan Tattermusch7897ae92017-06-07 22:57:36 +02009 * http://www.apache.org/licenses/LICENSE-2.0
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080010 *
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.
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080016 *
17 */
18
Yash Tibrewal37fdb732017-09-25 16:45:02 -070019#include <grpc/support/port_platform.h>
20
Craig Tiller9eb0fde2017-03-31 16:59:30 -070021#include "src/core/ext/filters/client_channel/client_channel.h"
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080022
Yash Tibrewalfcd26bc2017-09-25 15:08:28 -070023#include <inttypes.h>
Mark D. Roth718c8342018-02-28 13:00:04 -080024#include <limits.h>
Mark D. Roth4c0fe492016-08-31 13:51:55 -070025#include <stdbool.h>
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080026#include <stdio.h>
Craig Tillereb3b12e2015-06-26 14:42:49 -070027#include <string.h>
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080028
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080029#include <grpc/support/alloc.h>
30#include <grpc/support/log.h>
Mark D. Rothb2d24882016-10-27 15:44:07 -070031#include <grpc/support/string_util.h>
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080032#include <grpc/support/sync.h>
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080033
Yuchen Zeng0bad30a2017-10-05 21:47:39 -070034#include "src/core/ext/filters/client_channel/backup_poller.h"
Craig Tiller9eb0fde2017-03-31 16:59:30 -070035#include "src/core/ext/filters/client_channel/http_connect_handshaker.h"
36#include "src/core/ext/filters/client_channel/lb_policy_registry.h"
Mark D. Roth3e7f2df2018-02-26 13:17:06 -080037#include "src/core/ext/filters/client_channel/method_params.h"
Craig Tiller9eb0fde2017-03-31 16:59:30 -070038#include "src/core/ext/filters/client_channel/proxy_mapper_registry.h"
39#include "src/core/ext/filters/client_channel/resolver_registry.h"
40#include "src/core/ext/filters/client_channel/retry_throttle.h"
41#include "src/core/ext/filters/client_channel/subchannel.h"
Craig Tiller3be7dd02017-04-03 14:30:03 -070042#include "src/core/ext/filters/deadline/deadline_filter.h"
Mark D. Roth718c8342018-02-28 13:00:04 -080043#include "src/core/lib/backoff/backoff.h"
Craig Tiller9533d042016-03-25 17:11:06 -070044#include "src/core/lib/channel/channel_args.h"
45#include "src/core/lib/channel/connected_channel.h"
ncteisen3b42f832018-03-19 13:22:35 -070046#include "src/core/lib/channel/status_util.h"
Mark D. Rothdbdf4952018-01-18 11:21:12 -080047#include "src/core/lib/gpr/string.h"
Mark D. Roth718c8342018-02-28 13:00:04 -080048#include "src/core/lib/gprpp/inlined_vector.h"
49#include "src/core/lib/gprpp/manual_constructor.h"
Craig Tillerbefafe62017-02-09 11:30:54 -080050#include "src/core/lib/iomgr/combiner.h"
Craig Tiller9533d042016-03-25 17:11:06 -070051#include "src/core/lib/iomgr/iomgr.h"
Mark D. Roth4c0fe492016-08-31 13:51:55 -070052#include "src/core/lib/iomgr/polling_entity.h"
Craig Tiller9533d042016-03-25 17:11:06 -070053#include "src/core/lib/profiling/timers.h"
Craig Tiller7c70b6c2017-01-23 07:48:42 -080054#include "src/core/lib/slice/slice_internal.h"
Mark D. Roth718c8342018-02-28 13:00:04 -080055#include "src/core/lib/slice/slice_string_helpers.h"
Craig Tiller9533d042016-03-25 17:11:06 -070056#include "src/core/lib/surface/channel.h"
57#include "src/core/lib/transport/connectivity_state.h"
Mark D. Roth718c8342018-02-28 13:00:04 -080058#include "src/core/lib/transport/error_utils.h"
Mark D. Roth9fe284e2016-09-12 11:22:27 -070059#include "src/core/lib/transport/metadata.h"
60#include "src/core/lib/transport/metadata_batch.h"
Mark D. Rothea846a02016-11-03 11:32:54 -070061#include "src/core/lib/transport/service_config.h"
Mark D. Roth9fe284e2016-09-12 11:22:27 -070062#include "src/core/lib/transport/static_metadata.h"
Mark D. Roth718c8342018-02-28 13:00:04 -080063#include "src/core/lib/transport/status_metadata.h"
Craig Tiller8910ac62015-10-08 16:49:15 -070064
Mark D. Roth3e7f2df2018-02-26 13:17:06 -080065using grpc_core::internal::ClientChannelMethodParams;
66
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080067/* Client channel implementation */
68
Mark D. Roth718c8342018-02-28 13:00:04 -080069// By default, we buffer 256 KiB per RPC for retries.
70// TODO(roth): Do we have any data to suggest a better value?
71#define DEFAULT_PER_RPC_RETRY_BUFFER_SIZE (256 << 10)
72
73// This value was picked arbitrarily. It can be changed if there is
74// any even moderately compelling reason to do so.
75#define RETRY_BACKOFF_JITTER 0.2
76
Craig Tiller694580f2017-10-18 14:48:14 -070077grpc_core::TraceFlag grpc_client_channel_trace(false, "client_channel");
Mark D. Roth60751fe2017-07-07 12:50:33 -070078
Mark D. Roth26b7be42016-10-24 10:08:07 -070079/*************************************************************************
Mark D. Roth3e7f2df2018-02-26 13:17:06 -080080 * CHANNEL-WIDE FUNCTIONS
Mark D. Roth26b7be42016-10-24 10:08:07 -070081 */
82
Alexander Polcync3b1f182017-04-18 13:51:36 -070083struct external_connectivity_watcher;
84
Mark D. Roth3e7f2df2018-02-26 13:17:06 -080085typedef grpc_core::SliceHashTable<
86 grpc_core::RefCountedPtr<ClientChannelMethodParams>>
87 MethodParamsTable;
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080088
Craig Tiller800dacb2015-10-06 09:10:26 -070089typedef struct client_channel_channel_data {
Mark D. Roth209f6442018-02-08 10:26:46 -080090 grpc_core::OrphanablePtr<grpc_core::Resolver> resolver;
Mark D. Roth4c0fe492016-08-31 13:51:55 -070091 bool started_resolving;
Craig Tiller3be7dd02017-04-03 14:30:03 -070092 bool deadline_checking_enabled;
Craig Tillerbaa14a92017-11-03 09:09:36 -070093 grpc_client_channel_factory* client_channel_factory;
Mark D. Roth718c8342018-02-28 13:00:04 -080094 bool enable_retries;
95 size_t per_rpc_retry_buffer_size;
Craig Tillerf5f17122015-06-25 08:47:26 -070096
Craig Tillerbefafe62017-02-09 11:30:54 -080097 /** combiner protecting all variables below in this data structure */
Craig Tillerbaa14a92017-11-03 09:09:36 -070098 grpc_combiner* combiner;
Mark D. Roth046cf762016-09-26 11:13:51 -070099 /** currently active load balancer */
Mark D. Rothc8875492018-02-20 08:33:48 -0800100 grpc_core::OrphanablePtr<grpc_core::LoadBalancingPolicy> lb_policy;
Mark D. Rothd6d192d2017-02-23 08:58:42 -0800101 /** retry throttle data */
Craig Tillerbaa14a92017-11-03 09:09:36 -0700102 grpc_server_retry_throttle_data* retry_throttle_data;
Mark D. Roth9d480942016-10-19 14:18:05 -0700103 /** maps method names to method_parameters structs */
Mark D. Roth3e7f2df2018-02-26 13:17:06 -0800104 grpc_core::RefCountedPtr<MethodParamsTable> method_params_table;
Mark D. Roth046cf762016-09-26 11:13:51 -0700105 /** incoming resolver result - set by resolver.next() */
Craig Tillerbaa14a92017-11-03 09:09:36 -0700106 grpc_channel_args* resolver_result;
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700107 /** a list of closures that are all waiting for resolver result to come in */
108 grpc_closure_list waiting_for_resolver_result_closures;
Craig Tiller3f475422015-06-25 10:43:05 -0700109 /** resolver callback */
Mark D. Rothff4df062016-08-22 15:02:49 -0700110 grpc_closure on_resolver_result_changed;
Craig Tiller3f475422015-06-25 10:43:05 -0700111 /** connectivity state being tracked */
Craig Tillerca3e9d32015-06-27 18:37:27 -0700112 grpc_connectivity_state_tracker state_tracker;
Craig Tiller48cb07c2015-07-15 16:16:15 -0700113 /** when an lb_policy arrives, should we try to exit idle */
Mark D. Roth4c0fe492016-08-31 13:51:55 -0700114 bool exit_idle_when_lb_policy_arrives;
Craig Tiller906e3bc2015-11-24 07:31:31 -0800115 /** owning stack */
Craig Tillerbaa14a92017-11-03 09:09:36 -0700116 grpc_channel_stack* owning_stack;
Craig Tiller69b093b2016-02-25 19:04:07 -0800117 /** interested parties (owned) */
Craig Tillerbaa14a92017-11-03 09:09:36 -0700118 grpc_pollset_set* interested_parties;
Craig Tiller613dafa2017-02-09 12:00:43 -0800119
Alexander Polcync3b1f182017-04-18 13:51:36 -0700120 /* external_connectivity_watcher_list head is guarded by its own mutex, since
121 * counts need to be grabbed immediately without polling on a cq */
122 gpr_mu external_connectivity_watcher_list_mu;
Craig Tillerbaa14a92017-11-03 09:09:36 -0700123 struct external_connectivity_watcher* external_connectivity_watcher_list_head;
Alexander Polcync3b1f182017-04-18 13:51:36 -0700124
Mark D. Roth718c8342018-02-28 13:00:04 -0800125 /* the following properties are guarded by a mutex since APIs require them
Craig Tiller46dd7902017-02-23 09:42:16 -0800126 to be instantaneously available */
Craig Tiller613dafa2017-02-09 12:00:43 -0800127 gpr_mu info_mu;
Craig Tillerbaa14a92017-11-03 09:09:36 -0700128 char* info_lb_policy_name;
Craig Tiller613dafa2017-02-09 12:00:43 -0800129 /** service config in JSON form */
Craig Tillerbaa14a92017-11-03 09:09:36 -0700130 char* info_service_config_json;
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800131} channel_data;
132
Juanli Shen592cf342017-12-04 20:52:01 -0800133typedef struct {
134 channel_data* chand;
135 /** used as an identifier, don't dereference it because the LB policy may be
136 * non-existing when the callback is run */
Mark D. Rothc8875492018-02-20 08:33:48 -0800137 grpc_core::LoadBalancingPolicy* lb_policy;
Juanli Shen592cf342017-12-04 20:52:01 -0800138 grpc_closure closure;
139} reresolution_request_args;
140
Craig Tillerd6c98df2015-08-18 09:33:44 -0700141/** We create one watcher for each new lb_policy that is returned from a
Mark D. Roth4c0fe492016-08-31 13:51:55 -0700142 resolver, to watch for state changes from the lb_policy. When a state
143 change is seen, we update the channel, and create a new watcher. */
Craig Tillera82950e2015-09-22 12:33:20 -0700144typedef struct {
Craig Tillerbaa14a92017-11-03 09:09:36 -0700145 channel_data* chand;
Craig Tiller33825112015-09-18 07:44:19 -0700146 grpc_closure on_changed;
Craig Tiller1ada6ad2015-07-16 16:19:14 -0700147 grpc_connectivity_state state;
Mark D. Rothc8875492018-02-20 08:33:48 -0800148 grpc_core::LoadBalancingPolicy* lb_policy;
Craig Tiller1ada6ad2015-07-16 16:19:14 -0700149} lb_policy_connectivity_watcher;
150
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800151static void watch_lb_policy_locked(channel_data* chand,
Mark D. Rothc8875492018-02-20 08:33:48 -0800152 grpc_core::LoadBalancingPolicy* lb_policy,
Craig Tiller2400bf52017-02-09 16:25:19 -0800153 grpc_connectivity_state current_state);
Craig Tiller1ada6ad2015-07-16 16:19:14 -0700154
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800155static void set_channel_connectivity_state_locked(channel_data* chand,
Craig Tiller8c0d96f2016-03-11 14:27:52 -0800156 grpc_connectivity_state state,
Craig Tillerbaa14a92017-11-03 09:09:36 -0700157 grpc_error* error,
158 const char* reason) {
David Garcia Quintas37251282017-04-14 13:46:03 -0700159 /* TODO: Improve failure handling:
160 * - Make it possible for policies to return GRPC_CHANNEL_TRANSIENT_FAILURE.
161 * - Hand over pending picks from old policies during the switch that happens
162 * when resolver provides an update. */
Craig Tiller4782d922017-11-10 09:53:21 -0800163 if (chand->lb_policy != nullptr) {
David Garcia Quintas956f7002017-04-13 15:40:06 -0700164 if (state == GRPC_CHANNEL_TRANSIENT_FAILURE) {
165 /* cancel picks with wait_for_ready=false */
Mark D. Rothc8875492018-02-20 08:33:48 -0800166 chand->lb_policy->CancelMatchingPicksLocked(
David Garcia Quintas956f7002017-04-13 15:40:06 -0700167 /* mask= */ GRPC_INITIAL_METADATA_WAIT_FOR_READY,
168 /* check= */ 0, GRPC_ERROR_REF(error));
169 } else if (state == GRPC_CHANNEL_SHUTDOWN) {
170 /* cancel all picks */
Mark D. Rothc8875492018-02-20 08:33:48 -0800171 chand->lb_policy->CancelMatchingPicksLocked(/* mask= */ 0, /* check= */ 0,
172 GRPC_ERROR_REF(error));
David Garcia Quintas956f7002017-04-13 15:40:06 -0700173 }
Craig Tiller8c0d96f2016-03-11 14:27:52 -0800174 }
Craig Tiller6014e8a2017-10-16 13:50:29 -0700175 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth60751fe2017-07-07 12:50:33 -0700176 gpr_log(GPR_DEBUG, "chand=%p: setting connectivity state to %s", chand,
177 grpc_connectivity_state_name(state));
178 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800179 grpc_connectivity_state_set(&chand->state_tracker, state, error, reason);
Craig Tiller8c0d96f2016-03-11 14:27:52 -0800180}
181
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800182static void on_lb_policy_state_changed_locked(void* arg, grpc_error* error) {
Noah Eisen4d20a662018-02-09 09:34:04 -0800183 lb_policy_connectivity_watcher* w =
184 static_cast<lb_policy_connectivity_watcher*>(arg);
Craig Tillerc5de8352017-02-09 14:08:05 -0800185 /* check if the notification is for the latest policy */
Mark D. Rothc8875492018-02-20 08:33:48 -0800186 if (w->lb_policy == w->chand->lb_policy.get()) {
Craig Tiller6014e8a2017-10-16 13:50:29 -0700187 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth60751fe2017-07-07 12:50:33 -0700188 gpr_log(GPR_DEBUG, "chand=%p: lb_policy=%p state changed to %s", w->chand,
189 w->lb_policy, grpc_connectivity_state_name(w->state));
190 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800191 set_channel_connectivity_state_locked(w->chand, w->state,
Craig Tillerc5de8352017-02-09 14:08:05 -0800192 GRPC_ERROR_REF(error), "lb_changed");
193 if (w->state != GRPC_CHANNEL_SHUTDOWN) {
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800194 watch_lb_policy_locked(w->chand, w->lb_policy, w->state);
Craig Tillerc5de8352017-02-09 14:08:05 -0800195 }
Craig Tillera82950e2015-09-22 12:33:20 -0700196 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800197 GRPC_CHANNEL_STACK_UNREF(w->chand->owning_stack, "watch_lb_policy");
Craig Tillera82950e2015-09-22 12:33:20 -0700198 gpr_free(w);
Craig Tiller1ada6ad2015-07-16 16:19:14 -0700199}
200
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800201static void watch_lb_policy_locked(channel_data* chand,
Mark D. Rothc8875492018-02-20 08:33:48 -0800202 grpc_core::LoadBalancingPolicy* lb_policy,
Craig Tiller2400bf52017-02-09 16:25:19 -0800203 grpc_connectivity_state current_state) {
Craig Tillerbaa14a92017-11-03 09:09:36 -0700204 lb_policy_connectivity_watcher* w =
Noah Eisenbe82e642018-02-09 09:16:55 -0800205 static_cast<lb_policy_connectivity_watcher*>(gpr_malloc(sizeof(*w)));
Craig Tiller906e3bc2015-11-24 07:31:31 -0800206 GRPC_CHANNEL_STACK_REF(chand->owning_stack, "watch_lb_policy");
Craig Tiller1ada6ad2015-07-16 16:19:14 -0700207 w->chand = chand;
ncteisen274bbbe2017-06-08 14:57:11 -0700208 GRPC_CLOSURE_INIT(&w->on_changed, on_lb_policy_state_changed_locked, w,
Craig Tilleree4b1452017-05-12 10:56:03 -0700209 grpc_combiner_scheduler(chand->combiner));
Craig Tiller1ada6ad2015-07-16 16:19:14 -0700210 w->state = current_state;
211 w->lb_policy = lb_policy;
Mark D. Rothc8875492018-02-20 08:33:48 -0800212 lb_policy->NotifyOnStateChangeLocked(&w->state, &w->on_changed);
Craig Tiller1ada6ad2015-07-16 16:19:14 -0700213}
214
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800215static void start_resolving_locked(channel_data* chand) {
Craig Tiller6014e8a2017-10-16 13:50:29 -0700216 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth60751fe2017-07-07 12:50:33 -0700217 gpr_log(GPR_DEBUG, "chand=%p: starting name resolution", chand);
218 }
219 GPR_ASSERT(!chand->started_resolving);
220 chand->started_resolving = true;
221 GRPC_CHANNEL_STACK_REF(chand->owning_stack, "resolver");
Mark D. Roth209f6442018-02-08 10:26:46 -0800222 chand->resolver->NextLocked(&chand->resolver_result,
223 &chand->on_resolver_result_changed);
Mark D. Roth60751fe2017-07-07 12:50:33 -0700224}
225
Mark D. Rothd6d192d2017-02-23 08:58:42 -0800226typedef struct {
Craig Tillerbaa14a92017-11-03 09:09:36 -0700227 char* server_name;
228 grpc_server_retry_throttle_data* retry_throttle_data;
Mark D. Rothd6d192d2017-02-23 08:58:42 -0800229} service_config_parsing_state;
230
Mark D. Roth3e7f2df2018-02-26 13:17:06 -0800231static void parse_retry_throttle_params(
232 const grpc_json* field, service_config_parsing_state* parsing_state) {
Mark D. Rothd6d192d2017-02-23 08:58:42 -0800233 if (strcmp(field->key, "retryThrottling") == 0) {
Craig Tiller4782d922017-11-10 09:53:21 -0800234 if (parsing_state->retry_throttle_data != nullptr) return; // Duplicate.
Mark D. Rothd6d192d2017-02-23 08:58:42 -0800235 if (field->type != GRPC_JSON_OBJECT) return;
236 int max_milli_tokens = 0;
237 int milli_token_ratio = 0;
Craig Tiller4782d922017-11-10 09:53:21 -0800238 for (grpc_json* sub_field = field->child; sub_field != nullptr;
Mark D. Rothd6d192d2017-02-23 08:58:42 -0800239 sub_field = sub_field->next) {
Craig Tiller4782d922017-11-10 09:53:21 -0800240 if (sub_field->key == nullptr) return;
Mark D. Rothd6d192d2017-02-23 08:58:42 -0800241 if (strcmp(sub_field->key, "maxTokens") == 0) {
242 if (max_milli_tokens != 0) return; // Duplicate.
243 if (sub_field->type != GRPC_JSON_NUMBER) return;
244 max_milli_tokens = gpr_parse_nonnegative_int(sub_field->value);
245 if (max_milli_tokens == -1) return;
246 max_milli_tokens *= 1000;
247 } else if (strcmp(sub_field->key, "tokenRatio") == 0) {
248 if (milli_token_ratio != 0) return; // Duplicate.
249 if (sub_field->type != GRPC_JSON_NUMBER) return;
250 // We support up to 3 decimal digits.
251 size_t whole_len = strlen(sub_field->value);
252 uint32_t multiplier = 1;
253 uint32_t decimal_value = 0;
Craig Tillerbaa14a92017-11-03 09:09:36 -0700254 const char* decimal_point = strchr(sub_field->value, '.');
Craig Tiller4782d922017-11-10 09:53:21 -0800255 if (decimal_point != nullptr) {
Noah Eisenbe82e642018-02-09 09:16:55 -0800256 whole_len = static_cast<size_t>(decimal_point - sub_field->value);
Mark D. Rothd6d192d2017-02-23 08:58:42 -0800257 multiplier = 1000;
258 size_t decimal_len = strlen(decimal_point + 1);
259 if (decimal_len > 3) decimal_len = 3;
260 if (!gpr_parse_bytes_to_uint32(decimal_point + 1, decimal_len,
261 &decimal_value)) {
262 return;
263 }
264 uint32_t decimal_multiplier = 1;
265 for (size_t i = 0; i < (3 - decimal_len); ++i) {
266 decimal_multiplier *= 10;
267 }
268 decimal_value *= decimal_multiplier;
269 }
270 uint32_t whole_value;
271 if (!gpr_parse_bytes_to_uint32(sub_field->value, whole_len,
272 &whole_value)) {
273 return;
274 }
Noah Eisen4d20a662018-02-09 09:34:04 -0800275 milli_token_ratio =
276 static_cast<int>((whole_value * multiplier) + decimal_value);
Mark D. Rothb3322562017-02-23 14:38:02 -0800277 if (milli_token_ratio <= 0) return;
Mark D. Rothd6d192d2017-02-23 08:58:42 -0800278 }
279 }
280 parsing_state->retry_throttle_data =
281 grpc_retry_throttle_map_get_data_for_server(
282 parsing_state->server_name, max_milli_tokens, milli_token_ratio);
283 }
284}
285
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800286static void request_reresolution_locked(void* arg, grpc_error* error) {
Noah Eisen4d20a662018-02-09 09:34:04 -0800287 reresolution_request_args* args =
288 static_cast<reresolution_request_args*>(arg);
Juanli Shen592cf342017-12-04 20:52:01 -0800289 channel_data* chand = args->chand;
290 // If this invocation is for a stale LB policy, treat it as an LB shutdown
291 // signal.
Mark D. Rothc8875492018-02-20 08:33:48 -0800292 if (args->lb_policy != chand->lb_policy.get() || error != GRPC_ERROR_NONE ||
Juanli Shen592cf342017-12-04 20:52:01 -0800293 chand->resolver == nullptr) {
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800294 GRPC_CHANNEL_STACK_UNREF(chand->owning_stack, "re-resolution");
Juanli Shen592cf342017-12-04 20:52:01 -0800295 gpr_free(args);
296 return;
297 }
298 if (grpc_client_channel_trace.enabled()) {
299 gpr_log(GPR_DEBUG, "chand=%p: started name re-resolving", chand);
300 }
Mark D. Roth209f6442018-02-08 10:26:46 -0800301 chand->resolver->RequestReresolutionLocked();
Juanli Shen592cf342017-12-04 20:52:01 -0800302 // Give back the closure to the LB policy.
Mark D. Rothc8875492018-02-20 08:33:48 -0800303 chand->lb_policy->SetReresolutionClosureLocked(&args->closure);
Juanli Shen592cf342017-12-04 20:52:01 -0800304}
305
Mark D. Rothe63e06d2018-03-23 08:12:11 -0700306// TODO(roth): The logic in this function is very hard to follow. We
307// should refactor this so that it's easier to understand, perhaps as
308// part of changing the resolver API to more clearly differentiate
309// between transient failures and shutdown.
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800310static void on_resolver_result_changed_locked(void* arg, grpc_error* error) {
Noah Eisenbe82e642018-02-09 09:16:55 -0800311 channel_data* chand = static_cast<channel_data*>(arg);
Craig Tiller6014e8a2017-10-16 13:50:29 -0700312 if (grpc_client_channel_trace.enabled()) {
Mark D. Rothe63e06d2018-03-23 08:12:11 -0700313 gpr_log(GPR_DEBUG,
314 "chand=%p: got resolver result: resolver_result=%p error=%s", chand,
315 chand->resolver_result, grpc_error_string(error));
Mark D. Roth60751fe2017-07-07 12:50:33 -0700316 }
Mark D. Roth718c8342018-02-28 13:00:04 -0800317 // Extract the following fields from the resolver result, if non-nullptr.
Mark D. Roth15494b52017-07-12 15:26:55 -0700318 bool lb_policy_updated = false;
Mark D. Rothc8875492018-02-20 08:33:48 -0800319 bool lb_policy_created = false;
Craig Tiller4782d922017-11-10 09:53:21 -0800320 char* lb_policy_name_dup = nullptr;
Mark D. Roth60751fe2017-07-07 12:50:33 -0700321 bool lb_policy_name_changed = false;
Mark D. Rothc8875492018-02-20 08:33:48 -0800322 grpc_core::OrphanablePtr<grpc_core::LoadBalancingPolicy> new_lb_policy;
Craig Tiller4782d922017-11-10 09:53:21 -0800323 char* service_config_json = nullptr;
324 grpc_server_retry_throttle_data* retry_throttle_data = nullptr;
Mark D. Roth3e7f2df2018-02-26 13:17:06 -0800325 grpc_core::RefCountedPtr<MethodParamsTable> method_params_table;
Craig Tiller4782d922017-11-10 09:53:21 -0800326 if (chand->resolver_result != nullptr) {
Juanli Shen592cf342017-12-04 20:52:01 -0800327 if (chand->resolver != nullptr) {
328 // Find LB policy name.
Juanli Shen592cf342017-12-04 20:52:01 -0800329 const grpc_arg* channel_arg = grpc_channel_args_find(
330 chand->resolver_result, GRPC_ARG_LB_POLICY_NAME);
ncteisenbf323a92018-02-14 17:34:05 -0800331 const char* lb_policy_name = grpc_channel_arg_get_string(channel_arg);
Juanli Shen592cf342017-12-04 20:52:01 -0800332 // Special case: If at least one balancer address is present, we use
333 // the grpclb policy, regardless of what the resolver actually specified.
334 channel_arg =
335 grpc_channel_args_find(chand->resolver_result, GRPC_ARG_LB_ADDRESSES);
336 if (channel_arg != nullptr && channel_arg->type == GRPC_ARG_POINTER) {
337 grpc_lb_addresses* addresses =
Noah Eisenbe82e642018-02-09 09:16:55 -0800338 static_cast<grpc_lb_addresses*>(channel_arg->value.pointer.p);
Juanli Shen592cf342017-12-04 20:52:01 -0800339 bool found_balancer_address = false;
340 for (size_t i = 0; i < addresses->num_addresses; ++i) {
341 if (addresses->addresses[i].is_balancer) {
342 found_balancer_address = true;
343 break;
344 }
345 }
346 if (found_balancer_address) {
347 if (lb_policy_name != nullptr &&
348 strcmp(lb_policy_name, "grpclb") != 0) {
349 gpr_log(GPR_INFO,
350 "resolver requested LB policy %s but provided at least one "
351 "balancer address -- forcing use of grpclb LB policy",
352 lb_policy_name);
353 }
354 lb_policy_name = "grpclb";
355 }
356 }
357 // Use pick_first if nothing was specified and we didn't select grpclb
358 // above.
359 if (lb_policy_name == nullptr) lb_policy_name = "pick_first";
Juanli Shen592cf342017-12-04 20:52:01 -0800360 // Check to see if we're already using the right LB policy.
361 // Note: It's safe to use chand->info_lb_policy_name here without
362 // taking a lock on chand->info_mu, because this function is the
363 // only thing that modifies its value, and it can only be invoked
364 // once at any given time.
365 lb_policy_name_changed =
366 chand->info_lb_policy_name == nullptr ||
367 gpr_stricmp(chand->info_lb_policy_name, lb_policy_name) != 0;
368 if (chand->lb_policy != nullptr && !lb_policy_name_changed) {
369 // Continue using the same LB policy. Update with new addresses.
370 lb_policy_updated = true;
Mark D. Rothc8875492018-02-20 08:33:48 -0800371 chand->lb_policy->UpdateLocked(*chand->resolver_result);
Juanli Shen592cf342017-12-04 20:52:01 -0800372 } else {
373 // Instantiate new LB policy.
Mark D. Rothc8875492018-02-20 08:33:48 -0800374 grpc_core::LoadBalancingPolicy::Args lb_policy_args;
375 lb_policy_args.combiner = chand->combiner;
376 lb_policy_args.client_channel_factory = chand->client_channel_factory;
377 lb_policy_args.args = chand->resolver_result;
378 new_lb_policy =
379 grpc_core::LoadBalancingPolicyRegistry::CreateLoadBalancingPolicy(
380 lb_policy_name, lb_policy_args);
Juanli Shen592cf342017-12-04 20:52:01 -0800381 if (new_lb_policy == nullptr) {
382 gpr_log(GPR_ERROR, "could not create LB policy \"%s\"",
383 lb_policy_name);
384 } else {
Mark D. Roth3ef4af22018-02-21 07:53:26 -0800385 lb_policy_created = true;
Juanli Shen592cf342017-12-04 20:52:01 -0800386 reresolution_request_args* args =
Noah Eisen4d20a662018-02-09 09:34:04 -0800387 static_cast<reresolution_request_args*>(
388 gpr_zalloc(sizeof(*args)));
Juanli Shen592cf342017-12-04 20:52:01 -0800389 args->chand = chand;
Mark D. Rothc8875492018-02-20 08:33:48 -0800390 args->lb_policy = new_lb_policy.get();
Juanli Shen592cf342017-12-04 20:52:01 -0800391 GRPC_CLOSURE_INIT(&args->closure, request_reresolution_locked, args,
392 grpc_combiner_scheduler(chand->combiner));
393 GRPC_CHANNEL_STACK_REF(chand->owning_stack, "re-resolution");
Mark D. Rothc8875492018-02-20 08:33:48 -0800394 new_lb_policy->SetReresolutionClosureLocked(&args->closure);
Juanli Shen592cf342017-12-04 20:52:01 -0800395 }
396 }
Mark D. Roth718c8342018-02-28 13:00:04 -0800397 // Before we clean up, save a copy of lb_policy_name, since it might
398 // be pointing to data inside chand->resolver_result.
399 // The copy will be saved in chand->lb_policy_name below.
400 lb_policy_name_dup = gpr_strdup(lb_policy_name);
Juanli Shen592cf342017-12-04 20:52:01 -0800401 // Find service config.
402 channel_arg = grpc_channel_args_find(chand->resolver_result,
403 GRPC_ARG_SERVICE_CONFIG);
ncteisenbf323a92018-02-14 17:34:05 -0800404 service_config_json =
405 gpr_strdup(grpc_channel_arg_get_string(channel_arg));
406 if (service_config_json != nullptr) {
Mark D. Roth3e7f2df2018-02-26 13:17:06 -0800407 grpc_core::UniquePtr<grpc_core::ServiceConfig> service_config =
408 grpc_core::ServiceConfig::Create(service_config_json);
Juanli Shen592cf342017-12-04 20:52:01 -0800409 if (service_config != nullptr) {
Mark D. Roth718c8342018-02-28 13:00:04 -0800410 if (chand->enable_retries) {
411 channel_arg = grpc_channel_args_find(chand->resolver_result,
412 GRPC_ARG_SERVER_URI);
413 const char* server_uri = grpc_channel_arg_get_string(channel_arg);
414 GPR_ASSERT(server_uri != nullptr);
415 grpc_uri* uri = grpc_uri_parse(server_uri, true);
416 GPR_ASSERT(uri->path[0] != '\0');
417 service_config_parsing_state parsing_state;
418 memset(&parsing_state, 0, sizeof(parsing_state));
419 parsing_state.server_name =
420 uri->path[0] == '/' ? uri->path + 1 : uri->path;
421 service_config->ParseGlobalParams(parse_retry_throttle_params,
422 &parsing_state);
423 grpc_uri_destroy(uri);
424 retry_throttle_data = parsing_state.retry_throttle_data;
425 }
Mark D. Roth3e7f2df2018-02-26 13:17:06 -0800426 method_params_table = service_config->CreateMethodConfigTable(
427 ClientChannelMethodParams::CreateFromJson);
Juanli Shen592cf342017-12-04 20:52:01 -0800428 }
429 }
Mark D. Roth9fe284e2016-09-12 11:22:27 -0700430 }
Craig Tillera82950e2015-09-22 12:33:20 -0700431 }
Craig Tiller6014e8a2017-10-16 13:50:29 -0700432 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth60751fe2017-07-07 12:50:33 -0700433 gpr_log(GPR_DEBUG,
434 "chand=%p: resolver result: lb_policy_name=\"%s\"%s, "
435 "service_config=\"%s\"",
Yash Tibrewal9eb86722017-09-17 23:43:30 -0700436 chand, lb_policy_name_dup,
437 lb_policy_name_changed ? " (changed)" : "", service_config_json);
Mark D. Roth60751fe2017-07-07 12:50:33 -0700438 }
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700439 // Now swap out fields in chand. Note that the new values may still
Mark D. Roth718c8342018-02-28 13:00:04 -0800440 // be nullptr if (e.g.) the resolver failed to return results or the
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700441 // results did not contain the necessary data.
442 //
443 // First, swap out the data used by cc_get_channel_info().
Craig Tiller613dafa2017-02-09 12:00:43 -0800444 gpr_mu_lock(&chand->info_mu);
Craig Tiller4782d922017-11-10 09:53:21 -0800445 if (lb_policy_name_dup != nullptr) {
Craig Tiller613dafa2017-02-09 12:00:43 -0800446 gpr_free(chand->info_lb_policy_name);
Yash Tibrewal9eb86722017-09-17 23:43:30 -0700447 chand->info_lb_policy_name = lb_policy_name_dup;
Mark D. Rothb2d24882016-10-27 15:44:07 -0700448 }
Craig Tiller4782d922017-11-10 09:53:21 -0800449 if (service_config_json != nullptr) {
Craig Tiller613dafa2017-02-09 12:00:43 -0800450 gpr_free(chand->info_service_config_json);
451 chand->info_service_config_json = service_config_json;
Mark D. Rothc625c7a2016-11-09 14:12:37 -0800452 }
Craig Tiller613dafa2017-02-09 12:00:43 -0800453 gpr_mu_unlock(&chand->info_mu);
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700454 // Swap out the retry throttle data.
Craig Tiller4782d922017-11-10 09:53:21 -0800455 if (chand->retry_throttle_data != nullptr) {
Mark D. Rothd6d192d2017-02-23 08:58:42 -0800456 grpc_server_retry_throttle_data_unref(chand->retry_throttle_data);
457 }
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700458 chand->retry_throttle_data = retry_throttle_data;
459 // Swap out the method params table.
Mark D. Roth3e7f2df2018-02-26 13:17:06 -0800460 chand->method_params_table = std::move(method_params_table);
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700461 // If we have a new LB policy or are shutting down (in which case
Mark D. Roth718c8342018-02-28 13:00:04 -0800462 // new_lb_policy will be nullptr), swap out the LB policy, unreffing the
463 // old one and removing its fds from chand->interested_parties.
464 // Note that we do NOT do this if either (a) we updated the existing
465 // LB policy above or (b) we failed to create the new LB policy (in
466 // which case we want to continue using the most recent one we had).
Craig Tiller4782d922017-11-10 09:53:21 -0800467 if (new_lb_policy != nullptr || error != GRPC_ERROR_NONE ||
468 chand->resolver == nullptr) {
469 if (chand->lb_policy != nullptr) {
Craig Tiller6014e8a2017-10-16 13:50:29 -0700470 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth60751fe2017-07-07 12:50:33 -0700471 gpr_log(GPR_DEBUG, "chand=%p: unreffing lb_policy=%p", chand,
Mark D. Rothc8875492018-02-20 08:33:48 -0800472 chand->lb_policy.get());
Mark D. Roth60751fe2017-07-07 12:50:33 -0700473 }
Mark D. Rothc8875492018-02-20 08:33:48 -0800474 grpc_pollset_set_del_pollset_set(chand->lb_policy->interested_parties(),
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700475 chand->interested_parties);
Mark D. Rothc8875492018-02-20 08:33:48 -0800476 chand->lb_policy->HandOffPendingPicksLocked(new_lb_policy.get());
477 chand->lb_policy.reset();
Craig Tiller45724b32015-09-22 10:42:19 -0700478 }
Mark D. Rothc8875492018-02-20 08:33:48 -0800479 chand->lb_policy = std::move(new_lb_policy);
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700480 }
481 // Now that we've swapped out the relevant fields of chand, check for
482 // error or shutdown.
Craig Tiller4782d922017-11-10 09:53:21 -0800483 if (error != GRPC_ERROR_NONE || chand->resolver == nullptr) {
Craig Tiller6014e8a2017-10-16 13:50:29 -0700484 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth60751fe2017-07-07 12:50:33 -0700485 gpr_log(GPR_DEBUG, "chand=%p: shutting down", chand);
486 }
Craig Tiller4782d922017-11-10 09:53:21 -0800487 if (chand->resolver != nullptr) {
Craig Tiller6014e8a2017-10-16 13:50:29 -0700488 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth60751fe2017-07-07 12:50:33 -0700489 gpr_log(GPR_DEBUG, "chand=%p: shutting down resolver", chand);
490 }
Mark D. Roth209f6442018-02-08 10:26:46 -0800491 chand->resolver.reset();
Craig Tiller76a5c0e2016-03-09 09:05:30 -0800492 }
Craig Tiller8c0d96f2016-03-11 14:27:52 -0800493 set_channel_connectivity_state_locked(
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800494 chand, GRPC_CHANNEL_SHUTDOWN,
ncteisen4b36a3d2017-03-13 19:08:06 -0700495 GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700496 "Got resolver result after disconnection", &error, 1),
Craig Tiller804ff712016-05-05 16:25:40 -0700497 "resolver_gone");
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700498 grpc_closure_list_fail_all(&chand->waiting_for_resolver_result_closures,
499 GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
500 "Channel disconnected", &error, 1));
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800501 GRPC_CLOSURE_LIST_SCHED(&chand->waiting_for_resolver_result_closures);
Mark D. Roth1b95f472018-02-15 12:54:02 -0800502 GRPC_CHANNEL_STACK_UNREF(chand->owning_stack, "resolver");
Mark D. Rothe63e06d2018-03-23 08:12:11 -0700503 grpc_channel_args_destroy(chand->resolver_result);
504 chand->resolver_result = nullptr;
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700505 } else { // Not shutting down.
506 grpc_connectivity_state state = GRPC_CHANNEL_TRANSIENT_FAILURE;
Craig Tillerbaa14a92017-11-03 09:09:36 -0700507 grpc_error* state_error =
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700508 GRPC_ERROR_CREATE_FROM_STATIC_STRING("No load balancing policy");
Mark D. Rothc8875492018-02-20 08:33:48 -0800509 if (lb_policy_created) {
Craig Tiller6014e8a2017-10-16 13:50:29 -0700510 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth60751fe2017-07-07 12:50:33 -0700511 gpr_log(GPR_DEBUG, "chand=%p: initializing new LB policy", chand);
512 }
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700513 GRPC_ERROR_UNREF(state_error);
Mark D. Rothc8875492018-02-20 08:33:48 -0800514 state = chand->lb_policy->CheckConnectivityLocked(&state_error);
515 grpc_pollset_set_add_pollset_set(chand->lb_policy->interested_parties(),
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700516 chand->interested_parties);
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800517 GRPC_CLOSURE_LIST_SCHED(&chand->waiting_for_resolver_result_closures);
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700518 if (chand->exit_idle_when_lb_policy_arrives) {
Mark D. Rothc8875492018-02-20 08:33:48 -0800519 chand->lb_policy->ExitIdleLocked();
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700520 chand->exit_idle_when_lb_policy_arrives = false;
521 }
Mark D. Rothc8875492018-02-20 08:33:48 -0800522 watch_lb_policy_locked(chand, chand->lb_policy.get(), state);
Mark D. Rothe63e06d2018-03-23 08:12:11 -0700523 } else if (chand->resolver_result == nullptr) {
524 // Transient failure.
525 GRPC_CLOSURE_LIST_SCHED(&chand->waiting_for_resolver_result_closures);
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700526 }
Mark D. Roth15494b52017-07-12 15:26:55 -0700527 if (!lb_policy_updated) {
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800528 set_channel_connectivity_state_locked(
529 chand, state, GRPC_ERROR_REF(state_error), "new_lb+resolver");
Mark D. Roth15494b52017-07-12 15:26:55 -0700530 }
Mark D. Rothe63e06d2018-03-23 08:12:11 -0700531 grpc_channel_args_destroy(chand->resolver_result);
532 chand->resolver_result = nullptr;
Mark D. Roth209f6442018-02-08 10:26:46 -0800533 chand->resolver->NextLocked(&chand->resolver_result,
534 &chand->on_resolver_result_changed);
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700535 GRPC_ERROR_UNREF(state_error);
Craig Tillera82950e2015-09-22 12:33:20 -0700536 }
Craig Tiller3f475422015-06-25 10:43:05 -0700537}
538
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800539static void start_transport_op_locked(void* arg, grpc_error* error_ignored) {
Noah Eisenbe82e642018-02-09 09:16:55 -0800540 grpc_transport_op* op = static_cast<grpc_transport_op*>(arg);
Craig Tillerbaa14a92017-11-03 09:09:36 -0700541 grpc_channel_element* elem =
Noah Eisenbe82e642018-02-09 09:16:55 -0800542 static_cast<grpc_channel_element*>(op->handler_private.extra_arg);
543 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Craig Tiller000cd8f2015-09-18 07:20:29 -0700544
Craig Tiller4782d922017-11-10 09:53:21 -0800545 if (op->on_connectivity_state_change != nullptr) {
Craig Tillera82950e2015-09-22 12:33:20 -0700546 grpc_connectivity_state_notify_on_state_change(
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800547 &chand->state_tracker, op->connectivity_state,
Craig Tillera82950e2015-09-22 12:33:20 -0700548 op->on_connectivity_state_change);
Craig Tiller4782d922017-11-10 09:53:21 -0800549 op->on_connectivity_state_change = nullptr;
550 op->connectivity_state = nullptr;
Craig Tillera82950e2015-09-22 12:33:20 -0700551 }
552
Yuchen Zengc272dd72017-12-05 12:18:34 -0800553 if (op->send_ping.on_initiate != nullptr || op->send_ping.on_ack != nullptr) {
Craig Tiller4782d922017-11-10 09:53:21 -0800554 if (chand->lb_policy == nullptr) {
ncteisen274bbbe2017-06-08 14:57:11 -0700555 GRPC_CLOSURE_SCHED(
Yash Tibrewald6c292f2017-12-07 19:38:43 -0800556 op->send_ping.on_initiate,
Yuchen Zengc272dd72017-12-05 12:18:34 -0800557 GRPC_ERROR_CREATE_FROM_STATIC_STRING("Ping with no load balancing"));
558 GRPC_CLOSURE_SCHED(
Yash Tibrewald6c292f2017-12-07 19:38:43 -0800559 op->send_ping.on_ack,
ncteisen4b36a3d2017-03-13 19:08:06 -0700560 GRPC_ERROR_CREATE_FROM_STATIC_STRING("Ping with no load balancing"));
Craig Tiller26dab312015-12-07 14:43:47 -0800561 } else {
Mark D. Rothc8875492018-02-20 08:33:48 -0800562 chand->lb_policy->PingOneLocked(op->send_ping.on_initiate,
563 op->send_ping.on_ack);
Craig Tiller4782d922017-11-10 09:53:21 -0800564 op->bind_pollset = nullptr;
Craig Tiller26dab312015-12-07 14:43:47 -0800565 }
Yuchen Zengc272dd72017-12-05 12:18:34 -0800566 op->send_ping.on_initiate = nullptr;
567 op->send_ping.on_ack = nullptr;
Craig Tiller26dab312015-12-07 14:43:47 -0800568 }
569
Craig Tiller1c51edc2016-05-07 16:18:43 -0700570 if (op->disconnect_with_error != GRPC_ERROR_NONE) {
Craig Tiller4782d922017-11-10 09:53:21 -0800571 if (chand->resolver != nullptr) {
Craig Tiller1c51edc2016-05-07 16:18:43 -0700572 set_channel_connectivity_state_locked(
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800573 chand, GRPC_CHANNEL_SHUTDOWN,
Craig Tiller1c51edc2016-05-07 16:18:43 -0700574 GRPC_ERROR_REF(op->disconnect_with_error), "disconnect");
Mark D. Roth209f6442018-02-08 10:26:46 -0800575 chand->resolver.reset();
Craig Tiller1c51edc2016-05-07 16:18:43 -0700576 if (!chand->started_resolving) {
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700577 grpc_closure_list_fail_all(&chand->waiting_for_resolver_result_closures,
Craig Tiller1c51edc2016-05-07 16:18:43 -0700578 GRPC_ERROR_REF(op->disconnect_with_error));
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800579 GRPC_CLOSURE_LIST_SCHED(&chand->waiting_for_resolver_result_closures);
Craig Tiller1c51edc2016-05-07 16:18:43 -0700580 }
Craig Tiller4782d922017-11-10 09:53:21 -0800581 if (chand->lb_policy != nullptr) {
Mark D. Rothc8875492018-02-20 08:33:48 -0800582 grpc_pollset_set_del_pollset_set(chand->lb_policy->interested_parties(),
Craig Tiller1c51edc2016-05-07 16:18:43 -0700583 chand->interested_parties);
Mark D. Rothc8875492018-02-20 08:33:48 -0800584 chand->lb_policy.reset();
Craig Tiller1c51edc2016-05-07 16:18:43 -0700585 }
Craig Tillerb12d22a2016-04-23 12:50:21 -0700586 }
Craig Tiller1c51edc2016-05-07 16:18:43 -0700587 GRPC_ERROR_UNREF(op->disconnect_with_error);
Craig Tillera82950e2015-09-22 12:33:20 -0700588 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800589 GRPC_CHANNEL_STACK_UNREF(chand->owning_stack, "start_transport_op");
Craig Tillerd2e5cfc2017-02-09 13:02:20 -0800590
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800591 GRPC_CLOSURE_SCHED(op->on_consumed, GRPC_ERROR_NONE);
Craig Tillerbefafe62017-02-09 11:30:54 -0800592}
593
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800594static void cc_start_transport_op(grpc_channel_element* elem,
Craig Tillerbaa14a92017-11-03 09:09:36 -0700595 grpc_transport_op* op) {
Noah Eisenbe82e642018-02-09 09:16:55 -0800596 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Craig Tillerbefafe62017-02-09 11:30:54 -0800597
Craig Tillerbefafe62017-02-09 11:30:54 -0800598 GPR_ASSERT(op->set_accept_stream == false);
Craig Tiller4782d922017-11-10 09:53:21 -0800599 if (op->bind_pollset != nullptr) {
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800600 grpc_pollset_set_add_pollset(chand->interested_parties, op->bind_pollset);
Craig Tillerbefafe62017-02-09 11:30:54 -0800601 }
602
Craig Tillerc55c1022017-03-10 10:26:42 -0800603 op->handler_private.extra_arg = elem;
Craig Tillerd2e5cfc2017-02-09 13:02:20 -0800604 GRPC_CHANNEL_STACK_REF(chand->owning_stack, "start_transport_op");
ncteisen274bbbe2017-06-08 14:57:11 -0700605 GRPC_CLOSURE_SCHED(
ncteisen274bbbe2017-06-08 14:57:11 -0700606 GRPC_CLOSURE_INIT(&op->handler_private.closure, start_transport_op_locked,
Craig Tilleree4b1452017-05-12 10:56:03 -0700607 op, grpc_combiner_scheduler(chand->combiner)),
Craig Tillerbefafe62017-02-09 11:30:54 -0800608 GRPC_ERROR_NONE);
Craig Tillerca3e9d32015-06-27 18:37:27 -0700609}
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800610
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800611static void cc_get_channel_info(grpc_channel_element* elem,
Craig Tillerbaa14a92017-11-03 09:09:36 -0700612 const grpc_channel_info* info) {
Noah Eisenbe82e642018-02-09 09:16:55 -0800613 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Craig Tiller613dafa2017-02-09 12:00:43 -0800614 gpr_mu_lock(&chand->info_mu);
Craig Tiller4782d922017-11-10 09:53:21 -0800615 if (info->lb_policy_name != nullptr) {
616 *info->lb_policy_name = chand->info_lb_policy_name == nullptr
617 ? nullptr
Craig Tiller613dafa2017-02-09 12:00:43 -0800618 : gpr_strdup(chand->info_lb_policy_name);
Mark D. Rothb2d24882016-10-27 15:44:07 -0700619 }
Craig Tiller4782d922017-11-10 09:53:21 -0800620 if (info->service_config_json != nullptr) {
Craig Tiller613dafa2017-02-09 12:00:43 -0800621 *info->service_config_json =
Craig Tiller4782d922017-11-10 09:53:21 -0800622 chand->info_service_config_json == nullptr
623 ? nullptr
Craig Tiller613dafa2017-02-09 12:00:43 -0800624 : gpr_strdup(chand->info_service_config_json);
Mark D. Rothc625c7a2016-11-09 14:12:37 -0800625 }
Craig Tiller613dafa2017-02-09 12:00:43 -0800626 gpr_mu_unlock(&chand->info_mu);
Mark D. Rothb2d24882016-10-27 15:44:07 -0700627}
628
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700629/* Constructor for channel_data */
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800630static grpc_error* cc_init_channel_elem(grpc_channel_element* elem,
Craig Tillerbaa14a92017-11-03 09:09:36 -0700631 grpc_channel_element_args* args) {
Noah Eisenbe82e642018-02-09 09:16:55 -0800632 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700633 GPR_ASSERT(args->is_last);
634 GPR_ASSERT(elem->filter == &grpc_client_channel_filter);
Mark D. Roth21d4b2d2016-11-18 09:53:41 -0800635 // Initialize data members.
Craig Tilleree4b1452017-05-12 10:56:03 -0700636 chand->combiner = grpc_combiner_create();
Craig Tillerd85477512017-02-09 12:02:39 -0800637 gpr_mu_init(&chand->info_mu);
Alexander Polcync3b1f182017-04-18 13:51:36 -0700638 gpr_mu_init(&chand->external_connectivity_watcher_list_mu);
639
640 gpr_mu_lock(&chand->external_connectivity_watcher_list_mu);
Craig Tiller4782d922017-11-10 09:53:21 -0800641 chand->external_connectivity_watcher_list_head = nullptr;
Alexander Polcync3b1f182017-04-18 13:51:36 -0700642 gpr_mu_unlock(&chand->external_connectivity_watcher_list_mu);
643
Mark D. Roth21d4b2d2016-11-18 09:53:41 -0800644 chand->owning_stack = args->channel_stack;
ncteisen274bbbe2017-06-08 14:57:11 -0700645 GRPC_CLOSURE_INIT(&chand->on_resolver_result_changed,
Craig Tillerbefafe62017-02-09 11:30:54 -0800646 on_resolver_result_changed_locked, chand,
Craig Tilleree4b1452017-05-12 10:56:03 -0700647 grpc_combiner_scheduler(chand->combiner));
Mark D. Roth21d4b2d2016-11-18 09:53:41 -0800648 chand->interested_parties = grpc_pollset_set_create();
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700649 grpc_connectivity_state_init(&chand->state_tracker, GRPC_CHANNEL_IDLE,
650 "client_channel");
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800651 grpc_client_channel_start_backup_polling(chand->interested_parties);
Mark D. Roth718c8342018-02-28 13:00:04 -0800652 // Record max per-RPC retry buffer size.
653 const grpc_arg* arg = grpc_channel_args_find(
654 args->channel_args, GRPC_ARG_PER_RPC_RETRY_BUFFER_SIZE);
655 chand->per_rpc_retry_buffer_size = (size_t)grpc_channel_arg_get_integer(
656 arg, {DEFAULT_PER_RPC_RETRY_BUFFER_SIZE, 0, INT_MAX});
657 // Record enable_retries.
658 arg = grpc_channel_args_find(args->channel_args, GRPC_ARG_ENABLE_RETRIES);
659 chand->enable_retries = grpc_channel_arg_get_bool(arg, true);
Mark D. Roth21d4b2d2016-11-18 09:53:41 -0800660 // Record client channel factory.
Mark D. Roth718c8342018-02-28 13:00:04 -0800661 arg = grpc_channel_args_find(args->channel_args,
662 GRPC_ARG_CLIENT_CHANNEL_FACTORY);
Craig Tiller4782d922017-11-10 09:53:21 -0800663 if (arg == nullptr) {
David Garcia Quintas228a5142017-03-30 19:43:00 -0700664 return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
665 "Missing client channel factory in args for client channel filter");
666 }
667 if (arg->type != GRPC_ARG_POINTER) {
668 return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
669 "client channel factory arg must be a pointer");
670 }
Yash Tibrewalbc130da2017-09-12 22:44:08 -0700671 grpc_client_channel_factory_ref(
Noah Eisenbe82e642018-02-09 09:16:55 -0800672 static_cast<grpc_client_channel_factory*>(arg->value.pointer.p));
Yash Tibrewalca3c1c02017-09-07 22:47:16 -0700673 chand->client_channel_factory =
Noah Eisenbe82e642018-02-09 09:16:55 -0800674 static_cast<grpc_client_channel_factory*>(arg->value.pointer.p);
Mark D. Rothdc9bee72017-02-07 12:29:14 -0800675 // Get server name to resolve, using proxy mapper if needed.
Mark D. Roth86e90592016-11-18 09:56:40 -0800676 arg = grpc_channel_args_find(args->channel_args, GRPC_ARG_SERVER_URI);
Craig Tiller4782d922017-11-10 09:53:21 -0800677 if (arg == nullptr) {
David Garcia Quintas228a5142017-03-30 19:43:00 -0700678 return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
679 "Missing server uri in args for client channel filter");
680 }
681 if (arg->type != GRPC_ARG_STRING) {
682 return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
683 "server uri arg must be a string");
684 }
Craig Tiller4782d922017-11-10 09:53:21 -0800685 char* proxy_name = nullptr;
686 grpc_channel_args* new_args = nullptr;
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800687 grpc_proxy_mappers_map_name(arg->value.string, args->channel_args,
Mark D. Rothdc9bee72017-02-07 12:29:14 -0800688 &proxy_name, &new_args);
689 // Instantiate resolver.
Mark D. Roth209f6442018-02-08 10:26:46 -0800690 chand->resolver = grpc_core::ResolverRegistry::CreateResolver(
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800691 proxy_name != nullptr ? proxy_name : arg->value.string,
Craig Tiller4782d922017-11-10 09:53:21 -0800692 new_args != nullptr ? new_args : args->channel_args,
Craig Tiller972470b2017-02-09 15:05:36 -0800693 chand->interested_parties, chand->combiner);
Craig Tiller4782d922017-11-10 09:53:21 -0800694 if (proxy_name != nullptr) gpr_free(proxy_name);
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800695 if (new_args != nullptr) grpc_channel_args_destroy(new_args);
Craig Tiller4782d922017-11-10 09:53:21 -0800696 if (chand->resolver == nullptr) {
ncteisen4b36a3d2017-03-13 19:08:06 -0700697 return GRPC_ERROR_CREATE_FROM_STATIC_STRING("resolver creation failed");
Mark D. Roth5e2566e2016-11-18 10:53:13 -0800698 }
Craig Tiller3be7dd02017-04-03 14:30:03 -0700699 chand->deadline_checking_enabled =
700 grpc_deadline_checking_enabled(args->channel_args);
Mark D. Roth5e2566e2016-11-18 10:53:13 -0800701 return GRPC_ERROR_NONE;
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700702}
703
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800704static void shutdown_resolver_locked(void* arg, grpc_error* error) {
Mark D. Roth209f6442018-02-08 10:26:46 -0800705 grpc_core::Resolver* resolver = static_cast<grpc_core::Resolver*>(arg);
706 resolver->Orphan();
Craig Tiller972470b2017-02-09 15:05:36 -0800707}
708
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700709/* Destructor for channel_data */
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800710static void cc_destroy_channel_elem(grpc_channel_element* elem) {
Noah Eisenbe82e642018-02-09 09:16:55 -0800711 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Craig Tiller4782d922017-11-10 09:53:21 -0800712 if (chand->resolver != nullptr) {
ncteisen274bbbe2017-06-08 14:57:11 -0700713 GRPC_CLOSURE_SCHED(
Mark D. Roth209f6442018-02-08 10:26:46 -0800714 GRPC_CLOSURE_CREATE(shutdown_resolver_locked, chand->resolver.release(),
Yash Tibrewal0ee75742017-10-13 16:07:13 -0700715 grpc_combiner_scheduler(chand->combiner)),
Craig Tiller972470b2017-02-09 15:05:36 -0800716 GRPC_ERROR_NONE);
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700717 }
Craig Tiller4782d922017-11-10 09:53:21 -0800718 if (chand->client_channel_factory != nullptr) {
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800719 grpc_client_channel_factory_unref(chand->client_channel_factory);
Mark D. Roth0e48a9a2016-09-08 14:14:39 -0700720 }
Craig Tiller4782d922017-11-10 09:53:21 -0800721 if (chand->lb_policy != nullptr) {
Mark D. Rothc8875492018-02-20 08:33:48 -0800722 grpc_pollset_set_del_pollset_set(chand->lb_policy->interested_parties(),
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700723 chand->interested_parties);
Mark D. Rothc8875492018-02-20 08:33:48 -0800724 chand->lb_policy.reset();
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700725 }
Craig Tiller613dafa2017-02-09 12:00:43 -0800726 gpr_free(chand->info_lb_policy_name);
727 gpr_free(chand->info_service_config_json);
Craig Tiller4782d922017-11-10 09:53:21 -0800728 if (chand->retry_throttle_data != nullptr) {
Mark D. Rothd6d192d2017-02-23 08:58:42 -0800729 grpc_server_retry_throttle_data_unref(chand->retry_throttle_data);
730 }
Craig Tiller4782d922017-11-10 09:53:21 -0800731 if (chand->method_params_table != nullptr) {
Mark D. Roth3e7f2df2018-02-26 13:17:06 -0800732 chand->method_params_table.reset();
Mark D. Roth9fe284e2016-09-12 11:22:27 -0700733 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800734 grpc_client_channel_stop_backup_polling(chand->interested_parties);
735 grpc_connectivity_state_destroy(&chand->state_tracker);
736 grpc_pollset_set_destroy(chand->interested_parties);
737 GRPC_COMBINER_UNREF(chand->combiner, "client_channel");
Craig Tillerd85477512017-02-09 12:02:39 -0800738 gpr_mu_destroy(&chand->info_mu);
Alexander Polcync3b1f182017-04-18 13:51:36 -0700739 gpr_mu_destroy(&chand->external_connectivity_watcher_list_mu);
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700740}
741
742/*************************************************************************
743 * PER-CALL FUNCTIONS
744 */
745
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700746// Max number of batches that can be pending on a call at any given
Mark D. Roth718c8342018-02-28 13:00:04 -0800747// time. This includes one batch for each of the following ops:
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700748// recv_initial_metadata
749// send_initial_metadata
750// recv_message
751// send_message
752// recv_trailing_metadata
753// send_trailing_metadata
Mark D. Roth718c8342018-02-28 13:00:04 -0800754#define MAX_PENDING_BATCHES 6
755
756// Retry support:
757//
758// In order to support retries, we act as a proxy for stream op batches.
759// When we get a batch from the surface, we add it to our list of pending
760// batches, and we then use those batches to construct separate "child"
761// batches to be started on the subchannel call. When the child batches
762// return, we then decide which pending batches have been completed and
763// schedule their callbacks accordingly. If a subchannel call fails and
764// we want to retry it, we do a new pick and start again, constructing
765// new "child" batches for the new subchannel call.
766//
767// Note that retries are committed when receiving data from the server
768// (except for Trailers-Only responses). However, there may be many
769// send ops started before receiving any data, so we may have already
770// completed some number of send ops (and returned the completions up to
771// the surface) by the time we realize that we need to retry. To deal
772// with this, we cache data for send ops, so that we can replay them on a
773// different subchannel call even after we have completed the original
774// batches.
775//
776// There are two sets of data to maintain:
777// - In call_data (in the parent channel), we maintain a list of pending
778// ops and cached data for send ops.
779// - In the subchannel call, we maintain state to indicate what ops have
780// already been sent down to that call.
781//
782// When constructing the "child" batches, we compare those two sets of
783// data to see which batches need to be sent to the subchannel call.
784
785// TODO(roth): In subsequent PRs:
786// - add support for transparent retries (including initial metadata)
787// - figure out how to record stats in census for retries
788// (census filter is on top of this one)
789// - add census stats for retries
790
791// State used for starting a retryable batch on a subchannel call.
792// This provides its own grpc_transport_stream_op_batch and other data
793// structures needed to populate the ops in the batch.
794// We allocate one struct on the arena for each attempt at starting a
795// batch on a given subchannel call.
796typedef struct {
797 gpr_refcount refs;
798 grpc_call_element* elem;
799 grpc_subchannel_call* subchannel_call; // Holds a ref.
800 // The batch to use in the subchannel call.
801 // Its payload field points to subchannel_call_retry_state.batch_payload.
802 grpc_transport_stream_op_batch batch;
803 // For send_initial_metadata.
804 // Note that we need to make a copy of the initial metadata for each
805 // subchannel call instead of just referring to the copy in call_data,
806 // because filters in the subchannel stack will probably add entries,
807 // so we need to start in a pristine state for each attempt of the call.
808 grpc_linked_mdelem* send_initial_metadata_storage;
809 grpc_metadata_batch send_initial_metadata;
810 // For send_message.
Mark D. Roth3d8b32d2018-03-09 13:25:40 -0800811 grpc_core::ManualConstructor<grpc_core::ByteStreamCache::CachingByteStream>
812 send_message;
Mark D. Roth718c8342018-02-28 13:00:04 -0800813 // For send_trailing_metadata.
814 grpc_linked_mdelem* send_trailing_metadata_storage;
815 grpc_metadata_batch send_trailing_metadata;
816 // For intercepting recv_initial_metadata.
817 grpc_metadata_batch recv_initial_metadata;
818 grpc_closure recv_initial_metadata_ready;
819 bool trailing_metadata_available;
820 // For intercepting recv_message.
821 grpc_closure recv_message_ready;
Mark D. Roth3d8b32d2018-03-09 13:25:40 -0800822 grpc_core::OrphanablePtr<grpc_core::ByteStream> recv_message;
Mark D. Roth718c8342018-02-28 13:00:04 -0800823 // For intercepting recv_trailing_metadata.
824 grpc_metadata_batch recv_trailing_metadata;
825 grpc_transport_stream_stats collect_stats;
826 // For intercepting on_complete.
827 grpc_closure on_complete;
828} subchannel_batch_data;
829
830// Retry state associated with a subchannel call.
831// Stored in the parent_data of the subchannel call object.
832typedef struct {
833 // subchannel_batch_data.batch.payload points to this.
834 grpc_transport_stream_op_batch_payload batch_payload;
835 // These fields indicate which ops have been started and completed on
836 // this subchannel call.
837 size_t started_send_message_count;
838 size_t completed_send_message_count;
839 size_t started_recv_message_count;
840 size_t completed_recv_message_count;
841 bool started_send_initial_metadata : 1;
842 bool completed_send_initial_metadata : 1;
843 bool started_send_trailing_metadata : 1;
844 bool completed_send_trailing_metadata : 1;
845 bool started_recv_initial_metadata : 1;
846 bool completed_recv_initial_metadata : 1;
847 bool started_recv_trailing_metadata : 1;
848 bool completed_recv_trailing_metadata : 1;
849 // State for callback processing.
850 bool retry_dispatched : 1;
851 bool recv_initial_metadata_ready_deferred : 1;
852 bool recv_message_ready_deferred : 1;
853 grpc_error* recv_initial_metadata_error;
854 grpc_error* recv_message_error;
855} subchannel_call_retry_state;
856
857// Pending batches stored in call data.
858typedef struct {
859 // The pending batch. If nullptr, this slot is empty.
860 grpc_transport_stream_op_batch* batch;
861 // Indicates whether payload for send ops has been cached in call data.
862 bool send_ops_cached;
863} pending_batch;
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700864
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700865/** Call data. Holds a pointer to grpc_subchannel_call and the
866 associated machinery to create such a pointer.
867 Handles queueing of stream ops until a call object is ready, waiting
868 for initial metadata before trying to create a call object,
869 and handling cancellation gracefully. */
870typedef struct client_channel_call_data {
Mark D. Roth72f6da82016-09-02 13:42:38 -0700871 // State for handling deadlines.
872 // The code in deadline_filter.c requires this to be the first field.
Mark D. Roth72f6da82016-09-02 13:42:38 -0700873 // TODO(roth): This is slightly sub-optimal in that grpc_deadline_state
Mark D. Roth66f3d2b2017-09-01 09:02:17 -0700874 // and this struct both independently store pointers to the call stack
875 // and call combiner. If/when we have time, find a way to avoid this
876 // without breaking the grpc_deadline_state abstraction.
Mark D. Roth72f6da82016-09-02 13:42:38 -0700877 grpc_deadline_state deadline_state;
Mark D. Rothf28763c2016-09-14 15:18:40 -0700878
Craig Tiller7c70b6c2017-01-23 07:48:42 -0800879 grpc_slice path; // Request path.
Mark D. Rothe40dd292016-10-05 14:58:37 -0700880 gpr_timespec call_start_time;
Craig Tiller89c14282017-07-19 15:32:27 -0700881 grpc_millis deadline;
Craig Tillerbaa14a92017-11-03 09:09:36 -0700882 gpr_arena* arena;
883 grpc_call_stack* owning_call;
884 grpc_call_combiner* call_combiner;
Mark D. Roth76e264b2017-08-25 09:03:33 -0700885
Craig Tillerbaa14a92017-11-03 09:09:36 -0700886 grpc_server_retry_throttle_data* retry_throttle_data;
Mark D. Roth3e7f2df2018-02-26 13:17:06 -0800887 grpc_core::RefCountedPtr<ClientChannelMethodParams> method_params;
Mark D. Rothaa850a72016-09-26 13:38:02 -0700888
Craig Tillerbaa14a92017-11-03 09:09:36 -0700889 grpc_subchannel_call* subchannel_call;
Mark D. Roth718c8342018-02-28 13:00:04 -0800890
891 // Set when we get a cancel_stream op.
892 grpc_error* cancel_error;
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700893
Mark D. Rothc8875492018-02-20 08:33:48 -0800894 grpc_core::LoadBalancingPolicy::PickState pick;
Mark D. Roth718c8342018-02-28 13:00:04 -0800895 grpc_closure pick_closure;
896 grpc_closure pick_cancel_closure;
Mark D. Roth60751fe2017-07-07 12:50:33 -0700897
Craig Tillerbaa14a92017-11-03 09:09:36 -0700898 grpc_polling_entity* pollent;
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700899
Mark D. Roth718c8342018-02-28 13:00:04 -0800900 // Batches are added to this list when received from above.
901 // They are removed when we are done handling the batch (i.e., when
902 // either we have invoked all of the batch's callbacks or we have
903 // passed the batch down to the subchannel call and are not
904 // intercepting any of its callbacks).
905 pending_batch pending_batches[MAX_PENDING_BATCHES];
906 bool pending_send_initial_metadata : 1;
907 bool pending_send_message : 1;
908 bool pending_send_trailing_metadata : 1;
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700909
Mark D. Roth718c8342018-02-28 13:00:04 -0800910 // Retry state.
911 bool enable_retries : 1;
912 bool retry_committed : 1;
913 bool last_attempt_got_server_pushback : 1;
914 int num_attempts_completed;
915 size_t bytes_buffered_for_retry;
916 grpc_core::ManualConstructor<grpc_core::BackOff> retry_backoff;
917 grpc_timer retry_timer;
David Garcia Quintasd1a47f12016-09-02 12:46:44 +0200918
Mark D. Roth718c8342018-02-28 13:00:04 -0800919 // Cached data for retrying send ops.
920 // send_initial_metadata
921 bool seen_send_initial_metadata;
922 grpc_linked_mdelem* send_initial_metadata_storage;
923 grpc_metadata_batch send_initial_metadata;
924 uint32_t send_initial_metadata_flags;
925 gpr_atm* peer_string;
926 // send_message
927 // When we get a send_message op, we replace the original byte stream
Mark D. Roth3d8b32d2018-03-09 13:25:40 -0800928 // with a CachingByteStream that caches the slices to a local buffer for
929 // use in retries.
Mark D. Roth718c8342018-02-28 13:00:04 -0800930 // Note: We inline the cache for the first 3 send_message ops and use
931 // dynamic allocation after that. This number was essentially picked
932 // at random; it could be changed in the future to tune performance.
Mark D. Roth3d8b32d2018-03-09 13:25:40 -0800933 grpc_core::InlinedVector<grpc_core::ByteStreamCache*, 3> send_messages;
Mark D. Roth718c8342018-02-28 13:00:04 -0800934 // send_trailing_metadata
935 bool seen_send_trailing_metadata;
936 grpc_linked_mdelem* send_trailing_metadata_storage;
937 grpc_metadata_batch send_trailing_metadata;
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700938} call_data;
939
Mark D. Roth718c8342018-02-28 13:00:04 -0800940// Forward declarations.
941static void retry_commit(grpc_call_element* elem,
942 subchannel_call_retry_state* retry_state);
943static void start_internal_recv_trailing_metadata(grpc_call_element* elem);
944static void on_complete(void* arg, grpc_error* error);
945static void start_retriable_subchannel_batches(void* arg, grpc_error* ignored);
946static void pick_after_resolver_result_start_locked(grpc_call_element* elem);
947static void start_pick_locked(void* arg, grpc_error* ignored);
Craig Tiller8b1d59c2016-12-27 15:15:30 -0800948
Mark D. Roth718c8342018-02-28 13:00:04 -0800949//
950// send op data caching
951//
952
953// Caches data for send ops so that it can be retried later, if not
954// already cached.
955static void maybe_cache_send_ops_for_batch(call_data* calld,
956 pending_batch* pending) {
957 if (pending->send_ops_cached) return;
958 pending->send_ops_cached = true;
959 grpc_transport_stream_op_batch* batch = pending->batch;
960 // Save a copy of metadata for send_initial_metadata ops.
Mark D. Roth76e264b2017-08-25 09:03:33 -0700961 if (batch->send_initial_metadata) {
Mark D. Roth718c8342018-02-28 13:00:04 -0800962 calld->seen_send_initial_metadata = true;
963 GPR_ASSERT(calld->send_initial_metadata_storage == nullptr);
964 grpc_metadata_batch* send_initial_metadata =
965 batch->payload->send_initial_metadata.send_initial_metadata;
966 calld->send_initial_metadata_storage = (grpc_linked_mdelem*)gpr_arena_alloc(
967 calld->arena,
968 sizeof(grpc_linked_mdelem) * send_initial_metadata->list.count);
969 grpc_metadata_batch_copy(send_initial_metadata,
970 &calld->send_initial_metadata,
971 calld->send_initial_metadata_storage);
972 calld->send_initial_metadata_flags =
973 batch->payload->send_initial_metadata.send_initial_metadata_flags;
974 calld->peer_string = batch->payload->send_initial_metadata.peer_string;
975 }
976 // Set up cache for send_message ops.
977 if (batch->send_message) {
Mark D. Roth3d8b32d2018-03-09 13:25:40 -0800978 grpc_core::ByteStreamCache* cache =
979 static_cast<grpc_core::ByteStreamCache*>(
980 gpr_arena_alloc(calld->arena, sizeof(grpc_core::ByteStreamCache)));
981 new (cache) grpc_core::ByteStreamCache(
982 std::move(batch->payload->send_message.send_message));
Mark D. Roth718c8342018-02-28 13:00:04 -0800983 calld->send_messages.push_back(cache);
984 }
985 // Save metadata batch for send_trailing_metadata ops.
986 if (batch->send_trailing_metadata) {
987 calld->seen_send_trailing_metadata = true;
988 GPR_ASSERT(calld->send_trailing_metadata_storage == nullptr);
989 grpc_metadata_batch* send_trailing_metadata =
990 batch->payload->send_trailing_metadata.send_trailing_metadata;
991 calld->send_trailing_metadata_storage =
992 (grpc_linked_mdelem*)gpr_arena_alloc(
993 calld->arena,
994 sizeof(grpc_linked_mdelem) * send_trailing_metadata->list.count);
995 grpc_metadata_batch_copy(send_trailing_metadata,
996 &calld->send_trailing_metadata,
997 calld->send_trailing_metadata_storage);
Mark D. Roth76e264b2017-08-25 09:03:33 -0700998 }
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700999}
1000
Mark D. Roth718c8342018-02-28 13:00:04 -08001001// Frees cached send ops that have already been completed after
1002// committing the call.
1003static void free_cached_send_op_data_after_commit(
1004 grpc_call_element* elem, subchannel_call_retry_state* retry_state) {
Noah Eisenbe82e642018-02-09 09:16:55 -08001005 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1006 call_data* calld = static_cast<call_data*>(elem->call_data);
Mark D. Roth718c8342018-02-28 13:00:04 -08001007 if (retry_state->completed_send_initial_metadata) {
1008 grpc_metadata_batch_destroy(&calld->send_initial_metadata);
Mark D. Roth60751fe2017-07-07 12:50:33 -07001009 }
Mark D. Roth718c8342018-02-28 13:00:04 -08001010 for (size_t i = 0; i < retry_state->completed_send_message_count; ++i) {
1011 if (grpc_client_channel_trace.enabled()) {
1012 gpr_log(GPR_DEBUG,
1013 "chand=%p calld=%p: destroying calld->send_messages[%" PRIuPTR
1014 "]",
1015 chand, calld, i);
1016 }
Mark D. Roth3d8b32d2018-03-09 13:25:40 -08001017 calld->send_messages[i]->Destroy();
Mark D. Roth2a5959f2016-09-01 08:20:27 -07001018 }
Mark D. Roth718c8342018-02-28 13:00:04 -08001019 if (retry_state->completed_send_trailing_metadata) {
1020 grpc_metadata_batch_destroy(&calld->send_trailing_metadata);
1021 }
Mark D. Roth2a5959f2016-09-01 08:20:27 -07001022}
1023
Mark D. Roth718c8342018-02-28 13:00:04 -08001024// Frees cached send ops that were completed by the completed batch in
1025// batch_data. Used when batches are completed after the call is committed.
1026static void free_cached_send_op_data_for_completed_batch(
1027 grpc_call_element* elem, subchannel_batch_data* batch_data,
1028 subchannel_call_retry_state* retry_state) {
Noah Eisenbe82e642018-02-09 09:16:55 -08001029 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1030 call_data* calld = static_cast<call_data*>(elem->call_data);
Mark D. Roth718c8342018-02-28 13:00:04 -08001031 if (batch_data->batch.send_initial_metadata) {
1032 grpc_metadata_batch_destroy(&calld->send_initial_metadata);
1033 }
1034 if (batch_data->batch.send_message) {
1035 if (grpc_client_channel_trace.enabled()) {
1036 gpr_log(GPR_DEBUG,
1037 "chand=%p calld=%p: destroying calld->send_messages[%" PRIuPTR
1038 "]",
1039 chand, calld, retry_state->completed_send_message_count - 1);
1040 }
Mark D. Roth3d8b32d2018-03-09 13:25:40 -08001041 calld->send_messages[retry_state->completed_send_message_count - 1]
1042 ->Destroy();
Mark D. Roth718c8342018-02-28 13:00:04 -08001043 }
1044 if (batch_data->batch.send_trailing_metadata) {
1045 grpc_metadata_batch_destroy(&calld->send_trailing_metadata);
1046 }
1047}
1048
1049//
1050// pending_batches management
1051//
1052
1053// Returns the index into calld->pending_batches to be used for batch.
1054static size_t get_batch_index(grpc_transport_stream_op_batch* batch) {
1055 // Note: It is important the send_initial_metadata be the first entry
1056 // here, since the code in pick_subchannel_locked() assumes it will be.
1057 if (batch->send_initial_metadata) return 0;
1058 if (batch->send_message) return 1;
1059 if (batch->send_trailing_metadata) return 2;
1060 if (batch->recv_initial_metadata) return 3;
1061 if (batch->recv_message) return 4;
1062 if (batch->recv_trailing_metadata) return 5;
1063 GPR_UNREACHABLE_CODE(return (size_t)-1);
1064}
1065
1066// This is called via the call combiner, so access to calld is synchronized.
1067static void pending_batches_add(grpc_call_element* elem,
1068 grpc_transport_stream_op_batch* batch) {
1069 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1070 call_data* calld = static_cast<call_data*>(elem->call_data);
1071 const size_t idx = get_batch_index(batch);
Craig Tiller6014e8a2017-10-16 13:50:29 -07001072 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth718c8342018-02-28 13:00:04 -08001073 gpr_log(GPR_DEBUG,
1074 "chand=%p calld=%p: adding pending batch at index %" PRIuPTR, chand,
1075 calld, idx);
Mark D. Roth60751fe2017-07-07 12:50:33 -07001076 }
Mark D. Roth718c8342018-02-28 13:00:04 -08001077 pending_batch* pending = &calld->pending_batches[idx];
1078 GPR_ASSERT(pending->batch == nullptr);
1079 pending->batch = batch;
1080 pending->send_ops_cached = false;
1081 if (calld->enable_retries) {
1082 // Update state in calld about pending batches.
1083 // Also check if the batch takes us over the retry buffer limit.
1084 // Note: We don't check the size of trailing metadata here, because
1085 // gRPC clients do not send trailing metadata.
1086 if (batch->send_initial_metadata) {
1087 calld->pending_send_initial_metadata = true;
1088 calld->bytes_buffered_for_retry += grpc_metadata_batch_size(
1089 batch->payload->send_initial_metadata.send_initial_metadata);
1090 }
1091 if (batch->send_message) {
1092 calld->pending_send_message = true;
1093 calld->bytes_buffered_for_retry +=
Mark D. Roth3d8b32d2018-03-09 13:25:40 -08001094 batch->payload->send_message.send_message->length();
Mark D. Roth718c8342018-02-28 13:00:04 -08001095 }
1096 if (batch->send_trailing_metadata) {
1097 calld->pending_send_trailing_metadata = true;
1098 }
1099 if (calld->bytes_buffered_for_retry > chand->per_rpc_retry_buffer_size) {
1100 if (grpc_client_channel_trace.enabled()) {
1101 gpr_log(GPR_DEBUG,
1102 "chand=%p calld=%p: exceeded retry buffer size, committing",
1103 chand, calld);
1104 }
1105 subchannel_call_retry_state* retry_state =
1106 calld->subchannel_call == nullptr
1107 ? nullptr
1108 : static_cast<subchannel_call_retry_state*>(
1109 grpc_connected_subchannel_call_get_parent_data(
1110 calld->subchannel_call));
1111 retry_commit(elem, retry_state);
1112 // If we are not going to retry and have not yet started, pretend
1113 // retries are disabled so that we don't bother with retry overhead.
1114 if (calld->num_attempts_completed == 0) {
1115 if (grpc_client_channel_trace.enabled()) {
1116 gpr_log(GPR_DEBUG,
1117 "chand=%p calld=%p: disabling retries before first attempt",
1118 chand, calld);
Mark D. Roth0ca0be82017-06-20 07:49:33 -07001119 }
Mark D. Roth718c8342018-02-28 13:00:04 -08001120 calld->enable_retries = false;
Craig Tiller11c17d42017-03-13 13:36:34 -07001121 }
1122 }
1123 }
Craig Tiller11c17d42017-03-13 13:36:34 -07001124}
Craig Tillerea4a4f12017-03-13 13:36:52 -07001125
Mark D. Roth718c8342018-02-28 13:00:04 -08001126static void pending_batch_clear(call_data* calld, pending_batch* pending) {
1127 if (calld->enable_retries) {
1128 if (pending->batch->send_initial_metadata) {
1129 calld->pending_send_initial_metadata = false;
1130 }
1131 if (pending->batch->send_message) {
1132 calld->pending_send_message = false;
1133 }
1134 if (pending->batch->send_trailing_metadata) {
1135 calld->pending_send_trailing_metadata = false;
1136 }
1137 }
1138 pending->batch = nullptr;
1139}
1140
1141// This is called via the call combiner, so access to calld is synchronized.
1142static void fail_pending_batch_in_call_combiner(void* arg, grpc_error* error) {
1143 grpc_transport_stream_op_batch* batch =
1144 static_cast<grpc_transport_stream_op_batch*>(arg);
1145 call_data* calld = static_cast<call_data*>(batch->handler_private.extra_arg);
1146 // Note: This will release the call combiner.
1147 grpc_transport_stream_op_batch_finish_with_failure(
1148 batch, GRPC_ERROR_REF(error), calld->call_combiner);
1149}
1150
1151// This is called via the call combiner, so access to calld is synchronized.
1152// If yield_call_combiner is true, assumes responsibility for yielding
1153// the call combiner.
1154static void pending_batches_fail(grpc_call_element* elem, grpc_error* error,
1155 bool yield_call_combiner) {
1156 GPR_ASSERT(error != GRPC_ERROR_NONE);
1157 call_data* calld = static_cast<call_data*>(elem->call_data);
1158 if (grpc_client_channel_trace.enabled()) {
1159 size_t num_batches = 0;
1160 for (size_t i = 0; i < GPR_ARRAY_SIZE(calld->pending_batches); ++i) {
1161 if (calld->pending_batches[i].batch != nullptr) ++num_batches;
1162 }
1163 gpr_log(GPR_DEBUG,
1164 "chand=%p calld=%p: failing %" PRIuPTR " pending batches: %s",
1165 elem->channel_data, calld, num_batches, grpc_error_string(error));
1166 }
1167 grpc_transport_stream_op_batch*
1168 batches[GPR_ARRAY_SIZE(calld->pending_batches)];
1169 size_t num_batches = 0;
1170 for (size_t i = 0; i < GPR_ARRAY_SIZE(calld->pending_batches); ++i) {
1171 pending_batch* pending = &calld->pending_batches[i];
1172 grpc_transport_stream_op_batch* batch = pending->batch;
1173 if (batch != nullptr) {
1174 batches[num_batches++] = batch;
1175 pending_batch_clear(calld, pending);
1176 }
1177 }
1178 for (size_t i = yield_call_combiner ? 1 : 0; i < num_batches; ++i) {
1179 grpc_transport_stream_op_batch* batch = batches[i];
1180 batch->handler_private.extra_arg = calld;
1181 GRPC_CLOSURE_INIT(&batch->handler_private.closure,
1182 fail_pending_batch_in_call_combiner, batch,
1183 grpc_schedule_on_exec_ctx);
1184 GRPC_CALL_COMBINER_START(calld->call_combiner,
1185 &batch->handler_private.closure,
1186 GRPC_ERROR_REF(error), "pending_batches_fail");
1187 }
1188 if (yield_call_combiner) {
1189 if (num_batches > 0) {
1190 // Note: This will release the call combiner.
1191 grpc_transport_stream_op_batch_finish_with_failure(
1192 batches[0], GRPC_ERROR_REF(error), calld->call_combiner);
1193 } else {
1194 GRPC_CALL_COMBINER_STOP(calld->call_combiner, "pending_batches_fail");
1195 }
1196 }
1197 GRPC_ERROR_UNREF(error);
1198}
1199
1200// This is called via the call combiner, so access to calld is synchronized.
1201static void resume_pending_batch_in_call_combiner(void* arg,
1202 grpc_error* ignored) {
1203 grpc_transport_stream_op_batch* batch =
1204 static_cast<grpc_transport_stream_op_batch*>(arg);
1205 grpc_subchannel_call* subchannel_call =
1206 static_cast<grpc_subchannel_call*>(batch->handler_private.extra_arg);
1207 // Note: This will release the call combiner.
1208 grpc_subchannel_call_process_op(subchannel_call, batch);
1209}
1210
1211// This is called via the call combiner, so access to calld is synchronized.
1212static void pending_batches_resume(grpc_call_element* elem) {
Noah Eisenbe82e642018-02-09 09:16:55 -08001213 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1214 call_data* calld = static_cast<call_data*>(elem->call_data);
Mark D. Roth718c8342018-02-28 13:00:04 -08001215 if (calld->enable_retries) {
1216 start_retriable_subchannel_batches(elem, GRPC_ERROR_NONE);
1217 return;
1218 }
1219 // Retries not enabled; send down batches as-is.
1220 if (grpc_client_channel_trace.enabled()) {
1221 size_t num_batches = 0;
1222 for (size_t i = 0; i < GPR_ARRAY_SIZE(calld->pending_batches); ++i) {
1223 if (calld->pending_batches[i].batch != nullptr) ++num_batches;
1224 }
1225 gpr_log(GPR_DEBUG,
1226 "chand=%p calld=%p: starting %" PRIuPTR
1227 " pending batches on subchannel_call=%p",
1228 chand, calld, num_batches, calld->subchannel_call);
1229 }
1230 grpc_transport_stream_op_batch*
1231 batches[GPR_ARRAY_SIZE(calld->pending_batches)];
1232 size_t num_batches = 0;
1233 for (size_t i = 0; i < GPR_ARRAY_SIZE(calld->pending_batches); ++i) {
1234 pending_batch* pending = &calld->pending_batches[i];
1235 grpc_transport_stream_op_batch* batch = pending->batch;
1236 if (batch != nullptr) {
1237 batches[num_batches++] = batch;
1238 pending_batch_clear(calld, pending);
1239 }
1240 }
1241 for (size_t i = 1; i < num_batches; ++i) {
1242 grpc_transport_stream_op_batch* batch = batches[i];
1243 batch->handler_private.extra_arg = calld->subchannel_call;
1244 GRPC_CLOSURE_INIT(&batch->handler_private.closure,
1245 resume_pending_batch_in_call_combiner, batch,
1246 grpc_schedule_on_exec_ctx);
1247 GRPC_CALL_COMBINER_START(calld->call_combiner,
1248 &batch->handler_private.closure, GRPC_ERROR_NONE,
1249 "pending_batches_resume");
1250 }
1251 GPR_ASSERT(num_batches > 0);
1252 // Note: This will release the call combiner.
1253 grpc_subchannel_call_process_op(calld->subchannel_call, batches[0]);
1254}
1255
1256static void maybe_clear_pending_batch(grpc_call_element* elem,
1257 pending_batch* pending) {
1258 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1259 call_data* calld = static_cast<call_data*>(elem->call_data);
1260 grpc_transport_stream_op_batch* batch = pending->batch;
1261 // We clear the pending batch if all of its callbacks have been
1262 // scheduled and reset to nullptr.
1263 if (batch->on_complete == nullptr &&
1264 (!batch->recv_initial_metadata ||
1265 batch->payload->recv_initial_metadata.recv_initial_metadata_ready ==
1266 nullptr) &&
1267 (!batch->recv_message ||
1268 batch->payload->recv_message.recv_message_ready == nullptr)) {
1269 if (grpc_client_channel_trace.enabled()) {
1270 gpr_log(GPR_DEBUG, "chand=%p calld=%p: clearing pending batch", chand,
1271 calld);
1272 }
1273 pending_batch_clear(calld, pending);
1274 }
1275}
1276
1277// Returns true if all ops in the pending batch have been completed.
1278static bool pending_batch_is_completed(
1279 pending_batch* pending, call_data* calld,
1280 subchannel_call_retry_state* retry_state) {
1281 if (pending->batch == nullptr || pending->batch->on_complete == nullptr) {
1282 return false;
1283 }
1284 if (pending->batch->send_initial_metadata &&
1285 !retry_state->completed_send_initial_metadata) {
1286 return false;
1287 }
1288 if (pending->batch->send_message &&
1289 retry_state->completed_send_message_count < calld->send_messages.size()) {
1290 return false;
1291 }
1292 if (pending->batch->send_trailing_metadata &&
1293 !retry_state->completed_send_trailing_metadata) {
1294 return false;
1295 }
1296 if (pending->batch->recv_initial_metadata &&
1297 !retry_state->completed_recv_initial_metadata) {
1298 return false;
1299 }
1300 if (pending->batch->recv_message &&
1301 retry_state->completed_recv_message_count <
1302 retry_state->started_recv_message_count) {
1303 return false;
1304 }
1305 if (pending->batch->recv_trailing_metadata &&
1306 !retry_state->completed_recv_trailing_metadata) {
1307 return false;
1308 }
1309 return true;
1310}
1311
1312// Returns true if any op in the batch was not yet started.
1313static bool pending_batch_is_unstarted(
1314 pending_batch* pending, call_data* calld,
1315 subchannel_call_retry_state* retry_state) {
1316 if (pending->batch == nullptr || pending->batch->on_complete == nullptr) {
1317 return false;
1318 }
1319 if (pending->batch->send_initial_metadata &&
1320 !retry_state->started_send_initial_metadata) {
1321 return true;
1322 }
1323 if (pending->batch->send_message &&
1324 retry_state->started_send_message_count < calld->send_messages.size()) {
1325 return true;
1326 }
1327 if (pending->batch->send_trailing_metadata &&
1328 !retry_state->started_send_trailing_metadata) {
1329 return true;
1330 }
1331 if (pending->batch->recv_initial_metadata &&
1332 !retry_state->started_recv_initial_metadata) {
1333 return true;
1334 }
1335 if (pending->batch->recv_message &&
1336 retry_state->completed_recv_message_count ==
1337 retry_state->started_recv_message_count) {
1338 return true;
1339 }
1340 if (pending->batch->recv_trailing_metadata &&
1341 !retry_state->started_recv_trailing_metadata) {
1342 return true;
1343 }
1344 return false;
1345}
1346
1347//
1348// retry code
1349//
1350
1351// Commits the call so that no further retry attempts will be performed.
1352static void retry_commit(grpc_call_element* elem,
1353 subchannel_call_retry_state* retry_state) {
1354 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1355 call_data* calld = static_cast<call_data*>(elem->call_data);
1356 if (calld->retry_committed) return;
1357 calld->retry_committed = true;
1358 if (grpc_client_channel_trace.enabled()) {
1359 gpr_log(GPR_DEBUG, "chand=%p calld=%p: committing retries", chand, calld);
1360 }
1361 if (retry_state != nullptr) {
1362 free_cached_send_op_data_after_commit(elem, retry_state);
1363 }
1364}
1365
1366// Starts a retry after appropriate back-off.
1367static void do_retry(grpc_call_element* elem,
1368 subchannel_call_retry_state* retry_state,
1369 grpc_millis server_pushback_ms) {
1370 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1371 call_data* calld = static_cast<call_data*>(elem->call_data);
1372 GPR_ASSERT(calld->method_params != nullptr);
1373 const ClientChannelMethodParams::RetryPolicy* retry_policy =
1374 calld->method_params->retry_policy();
1375 GPR_ASSERT(retry_policy != nullptr);
1376 // Reset subchannel call and connected subchannel.
1377 if (calld->subchannel_call != nullptr) {
1378 GRPC_SUBCHANNEL_CALL_UNREF(calld->subchannel_call,
1379 "client_channel_call_retry");
1380 calld->subchannel_call = nullptr;
1381 }
1382 if (calld->pick.connected_subchannel != nullptr) {
1383 calld->pick.connected_subchannel.reset();
1384 }
1385 // Compute backoff delay.
1386 grpc_millis next_attempt_time;
1387 if (server_pushback_ms >= 0) {
1388 next_attempt_time = grpc_core::ExecCtx::Get()->Now() + server_pushback_ms;
1389 calld->last_attempt_got_server_pushback = true;
1390 } else {
1391 if (calld->num_attempts_completed == 1 ||
1392 calld->last_attempt_got_server_pushback) {
1393 calld->retry_backoff.Init(
1394 grpc_core::BackOff::Options()
1395 .set_initial_backoff(retry_policy->initial_backoff)
1396 .set_multiplier(retry_policy->backoff_multiplier)
1397 .set_jitter(RETRY_BACKOFF_JITTER)
1398 .set_max_backoff(retry_policy->max_backoff));
1399 calld->last_attempt_got_server_pushback = false;
1400 }
1401 next_attempt_time = calld->retry_backoff->NextAttemptTime();
1402 }
1403 if (grpc_client_channel_trace.enabled()) {
1404 gpr_log(GPR_DEBUG,
1405 "chand=%p calld=%p: retrying failed call in %" PRIuPTR " ms", chand,
1406 calld, next_attempt_time - grpc_core::ExecCtx::Get()->Now());
1407 }
1408 // Schedule retry after computed delay.
1409 GRPC_CLOSURE_INIT(&calld->pick_closure, start_pick_locked, elem,
1410 grpc_combiner_scheduler(chand->combiner));
1411 grpc_timer_init(&calld->retry_timer, next_attempt_time, &calld->pick_closure);
1412 // Update bookkeeping.
1413 if (retry_state != nullptr) retry_state->retry_dispatched = true;
1414}
1415
1416// Returns true if the call is being retried.
1417static bool maybe_retry(grpc_call_element* elem,
1418 subchannel_batch_data* batch_data,
1419 grpc_status_code status,
1420 grpc_mdelem* server_pushback_md) {
1421 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1422 call_data* calld = static_cast<call_data*>(elem->call_data);
1423 // Get retry policy.
1424 if (calld->method_params == nullptr) return false;
1425 const ClientChannelMethodParams::RetryPolicy* retry_policy =
1426 calld->method_params->retry_policy();
1427 if (retry_policy == nullptr) return false;
1428 // If we've already dispatched a retry from this call, return true.
1429 // This catches the case where the batch has multiple callbacks
1430 // (i.e., it includes either recv_message or recv_initial_metadata).
1431 subchannel_call_retry_state* retry_state = nullptr;
1432 if (batch_data != nullptr) {
1433 retry_state = static_cast<subchannel_call_retry_state*>(
1434 grpc_connected_subchannel_call_get_parent_data(
1435 batch_data->subchannel_call));
1436 if (retry_state->retry_dispatched) {
1437 if (grpc_client_channel_trace.enabled()) {
1438 gpr_log(GPR_DEBUG, "chand=%p calld=%p: retry already dispatched", chand,
1439 calld);
1440 }
1441 return true;
1442 }
1443 }
1444 // Check status.
1445 if (status == GRPC_STATUS_OK) {
1446 grpc_server_retry_throttle_data_record_success(calld->retry_throttle_data);
1447 if (grpc_client_channel_trace.enabled()) {
1448 gpr_log(GPR_DEBUG, "chand=%p calld=%p: call succeeded", chand, calld);
1449 }
1450 return false;
1451 }
1452 // Status is not OK. Check whether the status is retryable.
1453 if (!retry_policy->retryable_status_codes.Contains(status)) {
1454 if (grpc_client_channel_trace.enabled()) {
1455 gpr_log(GPR_DEBUG,
1456 "chand=%p calld=%p: status %s not configured as retryable", chand,
1457 calld, grpc_status_code_to_string(status));
1458 }
1459 return false;
1460 }
1461 // Record the failure and check whether retries are throttled.
1462 // Note that it's important for this check to come after the status
1463 // code check above, since we should only record failures whose statuses
1464 // match the configured retryable status codes, so that we don't count
1465 // things like failures due to malformed requests (INVALID_ARGUMENT).
1466 // Conversely, it's important for this to come before the remaining
1467 // checks, so that we don't fail to record failures due to other factors.
1468 if (!grpc_server_retry_throttle_data_record_failure(
1469 calld->retry_throttle_data)) {
1470 if (grpc_client_channel_trace.enabled()) {
1471 gpr_log(GPR_DEBUG, "chand=%p calld=%p: retries throttled", chand, calld);
1472 }
1473 return false;
1474 }
1475 // Check whether the call is committed.
1476 if (calld->retry_committed) {
1477 if (grpc_client_channel_trace.enabled()) {
1478 gpr_log(GPR_DEBUG, "chand=%p calld=%p: retries already committed", chand,
1479 calld);
1480 }
1481 return false;
1482 }
1483 // Check whether we have retries remaining.
1484 ++calld->num_attempts_completed;
1485 if (calld->num_attempts_completed >= retry_policy->max_attempts) {
1486 if (grpc_client_channel_trace.enabled()) {
1487 gpr_log(GPR_DEBUG, "chand=%p calld=%p: exceeded %d retry attempts", chand,
1488 calld, retry_policy->max_attempts);
1489 }
1490 return false;
1491 }
1492 // If the call was cancelled from the surface, don't retry.
1493 if (calld->cancel_error != GRPC_ERROR_NONE) {
1494 if (grpc_client_channel_trace.enabled()) {
1495 gpr_log(GPR_DEBUG,
1496 "chand=%p calld=%p: call cancelled from surface, not retrying",
1497 chand, calld);
1498 }
1499 return false;
1500 }
1501 // Check server push-back.
1502 grpc_millis server_pushback_ms = -1;
1503 if (server_pushback_md != nullptr) {
1504 // If the value is "-1" or any other unparseable string, we do not retry.
1505 uint32_t ms;
1506 if (!grpc_parse_slice_to_uint32(GRPC_MDVALUE(*server_pushback_md), &ms)) {
1507 if (grpc_client_channel_trace.enabled()) {
1508 gpr_log(GPR_DEBUG,
1509 "chand=%p calld=%p: not retrying due to server push-back",
1510 chand, calld);
1511 }
1512 return false;
1513 } else {
1514 if (grpc_client_channel_trace.enabled()) {
1515 gpr_log(GPR_DEBUG,
1516 "chand=%p calld=%p: server push-back: retry in %u ms", chand,
1517 calld, ms);
1518 }
1519 server_pushback_ms = (grpc_millis)ms;
1520 }
1521 }
1522 do_retry(elem, retry_state, server_pushback_ms);
1523 return true;
1524}
1525
1526//
1527// subchannel_batch_data
1528//
1529
1530static subchannel_batch_data* batch_data_create(grpc_call_element* elem,
1531 int refcount) {
1532 call_data* calld = static_cast<call_data*>(elem->call_data);
1533 subchannel_call_retry_state* retry_state =
1534 static_cast<subchannel_call_retry_state*>(
1535 grpc_connected_subchannel_call_get_parent_data(
1536 calld->subchannel_call));
1537 subchannel_batch_data* batch_data = static_cast<subchannel_batch_data*>(
1538 gpr_arena_alloc(calld->arena, sizeof(*batch_data)));
1539 batch_data->elem = elem;
1540 batch_data->subchannel_call =
1541 GRPC_SUBCHANNEL_CALL_REF(calld->subchannel_call, "batch_data_create");
1542 batch_data->batch.payload = &retry_state->batch_payload;
1543 gpr_ref_init(&batch_data->refs, refcount);
1544 GRPC_CLOSURE_INIT(&batch_data->on_complete, on_complete, batch_data,
1545 grpc_schedule_on_exec_ctx);
1546 batch_data->batch.on_complete = &batch_data->on_complete;
1547 GRPC_CALL_STACK_REF(calld->owning_call, "batch_data");
1548 return batch_data;
1549}
1550
1551static void batch_data_unref(subchannel_batch_data* batch_data) {
1552 if (gpr_unref(&batch_data->refs)) {
1553 if (batch_data->send_initial_metadata_storage != nullptr) {
1554 grpc_metadata_batch_destroy(&batch_data->send_initial_metadata);
1555 }
1556 if (batch_data->send_trailing_metadata_storage != nullptr) {
1557 grpc_metadata_batch_destroy(&batch_data->send_trailing_metadata);
1558 }
1559 if (batch_data->batch.recv_initial_metadata) {
1560 grpc_metadata_batch_destroy(&batch_data->recv_initial_metadata);
1561 }
1562 if (batch_data->batch.recv_trailing_metadata) {
1563 grpc_metadata_batch_destroy(&batch_data->recv_trailing_metadata);
1564 }
1565 GRPC_SUBCHANNEL_CALL_UNREF(batch_data->subchannel_call, "batch_data_unref");
1566 call_data* calld = static_cast<call_data*>(batch_data->elem->call_data);
1567 GRPC_CALL_STACK_UNREF(calld->owning_call, "batch_data");
1568 }
1569}
1570
1571//
1572// recv_initial_metadata callback handling
1573//
1574
1575// Invokes recv_initial_metadata_ready for a subchannel batch.
1576static void invoke_recv_initial_metadata_callback(void* arg,
1577 grpc_error* error) {
1578 subchannel_batch_data* batch_data = static_cast<subchannel_batch_data*>(arg);
1579 channel_data* chand =
1580 static_cast<channel_data*>(batch_data->elem->channel_data);
1581 call_data* calld = static_cast<call_data*>(batch_data->elem->call_data);
1582 // Find pending batch.
1583 pending_batch* pending = nullptr;
1584 for (size_t i = 0; i < GPR_ARRAY_SIZE(calld->pending_batches); ++i) {
1585 grpc_transport_stream_op_batch* batch = calld->pending_batches[i].batch;
1586 if (batch != nullptr && batch->recv_initial_metadata &&
1587 batch->payload->recv_initial_metadata.recv_initial_metadata_ready !=
1588 nullptr) {
1589 if (grpc_client_channel_trace.enabled()) {
1590 gpr_log(GPR_DEBUG,
1591 "chand=%p calld=%p: invoking recv_initial_metadata_ready for "
1592 "pending batch at index %" PRIuPTR,
1593 chand, calld, i);
1594 }
1595 pending = &calld->pending_batches[i];
1596 break;
1597 }
1598 }
1599 GPR_ASSERT(pending != nullptr);
1600 // Return metadata.
1601 grpc_metadata_batch_move(
1602 &batch_data->recv_initial_metadata,
1603 pending->batch->payload->recv_initial_metadata.recv_initial_metadata);
1604 // Update bookkeeping.
1605 // Note: Need to do this before invoking the callback, since invoking
1606 // the callback will result in yielding the call combiner.
1607 grpc_closure* recv_initial_metadata_ready =
1608 pending->batch->payload->recv_initial_metadata
1609 .recv_initial_metadata_ready;
1610 pending->batch->payload->recv_initial_metadata.recv_initial_metadata_ready =
1611 nullptr;
1612 maybe_clear_pending_batch(batch_data->elem, pending);
1613 batch_data_unref(batch_data);
1614 // Invoke callback.
1615 GRPC_CLOSURE_RUN(recv_initial_metadata_ready, GRPC_ERROR_REF(error));
1616}
1617
1618// Intercepts recv_initial_metadata_ready callback for retries.
1619// Commits the call and returns the initial metadata up the stack.
1620static void recv_initial_metadata_ready(void* arg, grpc_error* error) {
1621 subchannel_batch_data* batch_data = static_cast<subchannel_batch_data*>(arg);
1622 grpc_call_element* elem = batch_data->elem;
1623 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1624 call_data* calld = static_cast<call_data*>(elem->call_data);
1625 if (grpc_client_channel_trace.enabled()) {
1626 gpr_log(GPR_DEBUG,
1627 "chand=%p calld=%p: got recv_initial_metadata_ready, error=%s",
1628 chand, calld, grpc_error_string(error));
1629 }
1630 subchannel_call_retry_state* retry_state =
1631 static_cast<subchannel_call_retry_state*>(
1632 grpc_connected_subchannel_call_get_parent_data(
1633 batch_data->subchannel_call));
1634 // If we got an error or a Trailers-Only response and have not yet gotten
1635 // the recv_trailing_metadata on_complete callback, then defer
1636 // propagating this callback back to the surface. We can evaluate whether
1637 // to retry when recv_trailing_metadata comes back.
1638 if ((batch_data->trailing_metadata_available || error != GRPC_ERROR_NONE) &&
1639 !retry_state->completed_recv_trailing_metadata) {
1640 if (grpc_client_channel_trace.enabled()) {
1641 gpr_log(GPR_DEBUG,
1642 "chand=%p calld=%p: deferring recv_initial_metadata_ready "
1643 "(Trailers-Only)",
1644 chand, calld);
1645 }
1646 retry_state->recv_initial_metadata_ready_deferred = true;
1647 retry_state->recv_initial_metadata_error = GRPC_ERROR_REF(error);
1648 if (!retry_state->started_recv_trailing_metadata) {
1649 // recv_trailing_metadata not yet started by application; start it
1650 // ourselves to get status.
1651 start_internal_recv_trailing_metadata(elem);
1652 } else {
1653 GRPC_CALL_COMBINER_STOP(
1654 calld->call_combiner,
1655 "recv_initial_metadata_ready trailers-only or error");
1656 }
1657 return;
1658 }
1659 // Received valid initial metadata, so commit the call.
1660 retry_commit(elem, retry_state);
1661 // Manually invoking a callback function; it does not take ownership of error.
1662 invoke_recv_initial_metadata_callback(batch_data, error);
1663 GRPC_ERROR_UNREF(error);
1664}
1665
1666//
1667// recv_message callback handling
1668//
1669
1670// Invokes recv_message_ready for a subchannel batch.
1671static void invoke_recv_message_callback(void* arg, grpc_error* error) {
1672 subchannel_batch_data* batch_data = static_cast<subchannel_batch_data*>(arg);
1673 channel_data* chand =
1674 static_cast<channel_data*>(batch_data->elem->channel_data);
1675 call_data* calld = static_cast<call_data*>(batch_data->elem->call_data);
1676 // Find pending op.
1677 pending_batch* pending = nullptr;
1678 for (size_t i = 0; i < GPR_ARRAY_SIZE(calld->pending_batches); ++i) {
1679 grpc_transport_stream_op_batch* batch = calld->pending_batches[i].batch;
1680 if (batch != nullptr && batch->recv_message &&
1681 batch->payload->recv_message.recv_message_ready != nullptr) {
1682 if (grpc_client_channel_trace.enabled()) {
1683 gpr_log(GPR_DEBUG,
1684 "chand=%p calld=%p: invoking recv_message_ready for "
1685 "pending batch at index %" PRIuPTR,
1686 chand, calld, i);
1687 }
1688 pending = &calld->pending_batches[i];
1689 break;
1690 }
1691 }
1692 GPR_ASSERT(pending != nullptr);
1693 // Return payload.
1694 *pending->batch->payload->recv_message.recv_message =
Mark D. Roth3d8b32d2018-03-09 13:25:40 -08001695 std::move(batch_data->recv_message);
Mark D. Roth718c8342018-02-28 13:00:04 -08001696 // Update bookkeeping.
1697 // Note: Need to do this before invoking the callback, since invoking
1698 // the callback will result in yielding the call combiner.
1699 grpc_closure* recv_message_ready =
1700 pending->batch->payload->recv_message.recv_message_ready;
1701 pending->batch->payload->recv_message.recv_message_ready = nullptr;
1702 maybe_clear_pending_batch(batch_data->elem, pending);
1703 batch_data_unref(batch_data);
1704 // Invoke callback.
1705 GRPC_CLOSURE_RUN(recv_message_ready, GRPC_ERROR_REF(error));
1706}
1707
1708// Intercepts recv_message_ready callback for retries.
1709// Commits the call and returns the message up the stack.
1710static void recv_message_ready(void* arg, grpc_error* error) {
1711 subchannel_batch_data* batch_data = static_cast<subchannel_batch_data*>(arg);
1712 grpc_call_element* elem = batch_data->elem;
1713 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1714 call_data* calld = static_cast<call_data*>(elem->call_data);
1715 if (grpc_client_channel_trace.enabled()) {
1716 gpr_log(GPR_DEBUG, "chand=%p calld=%p: got recv_message_ready, error=%s",
1717 chand, calld, grpc_error_string(error));
1718 }
1719 subchannel_call_retry_state* retry_state =
1720 static_cast<subchannel_call_retry_state*>(
1721 grpc_connected_subchannel_call_get_parent_data(
1722 batch_data->subchannel_call));
1723 // If we got an error or the payload was nullptr and we have not yet gotten
1724 // the recv_trailing_metadata on_complete callback, then defer
1725 // propagating this callback back to the surface. We can evaluate whether
1726 // to retry when recv_trailing_metadata comes back.
1727 if ((batch_data->recv_message == nullptr || error != GRPC_ERROR_NONE) &&
1728 !retry_state->completed_recv_trailing_metadata) {
1729 if (grpc_client_channel_trace.enabled()) {
1730 gpr_log(GPR_DEBUG,
1731 "chand=%p calld=%p: deferring recv_message_ready (nullptr "
1732 "message and recv_trailing_metadata pending)",
1733 chand, calld);
1734 }
1735 retry_state->recv_message_ready_deferred = true;
1736 retry_state->recv_message_error = GRPC_ERROR_REF(error);
1737 if (!retry_state->started_recv_trailing_metadata) {
1738 // recv_trailing_metadata not yet started by application; start it
1739 // ourselves to get status.
1740 start_internal_recv_trailing_metadata(elem);
1741 } else {
1742 GRPC_CALL_COMBINER_STOP(calld->call_combiner, "recv_message_ready null");
1743 }
1744 return;
1745 }
1746 // Received a valid message, so commit the call.
1747 retry_commit(elem, retry_state);
1748 // Manually invoking a callback function; it does not take ownership of error.
1749 invoke_recv_message_callback(batch_data, error);
1750 GRPC_ERROR_UNREF(error);
1751}
1752
1753//
1754// on_complete callback handling
1755//
1756
1757// Updates retry_state to reflect the ops completed in batch_data.
1758static void update_retry_state_for_completed_batch(
1759 subchannel_batch_data* batch_data,
1760 subchannel_call_retry_state* retry_state) {
1761 if (batch_data->batch.send_initial_metadata) {
1762 retry_state->completed_send_initial_metadata = true;
1763 }
1764 if (batch_data->batch.send_message) {
1765 ++retry_state->completed_send_message_count;
1766 }
1767 if (batch_data->batch.send_trailing_metadata) {
1768 retry_state->completed_send_trailing_metadata = true;
1769 }
1770 if (batch_data->batch.recv_initial_metadata) {
1771 retry_state->completed_recv_initial_metadata = true;
1772 }
1773 if (batch_data->batch.recv_message) {
1774 ++retry_state->completed_recv_message_count;
1775 }
1776 if (batch_data->batch.recv_trailing_metadata) {
1777 retry_state->completed_recv_trailing_metadata = true;
1778 }
1779}
1780
1781// Represents a closure that needs to run as a result of a completed batch.
1782typedef struct {
1783 grpc_closure* closure;
1784 grpc_error* error;
1785 const char* reason;
1786} closure_to_execute;
1787
1788// Adds any necessary closures for deferred recv_initial_metadata and
1789// recv_message callbacks to closures, updating *num_closures as needed.
1790static void add_closures_for_deferred_recv_callbacks(
1791 subchannel_batch_data* batch_data, subchannel_call_retry_state* retry_state,
1792 closure_to_execute* closures, size_t* num_closures) {
1793 if (batch_data->batch.recv_trailing_metadata &&
1794 retry_state->recv_initial_metadata_ready_deferred) {
1795 closure_to_execute* closure = &closures[(*num_closures)++];
1796 closure->closure =
1797 GRPC_CLOSURE_INIT(&batch_data->recv_initial_metadata_ready,
1798 invoke_recv_initial_metadata_callback, batch_data,
1799 grpc_schedule_on_exec_ctx);
1800 closure->error = retry_state->recv_initial_metadata_error;
1801 closure->reason = "resuming recv_initial_metadata_ready";
1802 }
1803 if (batch_data->batch.recv_trailing_metadata &&
1804 retry_state->recv_message_ready_deferred) {
1805 closure_to_execute* closure = &closures[(*num_closures)++];
1806 closure->closure = GRPC_CLOSURE_INIT(&batch_data->recv_message_ready,
1807 invoke_recv_message_callback,
1808 batch_data, grpc_schedule_on_exec_ctx);
1809 closure->error = retry_state->recv_message_error;
1810 closure->reason = "resuming recv_message_ready";
1811 }
1812}
1813
1814// If there are any cached ops to replay or pending ops to start on the
1815// subchannel call, adds a closure to closures to invoke
1816// start_retriable_subchannel_batches(), updating *num_closures as needed.
1817static void add_closures_for_replay_or_pending_send_ops(
1818 grpc_call_element* elem, subchannel_batch_data* batch_data,
1819 subchannel_call_retry_state* retry_state, closure_to_execute* closures,
1820 size_t* num_closures) {
1821 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1822 call_data* calld = static_cast<call_data*>(elem->call_data);
1823 bool have_pending_send_message_ops =
1824 retry_state->started_send_message_count < calld->send_messages.size();
1825 bool have_pending_send_trailing_metadata_op =
1826 calld->seen_send_trailing_metadata &&
1827 !retry_state->started_send_trailing_metadata;
1828 if (!have_pending_send_message_ops &&
1829 !have_pending_send_trailing_metadata_op) {
1830 for (size_t i = 0; i < GPR_ARRAY_SIZE(calld->pending_batches); ++i) {
1831 pending_batch* pending = &calld->pending_batches[i];
1832 grpc_transport_stream_op_batch* batch = pending->batch;
1833 if (batch == nullptr || pending->send_ops_cached) continue;
1834 if (batch->send_message) have_pending_send_message_ops = true;
1835 if (batch->send_trailing_metadata) {
1836 have_pending_send_trailing_metadata_op = true;
1837 }
1838 }
1839 }
1840 if (have_pending_send_message_ops || have_pending_send_trailing_metadata_op) {
1841 if (grpc_client_channel_trace.enabled()) {
1842 gpr_log(GPR_DEBUG,
1843 "chand=%p calld=%p: starting next batch for pending send op(s)",
1844 chand, calld);
1845 }
1846 closure_to_execute* closure = &closures[(*num_closures)++];
1847 closure->closure = GRPC_CLOSURE_INIT(
1848 &batch_data->batch.handler_private.closure,
1849 start_retriable_subchannel_batches, elem, grpc_schedule_on_exec_ctx);
1850 closure->error = GRPC_ERROR_NONE;
1851 closure->reason = "starting next batch for send_* op(s)";
1852 }
1853}
1854
1855// For any pending batch completed in batch_data, adds the necessary
1856// completion closures to closures, updating *num_closures as needed.
1857static void add_closures_for_completed_pending_batches(
1858 grpc_call_element* elem, subchannel_batch_data* batch_data,
1859 subchannel_call_retry_state* retry_state, grpc_error* error,
1860 closure_to_execute* closures, size_t* num_closures) {
1861 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1862 call_data* calld = static_cast<call_data*>(elem->call_data);
1863 for (size_t i = 0; i < GPR_ARRAY_SIZE(calld->pending_batches); ++i) {
1864 pending_batch* pending = &calld->pending_batches[i];
1865 if (pending_batch_is_completed(pending, calld, retry_state)) {
1866 if (grpc_client_channel_trace.enabled()) {
1867 gpr_log(GPR_DEBUG,
1868 "chand=%p calld=%p: pending batch completed at index %" PRIuPTR,
1869 chand, calld, i);
1870 }
1871 // Copy the trailing metadata to return it to the surface.
1872 if (batch_data->batch.recv_trailing_metadata) {
1873 grpc_metadata_batch_move(&batch_data->recv_trailing_metadata,
1874 pending->batch->payload->recv_trailing_metadata
1875 .recv_trailing_metadata);
1876 }
1877 closure_to_execute* closure = &closures[(*num_closures)++];
1878 closure->closure = pending->batch->on_complete;
1879 closure->error = GRPC_ERROR_REF(error);
1880 closure->reason = "on_complete for pending batch";
1881 pending->batch->on_complete = nullptr;
1882 maybe_clear_pending_batch(elem, pending);
1883 }
1884 }
1885 GRPC_ERROR_UNREF(error);
1886}
1887
1888// For any pending batch containing an op that has not yet been started,
1889// adds the pending batch's completion closures to closures, updating
1890// *num_closures as needed.
1891static void add_closures_to_fail_unstarted_pending_batches(
1892 grpc_call_element* elem, subchannel_call_retry_state* retry_state,
1893 grpc_error* error, closure_to_execute* closures, size_t* num_closures) {
1894 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1895 call_data* calld = static_cast<call_data*>(elem->call_data);
1896 for (size_t i = 0; i < GPR_ARRAY_SIZE(calld->pending_batches); ++i) {
1897 pending_batch* pending = &calld->pending_batches[i];
1898 if (pending_batch_is_unstarted(pending, calld, retry_state)) {
1899 if (grpc_client_channel_trace.enabled()) {
1900 gpr_log(GPR_DEBUG,
1901 "chand=%p calld=%p: failing unstarted pending batch at index "
1902 "%" PRIuPTR,
1903 chand, calld, i);
1904 }
1905 if (pending->batch->recv_initial_metadata) {
1906 closure_to_execute* closure = &closures[(*num_closures)++];
1907 closure->closure = pending->batch->payload->recv_initial_metadata
1908 .recv_initial_metadata_ready;
1909 closure->error = GRPC_ERROR_REF(error);
1910 closure->reason =
1911 "failing recv_initial_metadata_ready for pending batch";
1912 pending->batch->payload->recv_initial_metadata
1913 .recv_initial_metadata_ready = nullptr;
1914 }
1915 if (pending->batch->recv_message) {
1916 *pending->batch->payload->recv_message.recv_message = nullptr;
1917 closure_to_execute* closure = &closures[(*num_closures)++];
1918 closure->closure =
1919 pending->batch->payload->recv_message.recv_message_ready;
1920 closure->error = GRPC_ERROR_REF(error);
1921 closure->reason = "failing recv_message_ready for pending batch";
1922 pending->batch->payload->recv_message.recv_message_ready = nullptr;
1923 }
1924 closure_to_execute* closure = &closures[(*num_closures)++];
1925 closure->closure = pending->batch->on_complete;
1926 closure->error = GRPC_ERROR_REF(error);
1927 closure->reason = "failing on_complete for pending batch";
1928 pending->batch->on_complete = nullptr;
1929 maybe_clear_pending_batch(elem, pending);
1930 }
1931 }
1932 GRPC_ERROR_UNREF(error);
1933}
1934
1935// Callback used to intercept on_complete from subchannel calls.
1936// Called only when retries are enabled.
1937static void on_complete(void* arg, grpc_error* error) {
1938 subchannel_batch_data* batch_data = static_cast<subchannel_batch_data*>(arg);
1939 grpc_call_element* elem = batch_data->elem;
1940 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1941 call_data* calld = static_cast<call_data*>(elem->call_data);
1942 if (grpc_client_channel_trace.enabled()) {
1943 char* batch_str = grpc_transport_stream_op_batch_string(&batch_data->batch);
1944 gpr_log(GPR_DEBUG, "chand=%p calld=%p: got on_complete, error=%s, batch=%s",
1945 chand, calld, grpc_error_string(error), batch_str);
1946 gpr_free(batch_str);
1947 }
1948 subchannel_call_retry_state* retry_state =
1949 static_cast<subchannel_call_retry_state*>(
1950 grpc_connected_subchannel_call_get_parent_data(
1951 batch_data->subchannel_call));
1952 // If we have previously completed recv_trailing_metadata, then the
1953 // call is finished.
1954 bool call_finished = retry_state->completed_recv_trailing_metadata;
1955 // Update bookkeeping in retry_state.
1956 update_retry_state_for_completed_batch(batch_data, retry_state);
1957 if (call_finished) {
1958 if (grpc_client_channel_trace.enabled()) {
1959 gpr_log(GPR_DEBUG, "chand=%p calld=%p: call already finished", chand,
1960 calld);
1961 }
1962 } else {
1963 // Check if this batch finished the call, and if so, get its status.
1964 // The call is finished if either (a) this callback was invoked with
1965 // an error or (b) we receive status.
1966 grpc_status_code status = GRPC_STATUS_OK;
1967 grpc_mdelem* server_pushback_md = nullptr;
1968 if (error != GRPC_ERROR_NONE) { // Case (a).
1969 call_finished = true;
1970 grpc_error_get_status(error, calld->deadline, &status, nullptr, nullptr,
1971 nullptr);
1972 } else if (batch_data->batch.recv_trailing_metadata) { // Case (b).
1973 call_finished = true;
1974 grpc_metadata_batch* md_batch =
1975 batch_data->batch.payload->recv_trailing_metadata
1976 .recv_trailing_metadata;
1977 GPR_ASSERT(md_batch->idx.named.grpc_status != nullptr);
1978 status = grpc_get_status_code_from_metadata(
1979 md_batch->idx.named.grpc_status->md);
1980 if (md_batch->idx.named.grpc_retry_pushback_ms != nullptr) {
1981 server_pushback_md = &md_batch->idx.named.grpc_retry_pushback_ms->md;
1982 }
1983 } else if (retry_state->completed_recv_trailing_metadata) {
1984 call_finished = true;
1985 }
1986 if (call_finished && grpc_client_channel_trace.enabled()) {
1987 gpr_log(GPR_DEBUG, "chand=%p calld=%p: call finished, status=%s", chand,
1988 calld, grpc_status_code_to_string(status));
1989 }
1990 // If the call is finished, check if we should retry.
1991 if (call_finished &&
1992 maybe_retry(elem, batch_data, status, server_pushback_md)) {
1993 // Unref batch_data for deferred recv_initial_metadata_ready or
1994 // recv_message_ready callbacks, if any.
1995 if (batch_data->batch.recv_trailing_metadata &&
1996 retry_state->recv_initial_metadata_ready_deferred) {
1997 batch_data_unref(batch_data);
1998 GRPC_ERROR_UNREF(retry_state->recv_initial_metadata_error);
1999 }
2000 if (batch_data->batch.recv_trailing_metadata &&
2001 retry_state->recv_message_ready_deferred) {
2002 batch_data_unref(batch_data);
2003 GRPC_ERROR_UNREF(retry_state->recv_message_error);
2004 }
2005 batch_data_unref(batch_data);
2006 return;
2007 }
2008 }
2009 // If the call is finished or retries are committed, free cached data for
2010 // send ops that we've just completed.
2011 if (call_finished || calld->retry_committed) {
2012 free_cached_send_op_data_for_completed_batch(elem, batch_data, retry_state);
2013 }
2014 // Call not being retried.
2015 // Construct list of closures to execute.
2016 // Max number of closures is number of pending batches plus one for
2017 // each of:
2018 // - recv_initial_metadata_ready (either deferred or unstarted)
2019 // - recv_message_ready (either deferred or unstarted)
2020 // - starting a new batch for pending send ops
2021 closure_to_execute closures[GPR_ARRAY_SIZE(calld->pending_batches) + 3];
2022 size_t num_closures = 0;
2023 // If there are deferred recv_initial_metadata_ready or recv_message_ready
2024 // callbacks, add them to closures.
2025 add_closures_for_deferred_recv_callbacks(batch_data, retry_state, closures,
2026 &num_closures);
2027 // Find pending batches whose ops are now complete and add their
2028 // on_complete callbacks to closures.
2029 add_closures_for_completed_pending_batches(elem, batch_data, retry_state,
2030 GRPC_ERROR_REF(error), closures,
2031 &num_closures);
2032 // Add closures to handle any pending batches that have not yet been started.
2033 // If the call is finished, we fail these batches; otherwise, we add a
2034 // callback to start_retriable_subchannel_batches() to start them on
2035 // the subchannel call.
2036 if (call_finished) {
2037 add_closures_to_fail_unstarted_pending_batches(
2038 elem, retry_state, GRPC_ERROR_REF(error), closures, &num_closures);
2039 } else {
2040 add_closures_for_replay_or_pending_send_ops(elem, batch_data, retry_state,
2041 closures, &num_closures);
2042 }
2043 // Don't need batch_data anymore.
2044 batch_data_unref(batch_data);
2045 // Schedule all of the closures identified above.
2046 // Note that the call combiner will be yielded for each closure that
2047 // we schedule. We're already running in the call combiner, so one of
2048 // the closures can be scheduled directly, but the others will
2049 // have to re-enter the call combiner.
2050 if (num_closures > 0) {
2051 GRPC_CLOSURE_SCHED(closures[0].closure, closures[0].error);
2052 for (size_t i = 1; i < num_closures; ++i) {
2053 GRPC_CALL_COMBINER_START(calld->call_combiner, closures[i].closure,
2054 closures[i].error, closures[i].reason);
2055 }
2056 } else {
2057 GRPC_CALL_COMBINER_STOP(calld->call_combiner,
2058 "no closures to run for on_complete");
2059 }
2060}
2061
2062//
2063// subchannel batch construction
2064//
2065
2066// Helper function used to start a subchannel batch in the call combiner.
2067static void start_batch_in_call_combiner(void* arg, grpc_error* ignored) {
2068 grpc_transport_stream_op_batch* batch =
2069 static_cast<grpc_transport_stream_op_batch*>(arg);
2070 grpc_subchannel_call* subchannel_call =
2071 static_cast<grpc_subchannel_call*>(batch->handler_private.extra_arg);
2072 // Note: This will release the call combiner.
2073 grpc_subchannel_call_process_op(subchannel_call, batch);
2074}
2075
2076// Adds retriable send_initial_metadata op to batch_data.
2077static void add_retriable_send_initial_metadata_op(
2078 call_data* calld, subchannel_call_retry_state* retry_state,
2079 subchannel_batch_data* batch_data) {
2080 // Maps the number of retries to the corresponding metadata value slice.
2081 static const grpc_slice* retry_count_strings[] = {
2082 &GRPC_MDSTR_1, &GRPC_MDSTR_2, &GRPC_MDSTR_3, &GRPC_MDSTR_4};
2083 // We need to make a copy of the metadata batch for each attempt, since
2084 // the filters in the subchannel stack may modify this batch, and we don't
2085 // want those modifications to be passed forward to subsequent attempts.
2086 //
2087 // If we've already completed one or more attempts, add the
2088 // grpc-retry-attempts header.
2089 batch_data->send_initial_metadata_storage =
2090 static_cast<grpc_linked_mdelem*>(gpr_arena_alloc(
2091 calld->arena, sizeof(grpc_linked_mdelem) *
2092 (calld->send_initial_metadata.list.count +
2093 (calld->num_attempts_completed > 0))));
2094 grpc_metadata_batch_copy(&calld->send_initial_metadata,
2095 &batch_data->send_initial_metadata,
2096 batch_data->send_initial_metadata_storage);
2097 if (batch_data->send_initial_metadata.idx.named.grpc_previous_rpc_attempts !=
2098 nullptr) {
2099 grpc_metadata_batch_remove(
2100 &batch_data->send_initial_metadata,
2101 batch_data->send_initial_metadata.idx.named.grpc_previous_rpc_attempts);
2102 }
2103 if (calld->num_attempts_completed > 0) {
2104 grpc_mdelem retry_md = grpc_mdelem_from_slices(
2105 GRPC_MDSTR_GRPC_PREVIOUS_RPC_ATTEMPTS,
2106 *retry_count_strings[calld->num_attempts_completed - 1]);
2107 grpc_error* error = grpc_metadata_batch_add_tail(
2108 &batch_data->send_initial_metadata,
2109 &batch_data->send_initial_metadata_storage[calld->send_initial_metadata
2110 .list.count],
2111 retry_md);
2112 if (error != GRPC_ERROR_NONE) {
2113 gpr_log(GPR_ERROR, "error adding retry metadata: %s",
2114 grpc_error_string(error));
2115 GPR_ASSERT(false);
2116 }
2117 }
2118 retry_state->started_send_initial_metadata = true;
2119 batch_data->batch.send_initial_metadata = true;
2120 batch_data->batch.payload->send_initial_metadata.send_initial_metadata =
2121 &batch_data->send_initial_metadata;
2122 batch_data->batch.payload->send_initial_metadata.send_initial_metadata_flags =
2123 calld->send_initial_metadata_flags;
2124 batch_data->batch.payload->send_initial_metadata.peer_string =
2125 calld->peer_string;
2126}
2127
2128// Adds retriable send_message op to batch_data.
2129static void add_retriable_send_message_op(
2130 grpc_call_element* elem, subchannel_call_retry_state* retry_state,
2131 subchannel_batch_data* batch_data) {
2132 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2133 call_data* calld = static_cast<call_data*>(elem->call_data);
2134 if (grpc_client_channel_trace.enabled()) {
2135 gpr_log(GPR_DEBUG,
2136 "chand=%p calld=%p: starting calld->send_messages[%" PRIuPTR "]",
2137 chand, calld, retry_state->started_send_message_count);
2138 }
Mark D. Roth3d8b32d2018-03-09 13:25:40 -08002139 grpc_core::ByteStreamCache* cache =
Mark D. Roth718c8342018-02-28 13:00:04 -08002140 calld->send_messages[retry_state->started_send_message_count];
2141 ++retry_state->started_send_message_count;
Mark D. Roth3d8b32d2018-03-09 13:25:40 -08002142 batch_data->send_message.Init(cache);
Mark D. Roth718c8342018-02-28 13:00:04 -08002143 batch_data->batch.send_message = true;
Mark D. Roth3d8b32d2018-03-09 13:25:40 -08002144 batch_data->batch.payload->send_message.send_message.reset(
2145 batch_data->send_message.get());
Mark D. Roth718c8342018-02-28 13:00:04 -08002146}
2147
2148// Adds retriable send_trailing_metadata op to batch_data.
2149static void add_retriable_send_trailing_metadata_op(
2150 call_data* calld, subchannel_call_retry_state* retry_state,
2151 subchannel_batch_data* batch_data) {
2152 // We need to make a copy of the metadata batch for each attempt, since
2153 // the filters in the subchannel stack may modify this batch, and we don't
2154 // want those modifications to be passed forward to subsequent attempts.
2155 batch_data->send_trailing_metadata_storage =
2156 static_cast<grpc_linked_mdelem*>(gpr_arena_alloc(
2157 calld->arena, sizeof(grpc_linked_mdelem) *
2158 calld->send_trailing_metadata.list.count));
2159 grpc_metadata_batch_copy(&calld->send_trailing_metadata,
2160 &batch_data->send_trailing_metadata,
2161 batch_data->send_trailing_metadata_storage);
2162 retry_state->started_send_trailing_metadata = true;
2163 batch_data->batch.send_trailing_metadata = true;
2164 batch_data->batch.payload->send_trailing_metadata.send_trailing_metadata =
2165 &batch_data->send_trailing_metadata;
2166}
2167
2168// Adds retriable recv_initial_metadata op to batch_data.
2169static void add_retriable_recv_initial_metadata_op(
2170 call_data* calld, subchannel_call_retry_state* retry_state,
2171 subchannel_batch_data* batch_data) {
2172 retry_state->started_recv_initial_metadata = true;
2173 batch_data->batch.recv_initial_metadata = true;
2174 grpc_metadata_batch_init(&batch_data->recv_initial_metadata);
2175 batch_data->batch.payload->recv_initial_metadata.recv_initial_metadata =
2176 &batch_data->recv_initial_metadata;
2177 batch_data->batch.payload->recv_initial_metadata.trailing_metadata_available =
2178 &batch_data->trailing_metadata_available;
2179 GRPC_CLOSURE_INIT(&batch_data->recv_initial_metadata_ready,
2180 recv_initial_metadata_ready, batch_data,
2181 grpc_schedule_on_exec_ctx);
2182 batch_data->batch.payload->recv_initial_metadata.recv_initial_metadata_ready =
2183 &batch_data->recv_initial_metadata_ready;
2184}
2185
2186// Adds retriable recv_message op to batch_data.
2187static void add_retriable_recv_message_op(
2188 call_data* calld, subchannel_call_retry_state* retry_state,
2189 subchannel_batch_data* batch_data) {
2190 ++retry_state->started_recv_message_count;
2191 batch_data->batch.recv_message = true;
2192 batch_data->batch.payload->recv_message.recv_message =
2193 &batch_data->recv_message;
2194 GRPC_CLOSURE_INIT(&batch_data->recv_message_ready, recv_message_ready,
2195 batch_data, grpc_schedule_on_exec_ctx);
2196 batch_data->batch.payload->recv_message.recv_message_ready =
2197 &batch_data->recv_message_ready;
2198}
2199
2200// Adds retriable recv_trailing_metadata op to batch_data.
2201static void add_retriable_recv_trailing_metadata_op(
2202 call_data* calld, subchannel_call_retry_state* retry_state,
2203 subchannel_batch_data* batch_data) {
2204 retry_state->started_recv_trailing_metadata = true;
2205 batch_data->batch.recv_trailing_metadata = true;
2206 grpc_metadata_batch_init(&batch_data->recv_trailing_metadata);
2207 batch_data->batch.payload->recv_trailing_metadata.recv_trailing_metadata =
2208 &batch_data->recv_trailing_metadata;
2209 batch_data->batch.collect_stats = true;
2210 batch_data->batch.payload->collect_stats.collect_stats =
2211 &batch_data->collect_stats;
2212}
2213
2214// Helper function used to start a recv_trailing_metadata batch. This
2215// is used in the case where a recv_initial_metadata or recv_message
2216// op fails in a way that we know the call is over but when the application
2217// has not yet started its own recv_trailing_metadata op.
2218static void start_internal_recv_trailing_metadata(grpc_call_element* elem) {
2219 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2220 call_data* calld = static_cast<call_data*>(elem->call_data);
2221 if (grpc_client_channel_trace.enabled()) {
2222 gpr_log(GPR_DEBUG,
2223 "chand=%p calld=%p: call failed but recv_trailing_metadata not "
2224 "started; starting it internally",
2225 chand, calld);
2226 }
2227 subchannel_call_retry_state* retry_state =
2228 static_cast<subchannel_call_retry_state*>(
2229 grpc_connected_subchannel_call_get_parent_data(
2230 calld->subchannel_call));
2231 subchannel_batch_data* batch_data = batch_data_create(elem, 1);
2232 add_retriable_recv_trailing_metadata_op(calld, retry_state, batch_data);
2233 // Note: This will release the call combiner.
2234 grpc_subchannel_call_process_op(calld->subchannel_call, &batch_data->batch);
2235}
2236
2237// If there are any cached send ops that need to be replayed on the
2238// current subchannel call, creates and returns a new subchannel batch
2239// to replay those ops. Otherwise, returns nullptr.
2240static subchannel_batch_data* maybe_create_subchannel_batch_for_replay(
2241 grpc_call_element* elem, subchannel_call_retry_state* retry_state) {
2242 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2243 call_data* calld = static_cast<call_data*>(elem->call_data);
2244 subchannel_batch_data* replay_batch_data = nullptr;
2245 // send_initial_metadata.
2246 if (calld->seen_send_initial_metadata &&
2247 !retry_state->started_send_initial_metadata &&
2248 !calld->pending_send_initial_metadata) {
2249 if (grpc_client_channel_trace.enabled()) {
2250 gpr_log(GPR_DEBUG,
2251 "chand=%p calld=%p: replaying previously completed "
2252 "send_initial_metadata op",
2253 chand, calld);
2254 }
2255 replay_batch_data = batch_data_create(elem, 1);
2256 add_retriable_send_initial_metadata_op(calld, retry_state,
2257 replay_batch_data);
2258 }
2259 // send_message.
2260 // Note that we can only have one send_message op in flight at a time.
2261 if (retry_state->started_send_message_count < calld->send_messages.size() &&
2262 retry_state->started_send_message_count ==
2263 retry_state->completed_send_message_count &&
2264 !calld->pending_send_message) {
2265 if (grpc_client_channel_trace.enabled()) {
2266 gpr_log(GPR_DEBUG,
2267 "chand=%p calld=%p: replaying previously completed "
2268 "send_message op",
2269 chand, calld);
2270 }
2271 if (replay_batch_data == nullptr) {
2272 replay_batch_data = batch_data_create(elem, 1);
2273 }
2274 add_retriable_send_message_op(elem, retry_state, replay_batch_data);
2275 }
2276 // send_trailing_metadata.
2277 // Note that we only add this op if we have no more send_message ops
2278 // to start, since we can't send down any more send_message ops after
2279 // send_trailing_metadata.
2280 if (calld->seen_send_trailing_metadata &&
2281 retry_state->started_send_message_count == calld->send_messages.size() &&
2282 !retry_state->started_send_trailing_metadata &&
2283 !calld->pending_send_trailing_metadata) {
2284 if (grpc_client_channel_trace.enabled()) {
2285 gpr_log(GPR_DEBUG,
2286 "chand=%p calld=%p: replaying previously completed "
2287 "send_trailing_metadata op",
2288 chand, calld);
2289 }
2290 if (replay_batch_data == nullptr) {
2291 replay_batch_data = batch_data_create(elem, 1);
2292 }
2293 add_retriable_send_trailing_metadata_op(calld, retry_state,
2294 replay_batch_data);
2295 }
2296 return replay_batch_data;
2297}
2298
2299// Adds subchannel batches for pending batches to batches, updating
2300// *num_batches as needed.
2301static void add_subchannel_batches_for_pending_batches(
2302 grpc_call_element* elem, subchannel_call_retry_state* retry_state,
2303 grpc_transport_stream_op_batch** batches, size_t* num_batches) {
2304 call_data* calld = static_cast<call_data*>(elem->call_data);
2305 for (size_t i = 0; i < GPR_ARRAY_SIZE(calld->pending_batches); ++i) {
2306 pending_batch* pending = &calld->pending_batches[i];
2307 grpc_transport_stream_op_batch* batch = pending->batch;
2308 if (batch == nullptr) continue;
2309 // Skip any batch that either (a) has already been started on this
2310 // subchannel call or (b) we can't start yet because we're still
2311 // replaying send ops that need to be completed first.
2312 // TODO(roth): Note that if any one op in the batch can't be sent
2313 // yet due to ops that we're replaying, we don't start any of the ops
2314 // in the batch. This is probably okay, but it could conceivably
2315 // lead to increased latency in some cases -- e.g., we could delay
2316 // starting a recv op due to it being in the same batch with a send
2317 // op. If/when we revamp the callback protocol in
2318 // transport_stream_op_batch, we may be able to fix this.
2319 if (batch->send_initial_metadata &&
2320 retry_state->started_send_initial_metadata) {
2321 continue;
2322 }
2323 if (batch->send_message && retry_state->completed_send_message_count <
2324 retry_state->started_send_message_count) {
2325 continue;
2326 }
2327 // Note that we only start send_trailing_metadata if we have no more
2328 // send_message ops to start, since we can't send down any more
2329 // send_message ops after send_trailing_metadata.
2330 if (batch->send_trailing_metadata &&
2331 (retry_state->started_send_message_count + batch->send_message <
2332 calld->send_messages.size() ||
2333 retry_state->started_send_trailing_metadata)) {
2334 continue;
2335 }
2336 if (batch->recv_initial_metadata &&
2337 retry_state->started_recv_initial_metadata) {
2338 continue;
2339 }
2340 if (batch->recv_message && retry_state->completed_recv_message_count <
2341 retry_state->started_recv_message_count) {
2342 continue;
2343 }
2344 if (batch->recv_trailing_metadata &&
2345 retry_state->started_recv_trailing_metadata) {
2346 continue;
2347 }
2348 // If we're not retrying, just send the batch as-is.
2349 if (calld->method_params == nullptr ||
2350 calld->method_params->retry_policy() == nullptr ||
2351 calld->retry_committed) {
2352 batches[(*num_batches)++] = batch;
2353 pending_batch_clear(calld, pending);
2354 continue;
2355 }
2356 // Create batch with the right number of callbacks.
2357 const int num_callbacks =
2358 1 + batch->recv_initial_metadata + batch->recv_message;
2359 subchannel_batch_data* batch_data = batch_data_create(elem, num_callbacks);
2360 // Cache send ops if needed.
2361 maybe_cache_send_ops_for_batch(calld, pending);
2362 // send_initial_metadata.
2363 if (batch->send_initial_metadata) {
2364 add_retriable_send_initial_metadata_op(calld, retry_state, batch_data);
2365 }
2366 // send_message.
2367 if (batch->send_message) {
2368 add_retriable_send_message_op(elem, retry_state, batch_data);
2369 }
2370 // send_trailing_metadata.
2371 if (batch->send_trailing_metadata) {
2372 add_retriable_send_trailing_metadata_op(calld, retry_state, batch_data);
2373 }
2374 // recv_initial_metadata.
2375 if (batch->recv_initial_metadata) {
2376 // recv_flags is only used on the server side.
2377 GPR_ASSERT(batch->payload->recv_initial_metadata.recv_flags == nullptr);
2378 add_retriable_recv_initial_metadata_op(calld, retry_state, batch_data);
2379 }
2380 // recv_message.
2381 if (batch->recv_message) {
2382 add_retriable_recv_message_op(calld, retry_state, batch_data);
2383 }
2384 // recv_trailing_metadata.
2385 if (batch->recv_trailing_metadata) {
2386 GPR_ASSERT(batch->collect_stats);
2387 add_retriable_recv_trailing_metadata_op(calld, retry_state, batch_data);
2388 }
2389 batches[(*num_batches)++] = &batch_data->batch;
2390 }
2391}
2392
2393// Constructs and starts whatever subchannel batches are needed on the
2394// subchannel call.
2395static void start_retriable_subchannel_batches(void* arg, grpc_error* ignored) {
2396 grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
2397 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2398 call_data* calld = static_cast<call_data*>(elem->call_data);
2399 if (grpc_client_channel_trace.enabled()) {
2400 gpr_log(GPR_DEBUG, "chand=%p calld=%p: constructing retriable batches",
2401 chand, calld);
2402 }
2403 subchannel_call_retry_state* retry_state =
2404 static_cast<subchannel_call_retry_state*>(
2405 grpc_connected_subchannel_call_get_parent_data(
2406 calld->subchannel_call));
2407 // We can start up to 6 batches.
2408 grpc_transport_stream_op_batch*
2409 batches[GPR_ARRAY_SIZE(calld->pending_batches)];
2410 size_t num_batches = 0;
2411 // Replay previously-returned send_* ops if needed.
2412 subchannel_batch_data* replay_batch_data =
2413 maybe_create_subchannel_batch_for_replay(elem, retry_state);
2414 if (replay_batch_data != nullptr) {
2415 batches[num_batches++] = &replay_batch_data->batch;
2416 }
2417 // Now add pending batches.
2418 add_subchannel_batches_for_pending_batches(elem, retry_state, batches,
2419 &num_batches);
2420 // Start batches on subchannel call.
2421 // Note that the call combiner will be yielded for each batch that we
2422 // send down. We're already running in the call combiner, so one of
2423 // the batches can be started directly, but the others will have to
2424 // re-enter the call combiner.
2425 if (grpc_client_channel_trace.enabled()) {
2426 gpr_log(GPR_DEBUG,
2427 "chand=%p calld=%p: starting %" PRIuPTR
2428 " retriable batches on subchannel_call=%p",
2429 chand, calld, num_batches, calld->subchannel_call);
2430 }
2431 if (num_batches == 0) {
2432 // This should be fairly rare, but it can happen when (e.g.) an
2433 // attempt completes before it has finished replaying all
2434 // previously sent messages.
2435 GRPC_CALL_COMBINER_STOP(calld->call_combiner,
2436 "no retriable subchannel batches to start");
2437 } else {
2438 for (size_t i = 1; i < num_batches; ++i) {
2439 if (grpc_client_channel_trace.enabled()) {
2440 char* batch_str = grpc_transport_stream_op_batch_string(batches[i]);
2441 gpr_log(GPR_DEBUG,
2442 "chand=%p calld=%p: starting batch in call combiner: %s", chand,
2443 calld, batch_str);
2444 gpr_free(batch_str);
2445 }
2446 batches[i]->handler_private.extra_arg = calld->subchannel_call;
2447 GRPC_CLOSURE_INIT(&batches[i]->handler_private.closure,
2448 start_batch_in_call_combiner, batches[i],
2449 grpc_schedule_on_exec_ctx);
2450 GRPC_CALL_COMBINER_START(calld->call_combiner,
2451 &batches[i]->handler_private.closure,
2452 GRPC_ERROR_NONE, "start_subchannel_batch");
2453 }
2454 if (grpc_client_channel_trace.enabled()) {
2455 char* batch_str = grpc_transport_stream_op_batch_string(batches[0]);
2456 gpr_log(GPR_DEBUG, "chand=%p calld=%p: starting batch: %s", chand, calld,
2457 batch_str);
2458 gpr_free(batch_str);
2459 }
2460 // Note: This will release the call combiner.
2461 grpc_subchannel_call_process_op(calld->subchannel_call, batches[0]);
2462 }
2463}
2464
2465//
2466// LB pick
2467//
2468
2469static void create_subchannel_call(grpc_call_element* elem, grpc_error* error) {
2470 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2471 call_data* calld = static_cast<call_data*>(elem->call_data);
2472 const size_t parent_data_size =
2473 calld->enable_retries ? sizeof(subchannel_call_retry_state) : 0;
David Garcia Quintasbaf1ac72018-01-09 14:24:32 -08002474 const grpc_core::ConnectedSubchannel::CallArgs call_args = {
Mark D. Rothc0febd32018-01-09 10:25:24 -08002475 calld->pollent, // pollent
2476 calld->path, // path
2477 calld->call_start_time, // start_time
2478 calld->deadline, // deadline
2479 calld->arena, // arena
2480 calld->pick.subchannel_call_context, // context
Mark D. Roth718c8342018-02-28 13:00:04 -08002481 calld->call_combiner, // call_combiner
2482 parent_data_size // parent_data_size
Yash Tibrewald8b84a22017-09-25 13:38:03 -07002483 };
David Garcia Quintas70fbe622018-01-09 19:27:46 -08002484 grpc_error* new_error = calld->pick.connected_subchannel->CreateCall(
David Garcia Quintasbaf1ac72018-01-09 14:24:32 -08002485 call_args, &calld->subchannel_call);
Craig Tiller6014e8a2017-10-16 13:50:29 -07002486 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth60751fe2017-07-07 12:50:33 -07002487 gpr_log(GPR_DEBUG, "chand=%p calld=%p: create subchannel_call=%p: error=%s",
Mark D. Roth76e264b2017-08-25 09:03:33 -07002488 chand, calld, calld->subchannel_call, grpc_error_string(new_error));
Mark D. Roth60751fe2017-07-07 12:50:33 -07002489 }
Mark D. Roth0ca0be82017-06-20 07:49:33 -07002490 if (new_error != GRPC_ERROR_NONE) {
2491 new_error = grpc_error_add_child(new_error, error);
Mark D. Roth718c8342018-02-28 13:00:04 -08002492 pending_batches_fail(elem, new_error, true /* yield_call_combiner */);
Mark D. Roth0ca0be82017-06-20 07:49:33 -07002493 } else {
Mark D. Roth718c8342018-02-28 13:00:04 -08002494 if (parent_data_size > 0) {
2495 subchannel_call_retry_state* retry_state =
2496 static_cast<subchannel_call_retry_state*>(
2497 grpc_connected_subchannel_call_get_parent_data(
2498 calld->subchannel_call));
2499 retry_state->batch_payload.context = calld->pick.subchannel_call_context;
2500 }
2501 pending_batches_resume(elem);
Craig Tiller11c17d42017-03-13 13:36:34 -07002502 }
Mark D. Roth0ca0be82017-06-20 07:49:33 -07002503 GRPC_ERROR_UNREF(error);
Craig Tiller11c17d42017-03-13 13:36:34 -07002504}
2505
Mark D. Rothb2929602017-09-11 09:31:11 -07002506// Invoked when a pick is completed, on both success or failure.
Mark D. Roth718c8342018-02-28 13:00:04 -08002507static void pick_done(void* arg, grpc_error* error) {
2508 grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
Noah Eisenbe82e642018-02-09 09:16:55 -08002509 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Mark D. Roth718c8342018-02-28 13:00:04 -08002510 call_data* calld = static_cast<call_data*>(elem->call_data);
David Garcia Quintasbe1b7f92018-01-12 14:01:38 -08002511 if (calld->pick.connected_subchannel == nullptr) {
Mark D. Roth0ca0be82017-06-20 07:49:33 -07002512 // Failed to create subchannel.
Mark D. Roth718c8342018-02-28 13:00:04 -08002513 // If there was no error, this is an LB policy drop, in which case
2514 // we return an error; otherwise, we may retry.
2515 grpc_status_code status = GRPC_STATUS_OK;
2516 grpc_error_get_status(error, calld->deadline, &status, nullptr, nullptr,
2517 nullptr);
2518 if (error == GRPC_ERROR_NONE || !calld->enable_retries ||
2519 !maybe_retry(elem, nullptr /* batch_data */, status,
2520 nullptr /* server_pushback_md */)) {
2521 grpc_error* new_error =
2522 error == GRPC_ERROR_NONE
2523 ? GRPC_ERROR_CREATE_FROM_STATIC_STRING(
2524 "Call dropped by load balancing policy")
2525 : GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
2526 "Failed to create subchannel", &error, 1);
2527 if (grpc_client_channel_trace.enabled()) {
2528 gpr_log(GPR_DEBUG,
2529 "chand=%p calld=%p: failed to create subchannel: error=%s",
2530 chand, calld, grpc_error_string(new_error));
2531 }
2532 pending_batches_fail(elem, new_error, true /* yield_call_combiner */);
Mark D. Roth60751fe2017-07-07 12:50:33 -07002533 }
Mark D. Roth2a5959f2016-09-01 08:20:27 -07002534 } else {
Mark D. Roth9fe284e2016-09-12 11:22:27 -07002535 /* Create call on subchannel. */
Mark D. Roth718c8342018-02-28 13:00:04 -08002536 create_subchannel_call(elem, GRPC_ERROR_REF(error));
Mark D. Roth2a5959f2016-09-01 08:20:27 -07002537 }
Mark D. Roth718c8342018-02-28 13:00:04 -08002538}
2539
2540// Invoked when a pick is completed to leave the client_channel combiner
2541// and continue processing in the call combiner.
2542static void pick_done_locked(grpc_call_element* elem, grpc_error* error) {
2543 call_data* calld = static_cast<call_data*>(elem->call_data);
2544 GRPC_CLOSURE_INIT(&calld->pick_closure, pick_done, elem,
2545 grpc_schedule_on_exec_ctx);
2546 GRPC_CLOSURE_SCHED(&calld->pick_closure, error);
Mark D. Roth2a5959f2016-09-01 08:20:27 -07002547}
2548
Mark D. Rothb2929602017-09-11 09:31:11 -07002549// A wrapper around pick_done_locked() that is used in cases where
2550// either (a) the pick was deferred pending a resolver result or (b) the
2551// pick was done asynchronously. Removes the call's polling entity from
2552// chand->interested_parties before invoking pick_done_locked().
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002553static void async_pick_done_locked(grpc_call_element* elem, grpc_error* error) {
Noah Eisenbe82e642018-02-09 09:16:55 -08002554 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2555 call_data* calld = static_cast<call_data*>(elem->call_data);
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002556 grpc_polling_entity_del_from_pollset_set(calld->pollent,
Mark D. Rothb2929602017-09-11 09:31:11 -07002557 chand->interested_parties);
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002558 pick_done_locked(elem, error);
Mark D. Rothb2929602017-09-11 09:31:11 -07002559}
2560
2561// Note: This runs under the client_channel combiner, but will NOT be
2562// holding the call combiner.
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002563static void pick_callback_cancel_locked(void* arg, grpc_error* error) {
Noah Eisenbe82e642018-02-09 09:16:55 -08002564 grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
2565 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2566 call_data* calld = static_cast<call_data*>(elem->call_data);
Mark D. Rothc0febd32018-01-09 10:25:24 -08002567 // Note: chand->lb_policy may have changed since we started our pick,
2568 // in which case we will be cancelling the pick on a policy other than
2569 // the one we started it on. However, this will just be a no-op.
2570 if (error != GRPC_ERROR_NONE && chand->lb_policy != nullptr) {
Craig Tiller6014e8a2017-10-16 13:50:29 -07002571 if (grpc_client_channel_trace.enabled()) {
Mark D. Rothb2929602017-09-11 09:31:11 -07002572 gpr_log(GPR_DEBUG, "chand=%p calld=%p: cancelling pick from LB policy %p",
Mark D. Rothc8875492018-02-20 08:33:48 -08002573 chand, calld, chand->lb_policy.get());
Mark D. Rothb2929602017-09-11 09:31:11 -07002574 }
Mark D. Rothc8875492018-02-20 08:33:48 -08002575 chand->lb_policy->CancelPickLocked(&calld->pick, GRPC_ERROR_REF(error));
Mark D. Rothb2929602017-09-11 09:31:11 -07002576 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002577 GRPC_CALL_STACK_UNREF(calld->owning_call, "pick_callback_cancel");
Mark D. Rothb2929602017-09-11 09:31:11 -07002578}
2579
Mark D. Rothc8875492018-02-20 08:33:48 -08002580// Callback invoked by LoadBalancingPolicy::PickLocked() for async picks.
Mark D. Rothb2929602017-09-11 09:31:11 -07002581// Unrefs the LB policy and invokes async_pick_done_locked().
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002582static void pick_callback_done_locked(void* arg, grpc_error* error) {
Noah Eisenbe82e642018-02-09 09:16:55 -08002583 grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
2584 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2585 call_data* calld = static_cast<call_data*>(elem->call_data);
Craig Tiller6014e8a2017-10-16 13:50:29 -07002586 if (grpc_client_channel_trace.enabled()) {
Mark D. Rothb2929602017-09-11 09:31:11 -07002587 gpr_log(GPR_DEBUG, "chand=%p calld=%p: pick completed asynchronously",
2588 chand, calld);
2589 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002590 async_pick_done_locked(elem, GRPC_ERROR_REF(error));
Ken Paysonf069dd42018-02-05 09:15:05 -08002591 GRPC_CALL_STACK_UNREF(calld->owning_call, "pick_callback");
Mark D. Rothb2929602017-09-11 09:31:11 -07002592}
2593
Mark D. Roth718c8342018-02-28 13:00:04 -08002594// Applies service config to the call. Must be invoked once we know
2595// that the resolver has returned results to the channel.
2596static void apply_service_config_to_call_locked(grpc_call_element* elem) {
2597 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2598 call_data* calld = static_cast<call_data*>(elem->call_data);
2599 if (grpc_client_channel_trace.enabled()) {
2600 gpr_log(GPR_DEBUG, "chand=%p calld=%p: applying service config to call",
2601 chand, calld);
2602 }
2603 if (chand->retry_throttle_data != nullptr) {
2604 calld->retry_throttle_data =
2605 grpc_server_retry_throttle_data_ref(chand->retry_throttle_data);
2606 }
2607 if (chand->method_params_table != nullptr) {
2608 calld->method_params = grpc_core::ServiceConfig::MethodConfigTableLookup(
2609 *chand->method_params_table, calld->path);
2610 if (calld->method_params != nullptr) {
2611 // If the deadline from the service config is shorter than the one
2612 // from the client API, reset the deadline timer.
2613 if (chand->deadline_checking_enabled &&
2614 calld->method_params->timeout() != 0) {
2615 const grpc_millis per_method_deadline =
2616 grpc_timespec_to_millis_round_up(calld->call_start_time) +
2617 calld->method_params->timeout();
2618 if (per_method_deadline < calld->deadline) {
2619 calld->deadline = per_method_deadline;
2620 grpc_deadline_state_reset(elem, calld->deadline);
2621 }
2622 }
2623 }
2624 }
2625 // If no retry policy, disable retries.
2626 // TODO(roth): Remove this when adding support for transparent retries.
2627 if (calld->method_params == nullptr ||
2628 calld->method_params->retry_policy() == nullptr) {
2629 calld->enable_retries = false;
2630 }
2631}
2632
Mark D. Rothc8875492018-02-20 08:33:48 -08002633// Starts a pick on chand->lb_policy.
2634// Returns true if pick is completed synchronously.
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002635static bool pick_callback_start_locked(grpc_call_element* elem) {
Noah Eisenbe82e642018-02-09 09:16:55 -08002636 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2637 call_data* calld = static_cast<call_data*>(elem->call_data);
Craig Tiller6014e8a2017-10-16 13:50:29 -07002638 if (grpc_client_channel_trace.enabled()) {
Mark D. Rothb2929602017-09-11 09:31:11 -07002639 gpr_log(GPR_DEBUG, "chand=%p calld=%p: starting pick on lb_policy=%p",
Mark D. Rothc8875492018-02-20 08:33:48 -08002640 chand, calld, chand->lb_policy.get());
Mark D. Rothb2929602017-09-11 09:31:11 -07002641 }
Mark D. Roth718c8342018-02-28 13:00:04 -08002642 // Only get service config data on the first attempt.
2643 if (calld->num_attempts_completed == 0) {
2644 apply_service_config_to_call_locked(elem);
2645 }
Mark D. Rothb2929602017-09-11 09:31:11 -07002646 // If the application explicitly set wait_for_ready, use that.
2647 // Otherwise, if the service config specified a value for this
2648 // method, use that.
Mark D. Roth718c8342018-02-28 13:00:04 -08002649 //
2650 // The send_initial_metadata batch will be the first one in the list,
2651 // as set by get_batch_index() above.
2652 calld->pick.initial_metadata =
2653 calld->seen_send_initial_metadata
2654 ? &calld->send_initial_metadata
2655 : calld->pending_batches[0]
2656 .batch->payload->send_initial_metadata.send_initial_metadata;
2657 uint32_t send_initial_metadata_flags =
2658 calld->seen_send_initial_metadata
2659 ? calld->send_initial_metadata_flags
2660 : calld->pending_batches[0]
2661 .batch->payload->send_initial_metadata
2662 .send_initial_metadata_flags;
Mark D. Rothb2929602017-09-11 09:31:11 -07002663 const bool wait_for_ready_set_from_api =
Mark D. Roth718c8342018-02-28 13:00:04 -08002664 send_initial_metadata_flags &
Mark D. Rothb2929602017-09-11 09:31:11 -07002665 GRPC_INITIAL_METADATA_WAIT_FOR_READY_EXPLICITLY_SET;
2666 const bool wait_for_ready_set_from_service_config =
Craig Tiller4782d922017-11-10 09:53:21 -08002667 calld->method_params != nullptr &&
Mark D. Roth3e7f2df2018-02-26 13:17:06 -08002668 calld->method_params->wait_for_ready() !=
2669 ClientChannelMethodParams::WAIT_FOR_READY_UNSET;
Mark D. Rothb2929602017-09-11 09:31:11 -07002670 if (!wait_for_ready_set_from_api && wait_for_ready_set_from_service_config) {
Mark D. Roth3e7f2df2018-02-26 13:17:06 -08002671 if (calld->method_params->wait_for_ready() ==
2672 ClientChannelMethodParams::WAIT_FOR_READY_TRUE) {
Mark D. Roth718c8342018-02-28 13:00:04 -08002673 send_initial_metadata_flags |= GRPC_INITIAL_METADATA_WAIT_FOR_READY;
Mark D. Rothb2929602017-09-11 09:31:11 -07002674 } else {
Mark D. Roth718c8342018-02-28 13:00:04 -08002675 send_initial_metadata_flags &= ~GRPC_INITIAL_METADATA_WAIT_FOR_READY;
Mark D. Rothb2929602017-09-11 09:31:11 -07002676 }
2677 }
Mark D. Roth718c8342018-02-28 13:00:04 -08002678 calld->pick.initial_metadata_flags = send_initial_metadata_flags;
2679 GRPC_CLOSURE_INIT(&calld->pick_closure, pick_callback_done_locked, elem,
Mark D. Rothb2929602017-09-11 09:31:11 -07002680 grpc_combiner_scheduler(chand->combiner));
Mark D. Roth718c8342018-02-28 13:00:04 -08002681 calld->pick.on_complete = &calld->pick_closure;
Ken Paysonf069dd42018-02-05 09:15:05 -08002682 GRPC_CALL_STACK_REF(calld->owning_call, "pick_callback");
Mark D. Rothc8875492018-02-20 08:33:48 -08002683 const bool pick_done = chand->lb_policy->PickLocked(&calld->pick);
Mark D. Rothb2929602017-09-11 09:31:11 -07002684 if (pick_done) {
Mark D. Rothc8875492018-02-20 08:33:48 -08002685 // Pick completed synchronously.
Craig Tiller6014e8a2017-10-16 13:50:29 -07002686 if (grpc_client_channel_trace.enabled()) {
Mark D. Rothb2929602017-09-11 09:31:11 -07002687 gpr_log(GPR_DEBUG, "chand=%p calld=%p: pick completed synchronously",
2688 chand, calld);
2689 }
Ken Paysonf069dd42018-02-05 09:15:05 -08002690 GRPC_CALL_STACK_UNREF(calld->owning_call, "pick_callback");
Mark D. Rothb2929602017-09-11 09:31:11 -07002691 } else {
2692 GRPC_CALL_STACK_REF(calld->owning_call, "pick_callback_cancel");
2693 grpc_call_combiner_set_notify_on_cancel(
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002694 calld->call_combiner,
Mark D. Roth718c8342018-02-28 13:00:04 -08002695 GRPC_CLOSURE_INIT(&calld->pick_cancel_closure,
Mark D. Rothb2929602017-09-11 09:31:11 -07002696 pick_callback_cancel_locked, elem,
2697 grpc_combiner_scheduler(chand->combiner)));
2698 }
2699 return pick_done;
2700}
Mark D. Roth0ca0be82017-06-20 07:49:33 -07002701
Craig Tiller577c9b22015-11-02 14:11:15 -08002702typedef struct {
Craig Tillerbaa14a92017-11-03 09:09:36 -07002703 grpc_call_element* elem;
Mark D. Roth66f3d2b2017-09-01 09:02:17 -07002704 bool finished;
Craig Tiller577c9b22015-11-02 14:11:15 -08002705 grpc_closure closure;
Mark D. Roth66f3d2b2017-09-01 09:02:17 -07002706 grpc_closure cancel_closure;
Mark D. Roth0ca0be82017-06-20 07:49:33 -07002707} pick_after_resolver_result_args;
Craig Tiller577c9b22015-11-02 14:11:15 -08002708
Mark D. Roth76e264b2017-08-25 09:03:33 -07002709// Note: This runs under the client_channel combiner, but will NOT be
2710// holding the call combiner.
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002711static void pick_after_resolver_result_cancel_locked(void* arg,
Craig Tillerbaa14a92017-11-03 09:09:36 -07002712 grpc_error* error) {
Noah Eisen4d20a662018-02-09 09:34:04 -08002713 pick_after_resolver_result_args* args =
2714 static_cast<pick_after_resolver_result_args*>(arg);
Mark D. Roth66f3d2b2017-09-01 09:02:17 -07002715 if (args->finished) {
2716 gpr_free(args);
Mark D. Rothb2b9a0f2017-09-01 09:06:47 -07002717 return;
Mark D. Roth764cf042017-09-01 09:00:06 -07002718 }
Mark D. Roth76e264b2017-08-25 09:03:33 -07002719 // If we don't yet have a resolver result, then a closure for
2720 // pick_after_resolver_result_done_locked() will have been added to
2721 // chand->waiting_for_resolver_result_closures, and it may not be invoked
2722 // until after this call has been destroyed. We mark the operation as
Mark D. Rothb2b9a0f2017-09-01 09:06:47 -07002723 // finished, so that when pick_after_resolver_result_done_locked()
Mark D. Roth76e264b2017-08-25 09:03:33 -07002724 // is called, it will be a no-op. We also immediately invoke
Mark D. Rothb2929602017-09-11 09:31:11 -07002725 // async_pick_done_locked() to propagate the error back to the caller.
2726 args->finished = true;
Craig Tillerbaa14a92017-11-03 09:09:36 -07002727 grpc_call_element* elem = args->elem;
Noah Eisenbe82e642018-02-09 09:16:55 -08002728 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2729 call_data* calld = static_cast<call_data*>(elem->call_data);
Craig Tiller6014e8a2017-10-16 13:50:29 -07002730 if (grpc_client_channel_trace.enabled()) {
Mark D. Rothb2b9a0f2017-09-01 09:06:47 -07002731 gpr_log(GPR_DEBUG,
2732 "chand=%p calld=%p: cancelling pick waiting for resolver result",
2733 chand, calld);
Mark D. Roth76e264b2017-08-25 09:03:33 -07002734 }
Mark D. Rothb2b9a0f2017-09-01 09:06:47 -07002735 // Note: Although we are not in the call combiner here, we are
2736 // basically stealing the call combiner from the pending pick, so
Mark D. Rothb2929602017-09-11 09:31:11 -07002737 // it's safe to call async_pick_done_locked() here -- we are
Mark D. Rothb2b9a0f2017-09-01 09:06:47 -07002738 // essentially calling it here instead of calling it in
2739 // pick_after_resolver_result_done_locked().
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002740 async_pick_done_locked(elem, GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
2741 "Pick cancelled", &error, 1));
Mark D. Roth76e264b2017-08-25 09:03:33 -07002742}
2743
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002744static void pick_after_resolver_result_done_locked(void* arg,
Craig Tillerbaa14a92017-11-03 09:09:36 -07002745 grpc_error* error) {
Noah Eisen4d20a662018-02-09 09:34:04 -08002746 pick_after_resolver_result_args* args =
2747 static_cast<pick_after_resolver_result_args*>(arg);
Mark D. Roth66f3d2b2017-09-01 09:02:17 -07002748 if (args->finished) {
Craig Tiller577c9b22015-11-02 14:11:15 -08002749 /* cancelled, do nothing */
Craig Tiller6014e8a2017-10-16 13:50:29 -07002750 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth60751fe2017-07-07 12:50:33 -07002751 gpr_log(GPR_DEBUG, "call cancelled before resolver result");
2752 }
Mark D. Roth66f3d2b2017-09-01 09:02:17 -07002753 gpr_free(args);
Mark D. Rothb2b9a0f2017-09-01 09:06:47 -07002754 return;
2755 }
2756 args->finished = true;
Craig Tillerbaa14a92017-11-03 09:09:36 -07002757 grpc_call_element* elem = args->elem;
Noah Eisenbe82e642018-02-09 09:16:55 -08002758 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2759 call_data* calld = static_cast<call_data*>(elem->call_data);
Mark D. Rothb2b9a0f2017-09-01 09:06:47 -07002760 if (error != GRPC_ERROR_NONE) {
Craig Tiller6014e8a2017-10-16 13:50:29 -07002761 if (grpc_client_channel_trace.enabled()) {
Mark D. Rothb2b9a0f2017-09-01 09:06:47 -07002762 gpr_log(GPR_DEBUG, "chand=%p calld=%p: resolver failed to return data",
2763 chand, calld);
2764 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002765 async_pick_done_locked(elem, GRPC_ERROR_REF(error));
Mark D. Rothe63e06d2018-03-23 08:12:11 -07002766 } else if (chand->resolver == nullptr) {
2767 // Shutting down.
2768 if (grpc_client_channel_trace.enabled()) {
2769 gpr_log(GPR_DEBUG, "chand=%p calld=%p: resolver disconnected", chand,
2770 calld);
2771 }
2772 async_pick_done_locked(
2773 elem, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Disconnected"));
2774 } else if (chand->lb_policy == nullptr) {
2775 // Transient resolver failure.
2776 // If call has wait_for_ready=true, try again; otherwise, fail.
2777 uint32_t send_initial_metadata_flags =
2778 calld->seen_send_initial_metadata
2779 ? calld->send_initial_metadata_flags
2780 : calld->pending_batches[0]
2781 .batch->payload->send_initial_metadata
2782 .send_initial_metadata_flags;
2783 if (send_initial_metadata_flags & GRPC_INITIAL_METADATA_WAIT_FOR_READY) {
2784 if (grpc_client_channel_trace.enabled()) {
2785 gpr_log(GPR_DEBUG,
2786 "chand=%p calld=%p: resolver returned but no LB policy; "
2787 "wait_for_ready=true; trying again",
2788 chand, calld);
2789 }
2790 pick_after_resolver_result_start_locked(elem);
2791 } else {
2792 if (grpc_client_channel_trace.enabled()) {
2793 gpr_log(GPR_DEBUG,
2794 "chand=%p calld=%p: resolver returned but no LB policy; "
2795 "wait_for_ready=false; failing",
2796 chand, calld);
2797 }
2798 async_pick_done_locked(
2799 elem,
2800 grpc_error_set_int(
2801 GRPC_ERROR_CREATE_FROM_STATIC_STRING("Name resolution failure"),
2802 GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE));
2803 }
2804 } else {
Craig Tiller6014e8a2017-10-16 13:50:29 -07002805 if (grpc_client_channel_trace.enabled()) {
Mark D. Rothb2b9a0f2017-09-01 09:06:47 -07002806 gpr_log(GPR_DEBUG, "chand=%p calld=%p: resolver returned, doing pick",
2807 chand, calld);
2808 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002809 if (pick_callback_start_locked(elem)) {
Mark D. Rothb2929602017-09-11 09:31:11 -07002810 // Even if the LB policy returns a result synchronously, we have
2811 // already added our polling entity to chand->interested_parties
2812 // in order to wait for the resolver result, so we need to
2813 // remove it here. Therefore, we call async_pick_done_locked()
2814 // instead of pick_done_locked().
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002815 async_pick_done_locked(elem, GRPC_ERROR_NONE);
Mark D. Roth9dab7d52016-10-07 07:48:03 -07002816 }
Craig Tiller577c9b22015-11-02 14:11:15 -08002817 }
Craig Tiller577c9b22015-11-02 14:11:15 -08002818}
2819
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002820static void pick_after_resolver_result_start_locked(grpc_call_element* elem) {
Noah Eisenbe82e642018-02-09 09:16:55 -08002821 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2822 call_data* calld = static_cast<call_data*>(elem->call_data);
Craig Tiller6014e8a2017-10-16 13:50:29 -07002823 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth60751fe2017-07-07 12:50:33 -07002824 gpr_log(GPR_DEBUG,
2825 "chand=%p calld=%p: deferring pick pending resolver result", chand,
2826 calld);
Mark D. Roth64a317c2017-05-02 08:27:08 -07002827 }
Craig Tillerbaa14a92017-11-03 09:09:36 -07002828 pick_after_resolver_result_args* args =
Noah Eisenbe82e642018-02-09 09:16:55 -08002829 static_cast<pick_after_resolver_result_args*>(gpr_zalloc(sizeof(*args)));
Mark D. Roth60751fe2017-07-07 12:50:33 -07002830 args->elem = elem;
2831 GRPC_CLOSURE_INIT(&args->closure, pick_after_resolver_result_done_locked,
2832 args, grpc_combiner_scheduler(chand->combiner));
2833 grpc_closure_list_append(&chand->waiting_for_resolver_result_closures,
2834 &args->closure, GRPC_ERROR_NONE);
Mark D. Roth76e264b2017-08-25 09:03:33 -07002835 grpc_call_combiner_set_notify_on_cancel(
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002836 calld->call_combiner,
Mark D. Roth66f3d2b2017-09-01 09:02:17 -07002837 GRPC_CLOSURE_INIT(&args->cancel_closure,
2838 pick_after_resolver_result_cancel_locked, args,
Mark D. Roth76e264b2017-08-25 09:03:33 -07002839 grpc_combiner_scheduler(chand->combiner)));
Mark D. Roth60751fe2017-07-07 12:50:33 -07002840}
2841
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002842static void start_pick_locked(void* arg, grpc_error* ignored) {
Noah Eisenbe82e642018-02-09 09:16:55 -08002843 grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
2844 call_data* calld = static_cast<call_data*>(elem->call_data);
2845 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
David Garcia Quintasbe1b7f92018-01-12 14:01:38 -08002846 GPR_ASSERT(calld->pick.connected_subchannel == nullptr);
Mark D. Roth718c8342018-02-28 13:00:04 -08002847 GPR_ASSERT(calld->subchannel_call == nullptr);
Craig Tiller4782d922017-11-10 09:53:21 -08002848 if (chand->lb_policy != nullptr) {
Mark D. Rothb2929602017-09-11 09:31:11 -07002849 // We already have an LB policy, so ask it for a pick.
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002850 if (pick_callback_start_locked(elem)) {
Mark D. Rothb2929602017-09-11 09:31:11 -07002851 // Pick completed synchronously.
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002852 pick_done_locked(elem, GRPC_ERROR_NONE);
Mark D. Rothb2929602017-09-11 09:31:11 -07002853 return;
Mark D. Roth2a5959f2016-09-01 08:20:27 -07002854 }
Mark D. Roth76e264b2017-08-25 09:03:33 -07002855 } else {
Mark D. Rothb2929602017-09-11 09:31:11 -07002856 // We do not yet have an LB policy, so wait for a resolver result.
Craig Tiller4782d922017-11-10 09:53:21 -08002857 if (chand->resolver == nullptr) {
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002858 pick_done_locked(elem,
Mark D. Rothb2929602017-09-11 09:31:11 -07002859 GRPC_ERROR_CREATE_FROM_STATIC_STRING("Disconnected"));
2860 return;
2861 }
2862 if (!chand->started_resolving) {
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002863 start_resolving_locked(chand);
Mark D. Rothb2929602017-09-11 09:31:11 -07002864 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002865 pick_after_resolver_result_start_locked(elem);
Mark D. Roth2a5959f2016-09-01 08:20:27 -07002866 }
Mark D. Rothb2929602017-09-11 09:31:11 -07002867 // We need to wait for either a resolver result or for an async result
2868 // from the LB policy. Add the polling entity from call_data to the
2869 // channel_data's interested_parties, so that the I/O of the LB policy
2870 // and resolver can be done under it. The polling entity will be
2871 // removed in async_pick_done_locked().
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002872 grpc_polling_entity_add_to_pollset_set(calld->pollent,
Mark D. Rothb2929602017-09-11 09:31:11 -07002873 chand->interested_parties);
Craig Tillera11bfc82017-02-14 09:56:33 -08002874}
2875
Mark D. Roth718c8342018-02-28 13:00:04 -08002876//
2877// filter call vtable functions
2878//
Mark D. Rothd6d192d2017-02-23 08:58:42 -08002879
Craig Tillere1b51da2017-03-31 15:44:33 -07002880static void cc_start_transport_stream_op_batch(
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002881 grpc_call_element* elem, grpc_transport_stream_op_batch* batch) {
yang-gce1cfea2018-01-31 15:59:50 -08002882 GPR_TIMER_SCOPE("cc_start_transport_stream_op_batch", 0);
Noah Eisenbe82e642018-02-09 09:16:55 -08002883 call_data* calld = static_cast<call_data*>(elem->call_data);
2884 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Craig Tiller3be7dd02017-04-03 14:30:03 -07002885 if (chand->deadline_checking_enabled) {
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002886 grpc_deadline_state_client_start_transport_stream_op_batch(elem, batch);
Craig Tiller3be7dd02017-04-03 14:30:03 -07002887 }
Mark D. Roth76e264b2017-08-25 09:03:33 -07002888 // If we've previously been cancelled, immediately fail any new batches.
Mark D. Roth718c8342018-02-28 13:00:04 -08002889 if (calld->cancel_error != GRPC_ERROR_NONE) {
Craig Tiller6014e8a2017-10-16 13:50:29 -07002890 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth76e264b2017-08-25 09:03:33 -07002891 gpr_log(GPR_DEBUG, "chand=%p calld=%p: failing batch with error: %s",
Mark D. Roth718c8342018-02-28 13:00:04 -08002892 chand, calld, grpc_error_string(calld->cancel_error));
Mark D. Roth76e264b2017-08-25 09:03:33 -07002893 }
Mark D. Roth718c8342018-02-28 13:00:04 -08002894 // Note: This will release the call combiner.
Mark D. Roth76e264b2017-08-25 09:03:33 -07002895 grpc_transport_stream_op_batch_finish_with_failure(
Mark D. Roth718c8342018-02-28 13:00:04 -08002896 batch, GRPC_ERROR_REF(calld->cancel_error), calld->call_combiner);
yang-gce1cfea2018-01-31 15:59:50 -08002897 return;
Mark D. Roth76e264b2017-08-25 09:03:33 -07002898 }
Mark D. Roth718c8342018-02-28 13:00:04 -08002899 // Handle cancellation.
Mark D. Roth76e264b2017-08-25 09:03:33 -07002900 if (batch->cancel_stream) {
2901 // Stash a copy of cancel_error in our call data, so that we can use
2902 // it for subsequent operations. This ensures that if the call is
2903 // cancelled before any batches are passed down (e.g., if the deadline
2904 // is in the past when the call starts), we can return the right
2905 // error to the caller when the first batch does get passed down.
Mark D. Roth718c8342018-02-28 13:00:04 -08002906 GRPC_ERROR_UNREF(calld->cancel_error);
2907 calld->cancel_error =
2908 GRPC_ERROR_REF(batch->payload->cancel_stream.cancel_error);
Craig Tiller6014e8a2017-10-16 13:50:29 -07002909 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth76e264b2017-08-25 09:03:33 -07002910 gpr_log(GPR_DEBUG, "chand=%p calld=%p: recording cancel_error=%s", chand,
Mark D. Roth718c8342018-02-28 13:00:04 -08002911 calld, grpc_error_string(calld->cancel_error));
Mark D. Roth76e264b2017-08-25 09:03:33 -07002912 }
Mark D. Roth718c8342018-02-28 13:00:04 -08002913 // If we do not have a subchannel call (i.e., a pick has not yet
2914 // been started), fail all pending batches. Otherwise, send the
2915 // cancellation down to the subchannel call.
2916 if (calld->subchannel_call == nullptr) {
2917 pending_batches_fail(elem, GRPC_ERROR_REF(calld->cancel_error),
2918 false /* yield_call_combiner */);
2919 // Note: This will release the call combiner.
2920 grpc_transport_stream_op_batch_finish_with_failure(
2921 batch, GRPC_ERROR_REF(calld->cancel_error), calld->call_combiner);
Mark D. Roth76e264b2017-08-25 09:03:33 -07002922 } else {
Mark D. Roth718c8342018-02-28 13:00:04 -08002923 // Note: This will release the call combiner.
2924 grpc_subchannel_call_process_op(calld->subchannel_call, batch);
Mark D. Roth76e264b2017-08-25 09:03:33 -07002925 }
yang-gce1cfea2018-01-31 15:59:50 -08002926 return;
Mark D. Roth76e264b2017-08-25 09:03:33 -07002927 }
Mark D. Roth718c8342018-02-28 13:00:04 -08002928 // Add the batch to the pending list.
2929 pending_batches_add(elem, batch);
Mark D. Roth76e264b2017-08-25 09:03:33 -07002930 // Check if we've already gotten a subchannel call.
2931 // Note that once we have completed the pick, we do not need to enter
2932 // the channel combiner, which is more efficient (especially for
2933 // streaming calls).
Craig Tiller4782d922017-11-10 09:53:21 -08002934 if (calld->subchannel_call != nullptr) {
Craig Tiller6014e8a2017-10-16 13:50:29 -07002935 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth60751fe2017-07-07 12:50:33 -07002936 gpr_log(GPR_DEBUG,
Mark D. Roth718c8342018-02-28 13:00:04 -08002937 "chand=%p calld=%p: starting batch on subchannel_call=%p", chand,
Mark D. Roth76e264b2017-08-25 09:03:33 -07002938 calld, calld->subchannel_call);
Mark D. Roth60751fe2017-07-07 12:50:33 -07002939 }
Mark D. Roth718c8342018-02-28 13:00:04 -08002940 pending_batches_resume(elem);
yang-gce1cfea2018-01-31 15:59:50 -08002941 return;
Mark D. Roth2a5959f2016-09-01 08:20:27 -07002942 }
Mark D. Roth76e264b2017-08-25 09:03:33 -07002943 // We do not yet have a subchannel call.
Mark D. Roth76e264b2017-08-25 09:03:33 -07002944 // For batches containing a send_initial_metadata op, enter the channel
2945 // combiner to start a pick.
2946 if (batch->send_initial_metadata) {
Craig Tiller6014e8a2017-10-16 13:50:29 -07002947 if (grpc_client_channel_trace.enabled()) {
Mark D. Rothb2929602017-09-11 09:31:11 -07002948 gpr_log(GPR_DEBUG, "chand=%p calld=%p: entering client_channel combiner",
2949 chand, calld);
Mark D. Roth76e264b2017-08-25 09:03:33 -07002950 }
2951 GRPC_CLOSURE_SCHED(
Mark D. Roth76e264b2017-08-25 09:03:33 -07002952 GRPC_CLOSURE_INIT(&batch->handler_private.closure, start_pick_locked,
2953 elem, grpc_combiner_scheduler(chand->combiner)),
2954 GRPC_ERROR_NONE);
2955 } else {
2956 // For all other batches, release the call combiner.
Craig Tiller6014e8a2017-10-16 13:50:29 -07002957 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth76e264b2017-08-25 09:03:33 -07002958 gpr_log(GPR_DEBUG,
2959 "chand=%p calld=%p: saved batch, yeilding call combiner", chand,
2960 calld);
2961 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002962 GRPC_CALL_COMBINER_STOP(calld->call_combiner,
Mark D. Roth76e264b2017-08-25 09:03:33 -07002963 "batch does not include send_initial_metadata");
Mark D. Roth60751fe2017-07-07 12:50:33 -07002964 }
Mark D. Roth2a5959f2016-09-01 08:20:27 -07002965}
2966
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -08002967/* Constructor for call_data */
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002968static grpc_error* cc_init_call_elem(grpc_call_element* elem,
Craig Tillerbaa14a92017-11-03 09:09:36 -07002969 const grpc_call_element_args* args) {
Noah Eisenbe82e642018-02-09 09:16:55 -08002970 call_data* calld = static_cast<call_data*>(elem->call_data);
2971 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Mark D. Rothe40dd292016-10-05 14:58:37 -07002972 // Initialize data members.
Craig Tiller7c70b6c2017-01-23 07:48:42 -08002973 calld->path = grpc_slice_ref_internal(args->path);
Mark D. Rothff08f332016-10-14 13:01:01 -07002974 calld->call_start_time = args->start_time;
Craig Tiller89c14282017-07-19 15:32:27 -07002975 calld->deadline = args->deadline;
Craig Tillerd426cac2017-03-13 12:30:45 -07002976 calld->arena = args->arena;
Mark D. Roth66f3d2b2017-09-01 09:02:17 -07002977 calld->owning_call = args->call_stack;
Mark D. Roth76e264b2017-08-25 09:03:33 -07002978 calld->call_combiner = args->call_combiner;
Craig Tiller3be7dd02017-04-03 14:30:03 -07002979 if (chand->deadline_checking_enabled) {
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002980 grpc_deadline_state_init(elem, args->call_stack, args->call_combiner,
2981 calld->deadline);
Craig Tiller3be7dd02017-04-03 14:30:03 -07002982 }
Mark D. Roth718c8342018-02-28 13:00:04 -08002983 calld->enable_retries = chand->enable_retries;
Mark D. Roth0badbe82016-06-23 10:15:12 -07002984 return GRPC_ERROR_NONE;
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -08002985}
2986
2987/* Destructor for call_data */
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002988static void cc_destroy_call_elem(grpc_call_element* elem,
Craig Tillerbaa14a92017-11-03 09:09:36 -07002989 const grpc_call_final_info* final_info,
2990 grpc_closure* then_schedule_closure) {
Noah Eisenbe82e642018-02-09 09:16:55 -08002991 call_data* calld = static_cast<call_data*>(elem->call_data);
2992 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Craig Tiller3be7dd02017-04-03 14:30:03 -07002993 if (chand->deadline_checking_enabled) {
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002994 grpc_deadline_state_destroy(elem);
Craig Tiller3be7dd02017-04-03 14:30:03 -07002995 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002996 grpc_slice_unref_internal(calld->path);
Mark D. Roth3e7f2df2018-02-26 13:17:06 -08002997 calld->method_params.reset();
Mark D. Roth718c8342018-02-28 13:00:04 -08002998 GRPC_ERROR_UNREF(calld->cancel_error);
Craig Tiller4782d922017-11-10 09:53:21 -08002999 if (calld->subchannel_call != nullptr) {
Mark D. Roth76e264b2017-08-25 09:03:33 -07003000 grpc_subchannel_call_set_cleanup_closure(calld->subchannel_call,
Craig Tillerf7c8c9f2017-05-17 15:22:05 -07003001 then_schedule_closure);
Craig Tiller4782d922017-11-10 09:53:21 -08003002 then_schedule_closure = nullptr;
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003003 GRPC_SUBCHANNEL_CALL_UNREF(calld->subchannel_call,
Craig Tillerf7c8c9f2017-05-17 15:22:05 -07003004 "client_channel_destroy_call");
Mark D. Roth4c0fe492016-08-31 13:51:55 -07003005 }
Mark D. Roth718c8342018-02-28 13:00:04 -08003006 for (size_t i = 0; i < GPR_ARRAY_SIZE(calld->pending_batches); ++i) {
3007 GPR_ASSERT(calld->pending_batches[i].batch == nullptr);
3008 }
David Garcia Quintasbe1b7f92018-01-12 14:01:38 -08003009 if (calld->pick.connected_subchannel != nullptr) {
David Garcia Quintasdfa28512018-01-11 18:31:13 -08003010 calld->pick.connected_subchannel.reset();
Craig Tiller693d3942016-10-27 16:51:25 -07003011 }
Mark D. Roth09e458c2017-05-02 08:13:26 -07003012 for (size_t i = 0; i < GRPC_CONTEXT_COUNT; ++i) {
Mark D. Rothc0febd32018-01-09 10:25:24 -08003013 if (calld->pick.subchannel_call_context[i].value != nullptr) {
3014 calld->pick.subchannel_call_context[i].destroy(
3015 calld->pick.subchannel_call_context[i].value);
Mark D. Roth09e458c2017-05-02 08:13:26 -07003016 }
3017 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003018 GRPC_CLOSURE_SCHED(then_schedule_closure, GRPC_ERROR_NONE);
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -08003019}
3020
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003021static void cc_set_pollset_or_pollset_set(grpc_call_element* elem,
Craig Tillerbaa14a92017-11-03 09:09:36 -07003022 grpc_polling_entity* pollent) {
Noah Eisenbe82e642018-02-09 09:16:55 -08003023 call_data* calld = static_cast<call_data*>(elem->call_data);
David Garcia Quintas2a50dfe2016-05-31 15:09:12 -07003024 calld->pollent = pollent;
Craig Tiller577c9b22015-11-02 14:11:15 -08003025}
3026
Mark D. Roth2a5959f2016-09-01 08:20:27 -07003027/*************************************************************************
3028 * EXPORTED SYMBOLS
3029 */
3030
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -08003031const grpc_channel_filter grpc_client_channel_filter = {
Craig Tillera0f3abd2017-03-31 15:42:16 -07003032 cc_start_transport_stream_op_batch,
Craig Tillerf40df232016-03-25 13:38:14 -07003033 cc_start_transport_op,
3034 sizeof(call_data),
Mark D. Roth2a5959f2016-09-01 08:20:27 -07003035 cc_init_call_elem,
David Garcia Quintas4afce7e2016-04-18 16:25:17 -07003036 cc_set_pollset_or_pollset_set,
Mark D. Roth2a5959f2016-09-01 08:20:27 -07003037 cc_destroy_call_elem,
Craig Tillerf40df232016-03-25 13:38:14 -07003038 sizeof(channel_data),
Mark D. Roth2a5959f2016-09-01 08:20:27 -07003039 cc_init_channel_elem,
3040 cc_destroy_channel_elem,
Mark D. Rothb2d24882016-10-27 15:44:07 -07003041 cc_get_channel_info,
Craig Tillerf40df232016-03-25 13:38:14 -07003042 "client-channel",
Craig Tiller87d5b192015-04-16 14:37:57 -07003043};
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -08003044
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003045static void try_to_connect_locked(void* arg, grpc_error* error_ignored) {
Noah Eisenbe82e642018-02-09 09:16:55 -08003046 channel_data* chand = static_cast<channel_data*>(arg);
Craig Tiller4782d922017-11-10 09:53:21 -08003047 if (chand->lb_policy != nullptr) {
Mark D. Rothc8875492018-02-20 08:33:48 -08003048 chand->lb_policy->ExitIdleLocked();
Craig Tiller613dafa2017-02-09 12:00:43 -08003049 } else {
3050 chand->exit_idle_when_lb_policy_arrives = true;
Craig Tiller4782d922017-11-10 09:53:21 -08003051 if (!chand->started_resolving && chand->resolver != nullptr) {
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003052 start_resolving_locked(chand);
Craig Tiller613dafa2017-02-09 12:00:43 -08003053 }
3054 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003055 GRPC_CHANNEL_STACK_UNREF(chand->owning_stack, "try_to_connect");
Craig Tiller613dafa2017-02-09 12:00:43 -08003056}
3057
Craig Tillera82950e2015-09-22 12:33:20 -07003058grpc_connectivity_state grpc_client_channel_check_connectivity_state(
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003059 grpc_channel_element* elem, int try_to_connect) {
Noah Eisenbe82e642018-02-09 09:16:55 -08003060 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Craig Tillera8610c02017-02-14 10:05:11 -08003061 grpc_connectivity_state out =
3062 grpc_connectivity_state_check(&chand->state_tracker);
Craig Tillera82950e2015-09-22 12:33:20 -07003063 if (out == GRPC_CHANNEL_IDLE && try_to_connect) {
Craig Tillerd2e5cfc2017-02-09 13:02:20 -08003064 GRPC_CHANNEL_STACK_REF(chand->owning_stack, "try_to_connect");
ncteisen274bbbe2017-06-08 14:57:11 -07003065 GRPC_CLOSURE_SCHED(
Yash Tibrewal0ee75742017-10-13 16:07:13 -07003066 GRPC_CLOSURE_CREATE(try_to_connect_locked, chand,
3067 grpc_combiner_scheduler(chand->combiner)),
Craig Tiller613dafa2017-02-09 12:00:43 -08003068 GRPC_ERROR_NONE);
Craig Tillera82950e2015-09-22 12:33:20 -07003069 }
Craig Tiller48cb07c2015-07-15 16:16:15 -07003070 return out;
3071}
3072
Alexander Polcync3b1f182017-04-18 13:51:36 -07003073typedef struct external_connectivity_watcher {
Craig Tillerbaa14a92017-11-03 09:09:36 -07003074 channel_data* chand;
David Garcia Quintas87d5a312017-06-06 19:45:58 -07003075 grpc_polling_entity pollent;
Craig Tillerbaa14a92017-11-03 09:09:36 -07003076 grpc_closure* on_complete;
3077 grpc_closure* watcher_timer_init;
3078 grpc_connectivity_state* state;
Craig Tiller86c99582015-11-25 15:22:26 -08003079 grpc_closure my_closure;
Craig Tillerbaa14a92017-11-03 09:09:36 -07003080 struct external_connectivity_watcher* next;
Craig Tiller86c99582015-11-25 15:22:26 -08003081} external_connectivity_watcher;
3082
Craig Tillerbaa14a92017-11-03 09:09:36 -07003083static external_connectivity_watcher* lookup_external_connectivity_watcher(
3084 channel_data* chand, grpc_closure* on_complete) {
Alexander Polcync3b1f182017-04-18 13:51:36 -07003085 gpr_mu_lock(&chand->external_connectivity_watcher_list_mu);
Craig Tillerbaa14a92017-11-03 09:09:36 -07003086 external_connectivity_watcher* w =
Alexander Polcync3b1f182017-04-18 13:51:36 -07003087 chand->external_connectivity_watcher_list_head;
Craig Tiller4782d922017-11-10 09:53:21 -08003088 while (w != nullptr && w->on_complete != on_complete) {
Alexander Polcync3b1f182017-04-18 13:51:36 -07003089 w = w->next;
3090 }
3091 gpr_mu_unlock(&chand->external_connectivity_watcher_list_mu);
3092 return w;
3093}
3094
3095static void external_connectivity_watcher_list_append(
Craig Tillerbaa14a92017-11-03 09:09:36 -07003096 channel_data* chand, external_connectivity_watcher* w) {
Alexander Polcync3b1f182017-04-18 13:51:36 -07003097 GPR_ASSERT(!lookup_external_connectivity_watcher(chand, w->on_complete));
3098
3099 gpr_mu_lock(&w->chand->external_connectivity_watcher_list_mu);
3100 GPR_ASSERT(!w->next);
3101 w->next = chand->external_connectivity_watcher_list_head;
3102 chand->external_connectivity_watcher_list_head = w;
3103 gpr_mu_unlock(&w->chand->external_connectivity_watcher_list_mu);
3104}
3105
3106static void external_connectivity_watcher_list_remove(
Craig Tillerbaa14a92017-11-03 09:09:36 -07003107 channel_data* chand, external_connectivity_watcher* too_remove) {
Alexander Polcync3b1f182017-04-18 13:51:36 -07003108 GPR_ASSERT(
3109 lookup_external_connectivity_watcher(chand, too_remove->on_complete));
3110 gpr_mu_lock(&chand->external_connectivity_watcher_list_mu);
3111 if (too_remove == chand->external_connectivity_watcher_list_head) {
3112 chand->external_connectivity_watcher_list_head = too_remove->next;
3113 gpr_mu_unlock(&chand->external_connectivity_watcher_list_mu);
3114 return;
3115 }
Craig Tillerbaa14a92017-11-03 09:09:36 -07003116 external_connectivity_watcher* w =
Alexander Polcync3b1f182017-04-18 13:51:36 -07003117 chand->external_connectivity_watcher_list_head;
Craig Tiller4782d922017-11-10 09:53:21 -08003118 while (w != nullptr) {
Alexander Polcync3b1f182017-04-18 13:51:36 -07003119 if (w->next == too_remove) {
3120 w->next = w->next->next;
3121 gpr_mu_unlock(&chand->external_connectivity_watcher_list_mu);
3122 return;
3123 }
3124 w = w->next;
3125 }
3126 GPR_UNREACHABLE_CODE(return );
3127}
3128
3129int grpc_client_channel_num_external_connectivity_watchers(
Craig Tillerbaa14a92017-11-03 09:09:36 -07003130 grpc_channel_element* elem) {
Noah Eisenbe82e642018-02-09 09:16:55 -08003131 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Alexander Polcync3b1f182017-04-18 13:51:36 -07003132 int count = 0;
3133
3134 gpr_mu_lock(&chand->external_connectivity_watcher_list_mu);
Craig Tillerbaa14a92017-11-03 09:09:36 -07003135 external_connectivity_watcher* w =
Alexander Polcync3b1f182017-04-18 13:51:36 -07003136 chand->external_connectivity_watcher_list_head;
Craig Tiller4782d922017-11-10 09:53:21 -08003137 while (w != nullptr) {
Alexander Polcync3b1f182017-04-18 13:51:36 -07003138 count++;
3139 w = w->next;
3140 }
3141 gpr_mu_unlock(&chand->external_connectivity_watcher_list_mu);
3142
3143 return count;
3144}
3145
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003146static void on_external_watch_complete_locked(void* arg, grpc_error* error) {
Noah Eisen4d20a662018-02-09 09:34:04 -08003147 external_connectivity_watcher* w =
3148 static_cast<external_connectivity_watcher*>(arg);
Craig Tillerbaa14a92017-11-03 09:09:36 -07003149 grpc_closure* follow_up = w->on_complete;
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003150 grpc_polling_entity_del_from_pollset_set(&w->pollent,
David Garcia Quintas87d5a312017-06-06 19:45:58 -07003151 w->chand->interested_parties);
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003152 GRPC_CHANNEL_STACK_UNREF(w->chand->owning_stack,
Craig Tiller1d881fb2015-12-01 07:39:04 -08003153 "external_connectivity_watcher");
Alexander Polcync3b1f182017-04-18 13:51:36 -07003154 external_connectivity_watcher_list_remove(w->chand, w);
Craig Tiller86c99582015-11-25 15:22:26 -08003155 gpr_free(w);
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003156 GRPC_CLOSURE_RUN(follow_up, GRPC_ERROR_REF(error));
Craig Tiller613dafa2017-02-09 12:00:43 -08003157}
3158
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003159static void watch_connectivity_state_locked(void* arg,
Craig Tillerbaa14a92017-11-03 09:09:36 -07003160 grpc_error* error_ignored) {
Noah Eisen4d20a662018-02-09 09:34:04 -08003161 external_connectivity_watcher* w =
3162 static_cast<external_connectivity_watcher*>(arg);
Craig Tiller4782d922017-11-10 09:53:21 -08003163 external_connectivity_watcher* found = nullptr;
3164 if (w->state != nullptr) {
Alexander Polcync3b1f182017-04-18 13:51:36 -07003165 external_connectivity_watcher_list_append(w->chand, w);
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003166 GRPC_CLOSURE_RUN(w->watcher_timer_init, GRPC_ERROR_NONE);
Alexander Polcyn2004e392017-10-16 15:14:46 -07003167 GRPC_CLOSURE_INIT(&w->my_closure, on_external_watch_complete_locked, w,
3168 grpc_combiner_scheduler(w->chand->combiner));
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003169 grpc_connectivity_state_notify_on_state_change(&w->chand->state_tracker,
3170 w->state, &w->my_closure);
Alexander Polcync3b1f182017-04-18 13:51:36 -07003171 } else {
Craig Tiller4782d922017-11-10 09:53:21 -08003172 GPR_ASSERT(w->watcher_timer_init == nullptr);
Alexander Polcync3b1f182017-04-18 13:51:36 -07003173 found = lookup_external_connectivity_watcher(w->chand, w->on_complete);
3174 if (found) {
3175 GPR_ASSERT(found->on_complete == w->on_complete);
3176 grpc_connectivity_state_notify_on_state_change(
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003177 &found->chand->state_tracker, nullptr, &found->my_closure);
Alexander Polcync3b1f182017-04-18 13:51:36 -07003178 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003179 grpc_polling_entity_del_from_pollset_set(&w->pollent,
David Garcia Quintas87d5a312017-06-06 19:45:58 -07003180 w->chand->interested_parties);
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003181 GRPC_CHANNEL_STACK_UNREF(w->chand->owning_stack,
Alexander Polcync3b1f182017-04-18 13:51:36 -07003182 "external_connectivity_watcher");
3183 gpr_free(w);
3184 }
Craig Tiller86c99582015-11-25 15:22:26 -08003185}
3186
Craig Tillera82950e2015-09-22 12:33:20 -07003187void grpc_client_channel_watch_connectivity_state(
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003188 grpc_channel_element* elem, grpc_polling_entity pollent,
3189 grpc_connectivity_state* state, grpc_closure* closure,
3190 grpc_closure* watcher_timer_init) {
Noah Eisenbe82e642018-02-09 09:16:55 -08003191 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Craig Tillerbaa14a92017-11-03 09:09:36 -07003192 external_connectivity_watcher* w =
Noah Eisenbe82e642018-02-09 09:16:55 -08003193 static_cast<external_connectivity_watcher*>(gpr_zalloc(sizeof(*w)));
Craig Tiller86c99582015-11-25 15:22:26 -08003194 w->chand = chand;
David Garcia Quintas87d5a312017-06-06 19:45:58 -07003195 w->pollent = pollent;
Mark D. Roth92210832017-05-02 15:04:39 -07003196 w->on_complete = closure;
Craig Tiller613dafa2017-02-09 12:00:43 -08003197 w->state = state;
Alexander Polcync3b1f182017-04-18 13:51:36 -07003198 w->watcher_timer_init = watcher_timer_init;
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003199 grpc_polling_entity_add_to_pollset_set(&w->pollent,
David Garcia Quintas87d5a312017-06-06 19:45:58 -07003200 chand->interested_parties);
Craig Tiller1d881fb2015-12-01 07:39:04 -08003201 GRPC_CHANNEL_STACK_REF(w->chand->owning_stack,
3202 "external_connectivity_watcher");
ncteisen274bbbe2017-06-08 14:57:11 -07003203 GRPC_CLOSURE_SCHED(
ncteisen274bbbe2017-06-08 14:57:11 -07003204 GRPC_CLOSURE_INIT(&w->my_closure, watch_connectivity_state_locked, w,
Craig Tilleree4b1452017-05-12 10:56:03 -07003205 grpc_combiner_scheduler(chand->combiner)),
Craig Tiller613dafa2017-02-09 12:00:43 -08003206 GRPC_ERROR_NONE);
Craig Tiller48cb07c2015-07-15 16:16:15 -07003207}
Mark D. Roth718c8342018-02-28 13:00:04 -08003208
3209grpc_subchannel_call* grpc_client_channel_get_subchannel_call(
3210 grpc_call_element* elem) {
3211 call_data* calld = static_cast<call_data*>(elem->call_data);
3212 return calld->subchannel_call;
3213}