blob: bf3911e5eeadf2c43fd453ce381bb2b6ed989dc5 [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
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800306static void on_resolver_result_changed_locked(void* arg, grpc_error* error) {
Noah Eisenbe82e642018-02-09 09:16:55 -0800307 channel_data* chand = static_cast<channel_data*>(arg);
Craig Tiller6014e8a2017-10-16 13:50:29 -0700308 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth60751fe2017-07-07 12:50:33 -0700309 gpr_log(GPR_DEBUG, "chand=%p: got resolver result: error=%s", chand,
310 grpc_error_string(error));
311 }
Mark D. Roth718c8342018-02-28 13:00:04 -0800312 // Extract the following fields from the resolver result, if non-nullptr.
Mark D. Roth15494b52017-07-12 15:26:55 -0700313 bool lb_policy_updated = false;
Mark D. Rothc8875492018-02-20 08:33:48 -0800314 bool lb_policy_created = false;
Craig Tiller4782d922017-11-10 09:53:21 -0800315 char* lb_policy_name_dup = nullptr;
Mark D. Roth60751fe2017-07-07 12:50:33 -0700316 bool lb_policy_name_changed = false;
Mark D. Rothc8875492018-02-20 08:33:48 -0800317 grpc_core::OrphanablePtr<grpc_core::LoadBalancingPolicy> new_lb_policy;
Craig Tiller4782d922017-11-10 09:53:21 -0800318 char* service_config_json = nullptr;
319 grpc_server_retry_throttle_data* retry_throttle_data = nullptr;
Mark D. Roth3e7f2df2018-02-26 13:17:06 -0800320 grpc_core::RefCountedPtr<MethodParamsTable> method_params_table;
Craig Tiller4782d922017-11-10 09:53:21 -0800321 if (chand->resolver_result != nullptr) {
Juanli Shen592cf342017-12-04 20:52:01 -0800322 if (chand->resolver != nullptr) {
323 // Find LB policy name.
Juanli Shen592cf342017-12-04 20:52:01 -0800324 const grpc_arg* channel_arg = grpc_channel_args_find(
325 chand->resolver_result, GRPC_ARG_LB_POLICY_NAME);
ncteisenbf323a92018-02-14 17:34:05 -0800326 const char* lb_policy_name = grpc_channel_arg_get_string(channel_arg);
Juanli Shen592cf342017-12-04 20:52:01 -0800327 // Special case: If at least one balancer address is present, we use
328 // the grpclb policy, regardless of what the resolver actually specified.
329 channel_arg =
330 grpc_channel_args_find(chand->resolver_result, GRPC_ARG_LB_ADDRESSES);
331 if (channel_arg != nullptr && channel_arg->type == GRPC_ARG_POINTER) {
332 grpc_lb_addresses* addresses =
Noah Eisenbe82e642018-02-09 09:16:55 -0800333 static_cast<grpc_lb_addresses*>(channel_arg->value.pointer.p);
Juanli Shen592cf342017-12-04 20:52:01 -0800334 bool found_balancer_address = false;
335 for (size_t i = 0; i < addresses->num_addresses; ++i) {
336 if (addresses->addresses[i].is_balancer) {
337 found_balancer_address = true;
338 break;
339 }
340 }
341 if (found_balancer_address) {
342 if (lb_policy_name != nullptr &&
343 strcmp(lb_policy_name, "grpclb") != 0) {
344 gpr_log(GPR_INFO,
345 "resolver requested LB policy %s but provided at least one "
346 "balancer address -- forcing use of grpclb LB policy",
347 lb_policy_name);
348 }
349 lb_policy_name = "grpclb";
350 }
351 }
352 // Use pick_first if nothing was specified and we didn't select grpclb
353 // above.
354 if (lb_policy_name == nullptr) lb_policy_name = "pick_first";
Juanli Shen592cf342017-12-04 20:52:01 -0800355 // Check to see if we're already using the right LB policy.
356 // Note: It's safe to use chand->info_lb_policy_name here without
357 // taking a lock on chand->info_mu, because this function is the
358 // only thing that modifies its value, and it can only be invoked
359 // once at any given time.
360 lb_policy_name_changed =
361 chand->info_lb_policy_name == nullptr ||
362 gpr_stricmp(chand->info_lb_policy_name, lb_policy_name) != 0;
363 if (chand->lb_policy != nullptr && !lb_policy_name_changed) {
364 // Continue using the same LB policy. Update with new addresses.
365 lb_policy_updated = true;
Mark D. Rothc8875492018-02-20 08:33:48 -0800366 chand->lb_policy->UpdateLocked(*chand->resolver_result);
Juanli Shen592cf342017-12-04 20:52:01 -0800367 } else {
368 // Instantiate new LB policy.
Mark D. Rothc8875492018-02-20 08:33:48 -0800369 grpc_core::LoadBalancingPolicy::Args lb_policy_args;
370 lb_policy_args.combiner = chand->combiner;
371 lb_policy_args.client_channel_factory = chand->client_channel_factory;
372 lb_policy_args.args = chand->resolver_result;
373 new_lb_policy =
374 grpc_core::LoadBalancingPolicyRegistry::CreateLoadBalancingPolicy(
375 lb_policy_name, lb_policy_args);
Juanli Shen592cf342017-12-04 20:52:01 -0800376 if (new_lb_policy == nullptr) {
377 gpr_log(GPR_ERROR, "could not create LB policy \"%s\"",
378 lb_policy_name);
379 } else {
Mark D. Roth3ef4af22018-02-21 07:53:26 -0800380 lb_policy_created = true;
Juanli Shen592cf342017-12-04 20:52:01 -0800381 reresolution_request_args* args =
Noah Eisen4d20a662018-02-09 09:34:04 -0800382 static_cast<reresolution_request_args*>(
383 gpr_zalloc(sizeof(*args)));
Juanli Shen592cf342017-12-04 20:52:01 -0800384 args->chand = chand;
Mark D. Rothc8875492018-02-20 08:33:48 -0800385 args->lb_policy = new_lb_policy.get();
Juanli Shen592cf342017-12-04 20:52:01 -0800386 GRPC_CLOSURE_INIT(&args->closure, request_reresolution_locked, args,
387 grpc_combiner_scheduler(chand->combiner));
388 GRPC_CHANNEL_STACK_REF(chand->owning_stack, "re-resolution");
Mark D. Rothc8875492018-02-20 08:33:48 -0800389 new_lb_policy->SetReresolutionClosureLocked(&args->closure);
Juanli Shen592cf342017-12-04 20:52:01 -0800390 }
391 }
Mark D. Roth718c8342018-02-28 13:00:04 -0800392 // Before we clean up, save a copy of lb_policy_name, since it might
393 // be pointing to data inside chand->resolver_result.
394 // The copy will be saved in chand->lb_policy_name below.
395 lb_policy_name_dup = gpr_strdup(lb_policy_name);
Juanli Shen592cf342017-12-04 20:52:01 -0800396 // Find service config.
397 channel_arg = grpc_channel_args_find(chand->resolver_result,
398 GRPC_ARG_SERVICE_CONFIG);
ncteisenbf323a92018-02-14 17:34:05 -0800399 service_config_json =
400 gpr_strdup(grpc_channel_arg_get_string(channel_arg));
401 if (service_config_json != nullptr) {
Mark D. Roth3e7f2df2018-02-26 13:17:06 -0800402 grpc_core::UniquePtr<grpc_core::ServiceConfig> service_config =
403 grpc_core::ServiceConfig::Create(service_config_json);
Juanli Shen592cf342017-12-04 20:52:01 -0800404 if (service_config != nullptr) {
Mark D. Roth718c8342018-02-28 13:00:04 -0800405 if (chand->enable_retries) {
406 channel_arg = grpc_channel_args_find(chand->resolver_result,
407 GRPC_ARG_SERVER_URI);
408 const char* server_uri = grpc_channel_arg_get_string(channel_arg);
409 GPR_ASSERT(server_uri != nullptr);
410 grpc_uri* uri = grpc_uri_parse(server_uri, true);
411 GPR_ASSERT(uri->path[0] != '\0');
412 service_config_parsing_state parsing_state;
413 memset(&parsing_state, 0, sizeof(parsing_state));
414 parsing_state.server_name =
415 uri->path[0] == '/' ? uri->path + 1 : uri->path;
416 service_config->ParseGlobalParams(parse_retry_throttle_params,
417 &parsing_state);
418 grpc_uri_destroy(uri);
419 retry_throttle_data = parsing_state.retry_throttle_data;
420 }
Mark D. Roth3e7f2df2018-02-26 13:17:06 -0800421 method_params_table = service_config->CreateMethodConfigTable(
422 ClientChannelMethodParams::CreateFromJson);
Juanli Shen592cf342017-12-04 20:52:01 -0800423 }
424 }
Mark D. Roth9fe284e2016-09-12 11:22:27 -0700425 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800426 grpc_channel_args_destroy(chand->resolver_result);
Craig Tiller4782d922017-11-10 09:53:21 -0800427 chand->resolver_result = nullptr;
Craig Tillera82950e2015-09-22 12:33:20 -0700428 }
Craig Tiller6014e8a2017-10-16 13:50:29 -0700429 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth60751fe2017-07-07 12:50:33 -0700430 gpr_log(GPR_DEBUG,
431 "chand=%p: resolver result: lb_policy_name=\"%s\"%s, "
432 "service_config=\"%s\"",
Yash Tibrewal9eb86722017-09-17 23:43:30 -0700433 chand, lb_policy_name_dup,
434 lb_policy_name_changed ? " (changed)" : "", service_config_json);
Mark D. Roth60751fe2017-07-07 12:50:33 -0700435 }
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700436 // Now swap out fields in chand. Note that the new values may still
Mark D. Roth718c8342018-02-28 13:00:04 -0800437 // be nullptr if (e.g.) the resolver failed to return results or the
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700438 // results did not contain the necessary data.
439 //
440 // First, swap out the data used by cc_get_channel_info().
Craig Tiller613dafa2017-02-09 12:00:43 -0800441 gpr_mu_lock(&chand->info_mu);
Craig Tiller4782d922017-11-10 09:53:21 -0800442 if (lb_policy_name_dup != nullptr) {
Craig Tiller613dafa2017-02-09 12:00:43 -0800443 gpr_free(chand->info_lb_policy_name);
Yash Tibrewal9eb86722017-09-17 23:43:30 -0700444 chand->info_lb_policy_name = lb_policy_name_dup;
Mark D. Rothb2d24882016-10-27 15:44:07 -0700445 }
Craig Tiller4782d922017-11-10 09:53:21 -0800446 if (service_config_json != nullptr) {
Craig Tiller613dafa2017-02-09 12:00:43 -0800447 gpr_free(chand->info_service_config_json);
448 chand->info_service_config_json = service_config_json;
Mark D. Rothc625c7a2016-11-09 14:12:37 -0800449 }
Craig Tiller613dafa2017-02-09 12:00:43 -0800450 gpr_mu_unlock(&chand->info_mu);
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700451 // Swap out the retry throttle data.
Craig Tiller4782d922017-11-10 09:53:21 -0800452 if (chand->retry_throttle_data != nullptr) {
Mark D. Rothd6d192d2017-02-23 08:58:42 -0800453 grpc_server_retry_throttle_data_unref(chand->retry_throttle_data);
454 }
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700455 chand->retry_throttle_data = retry_throttle_data;
456 // Swap out the method params table.
Mark D. Roth3e7f2df2018-02-26 13:17:06 -0800457 chand->method_params_table = std::move(method_params_table);
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700458 // If we have a new LB policy or are shutting down (in which case
Mark D. Roth718c8342018-02-28 13:00:04 -0800459 // new_lb_policy will be nullptr), swap out the LB policy, unreffing the
460 // old one and removing its fds from chand->interested_parties.
461 // Note that we do NOT do this if either (a) we updated the existing
462 // LB policy above or (b) we failed to create the new LB policy (in
463 // which case we want to continue using the most recent one we had).
Craig Tiller4782d922017-11-10 09:53:21 -0800464 if (new_lb_policy != nullptr || error != GRPC_ERROR_NONE ||
465 chand->resolver == nullptr) {
466 if (chand->lb_policy != nullptr) {
Craig Tiller6014e8a2017-10-16 13:50:29 -0700467 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth60751fe2017-07-07 12:50:33 -0700468 gpr_log(GPR_DEBUG, "chand=%p: unreffing lb_policy=%p", chand,
Mark D. Rothc8875492018-02-20 08:33:48 -0800469 chand->lb_policy.get());
Mark D. Roth60751fe2017-07-07 12:50:33 -0700470 }
Mark D. Rothc8875492018-02-20 08:33:48 -0800471 grpc_pollset_set_del_pollset_set(chand->lb_policy->interested_parties(),
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700472 chand->interested_parties);
Mark D. Rothc8875492018-02-20 08:33:48 -0800473 chand->lb_policy->HandOffPendingPicksLocked(new_lb_policy.get());
474 chand->lb_policy.reset();
Craig Tiller45724b32015-09-22 10:42:19 -0700475 }
Mark D. Rothc8875492018-02-20 08:33:48 -0800476 chand->lb_policy = std::move(new_lb_policy);
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700477 }
478 // Now that we've swapped out the relevant fields of chand, check for
479 // error or shutdown.
Craig Tiller4782d922017-11-10 09:53:21 -0800480 if (error != GRPC_ERROR_NONE || chand->resolver == nullptr) {
Craig Tiller6014e8a2017-10-16 13:50:29 -0700481 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth60751fe2017-07-07 12:50:33 -0700482 gpr_log(GPR_DEBUG, "chand=%p: shutting down", chand);
483 }
Craig Tiller4782d922017-11-10 09:53:21 -0800484 if (chand->resolver != nullptr) {
Craig Tiller6014e8a2017-10-16 13:50:29 -0700485 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth60751fe2017-07-07 12:50:33 -0700486 gpr_log(GPR_DEBUG, "chand=%p: shutting down resolver", chand);
487 }
Mark D. Roth209f6442018-02-08 10:26:46 -0800488 chand->resolver.reset();
Craig Tiller76a5c0e2016-03-09 09:05:30 -0800489 }
Craig Tiller8c0d96f2016-03-11 14:27:52 -0800490 set_channel_connectivity_state_locked(
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800491 chand, GRPC_CHANNEL_SHUTDOWN,
ncteisen4b36a3d2017-03-13 19:08:06 -0700492 GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700493 "Got resolver result after disconnection", &error, 1),
Craig Tiller804ff712016-05-05 16:25:40 -0700494 "resolver_gone");
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700495 grpc_closure_list_fail_all(&chand->waiting_for_resolver_result_closures,
496 GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
497 "Channel disconnected", &error, 1));
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800498 GRPC_CLOSURE_LIST_SCHED(&chand->waiting_for_resolver_result_closures);
Mark D. Roth1b95f472018-02-15 12:54:02 -0800499 GRPC_CHANNEL_STACK_UNREF(chand->owning_stack, "resolver");
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700500 } else { // Not shutting down.
501 grpc_connectivity_state state = GRPC_CHANNEL_TRANSIENT_FAILURE;
Craig Tillerbaa14a92017-11-03 09:09:36 -0700502 grpc_error* state_error =
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700503 GRPC_ERROR_CREATE_FROM_STATIC_STRING("No load balancing policy");
Mark D. Rothc8875492018-02-20 08:33:48 -0800504 if (lb_policy_created) {
Craig Tiller6014e8a2017-10-16 13:50:29 -0700505 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth60751fe2017-07-07 12:50:33 -0700506 gpr_log(GPR_DEBUG, "chand=%p: initializing new LB policy", chand);
507 }
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700508 GRPC_ERROR_UNREF(state_error);
Mark D. Rothc8875492018-02-20 08:33:48 -0800509 state = chand->lb_policy->CheckConnectivityLocked(&state_error);
510 grpc_pollset_set_add_pollset_set(chand->lb_policy->interested_parties(),
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700511 chand->interested_parties);
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800512 GRPC_CLOSURE_LIST_SCHED(&chand->waiting_for_resolver_result_closures);
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700513 if (chand->exit_idle_when_lb_policy_arrives) {
Mark D. Rothc8875492018-02-20 08:33:48 -0800514 chand->lb_policy->ExitIdleLocked();
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700515 chand->exit_idle_when_lb_policy_arrives = false;
516 }
Mark D. Rothc8875492018-02-20 08:33:48 -0800517 watch_lb_policy_locked(chand, chand->lb_policy.get(), state);
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700518 }
Mark D. Roth15494b52017-07-12 15:26:55 -0700519 if (!lb_policy_updated) {
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800520 set_channel_connectivity_state_locked(
521 chand, state, GRPC_ERROR_REF(state_error), "new_lb+resolver");
Mark D. Roth15494b52017-07-12 15:26:55 -0700522 }
Mark D. Roth209f6442018-02-08 10:26:46 -0800523 chand->resolver->NextLocked(&chand->resolver_result,
524 &chand->on_resolver_result_changed);
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700525 GRPC_ERROR_UNREF(state_error);
Craig Tillera82950e2015-09-22 12:33:20 -0700526 }
Craig Tiller3f475422015-06-25 10:43:05 -0700527}
528
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800529static void start_transport_op_locked(void* arg, grpc_error* error_ignored) {
Noah Eisenbe82e642018-02-09 09:16:55 -0800530 grpc_transport_op* op = static_cast<grpc_transport_op*>(arg);
Craig Tillerbaa14a92017-11-03 09:09:36 -0700531 grpc_channel_element* elem =
Noah Eisenbe82e642018-02-09 09:16:55 -0800532 static_cast<grpc_channel_element*>(op->handler_private.extra_arg);
533 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Craig Tiller000cd8f2015-09-18 07:20:29 -0700534
Craig Tiller4782d922017-11-10 09:53:21 -0800535 if (op->on_connectivity_state_change != nullptr) {
Craig Tillera82950e2015-09-22 12:33:20 -0700536 grpc_connectivity_state_notify_on_state_change(
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800537 &chand->state_tracker, op->connectivity_state,
Craig Tillera82950e2015-09-22 12:33:20 -0700538 op->on_connectivity_state_change);
Craig Tiller4782d922017-11-10 09:53:21 -0800539 op->on_connectivity_state_change = nullptr;
540 op->connectivity_state = nullptr;
Craig Tillera82950e2015-09-22 12:33:20 -0700541 }
542
Yuchen Zengc272dd72017-12-05 12:18:34 -0800543 if (op->send_ping.on_initiate != nullptr || op->send_ping.on_ack != nullptr) {
Craig Tiller4782d922017-11-10 09:53:21 -0800544 if (chand->lb_policy == nullptr) {
ncteisen274bbbe2017-06-08 14:57:11 -0700545 GRPC_CLOSURE_SCHED(
Yash Tibrewald6c292f2017-12-07 19:38:43 -0800546 op->send_ping.on_initiate,
Yuchen Zengc272dd72017-12-05 12:18:34 -0800547 GRPC_ERROR_CREATE_FROM_STATIC_STRING("Ping with no load balancing"));
548 GRPC_CLOSURE_SCHED(
Yash Tibrewald6c292f2017-12-07 19:38:43 -0800549 op->send_ping.on_ack,
ncteisen4b36a3d2017-03-13 19:08:06 -0700550 GRPC_ERROR_CREATE_FROM_STATIC_STRING("Ping with no load balancing"));
Craig Tiller26dab312015-12-07 14:43:47 -0800551 } else {
Mark D. Rothc8875492018-02-20 08:33:48 -0800552 chand->lb_policy->PingOneLocked(op->send_ping.on_initiate,
553 op->send_ping.on_ack);
Craig Tiller4782d922017-11-10 09:53:21 -0800554 op->bind_pollset = nullptr;
Craig Tiller26dab312015-12-07 14:43:47 -0800555 }
Yuchen Zengc272dd72017-12-05 12:18:34 -0800556 op->send_ping.on_initiate = nullptr;
557 op->send_ping.on_ack = nullptr;
Craig Tiller26dab312015-12-07 14:43:47 -0800558 }
559
Craig Tiller1c51edc2016-05-07 16:18:43 -0700560 if (op->disconnect_with_error != GRPC_ERROR_NONE) {
Craig Tiller4782d922017-11-10 09:53:21 -0800561 if (chand->resolver != nullptr) {
Craig Tiller1c51edc2016-05-07 16:18:43 -0700562 set_channel_connectivity_state_locked(
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800563 chand, GRPC_CHANNEL_SHUTDOWN,
Craig Tiller1c51edc2016-05-07 16:18:43 -0700564 GRPC_ERROR_REF(op->disconnect_with_error), "disconnect");
Mark D. Roth209f6442018-02-08 10:26:46 -0800565 chand->resolver.reset();
Craig Tiller1c51edc2016-05-07 16:18:43 -0700566 if (!chand->started_resolving) {
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700567 grpc_closure_list_fail_all(&chand->waiting_for_resolver_result_closures,
Craig Tiller1c51edc2016-05-07 16:18:43 -0700568 GRPC_ERROR_REF(op->disconnect_with_error));
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800569 GRPC_CLOSURE_LIST_SCHED(&chand->waiting_for_resolver_result_closures);
Craig Tiller1c51edc2016-05-07 16:18:43 -0700570 }
Craig Tiller4782d922017-11-10 09:53:21 -0800571 if (chand->lb_policy != nullptr) {
Mark D. Rothc8875492018-02-20 08:33:48 -0800572 grpc_pollset_set_del_pollset_set(chand->lb_policy->interested_parties(),
Craig Tiller1c51edc2016-05-07 16:18:43 -0700573 chand->interested_parties);
Mark D. Rothc8875492018-02-20 08:33:48 -0800574 chand->lb_policy.reset();
Craig Tiller1c51edc2016-05-07 16:18:43 -0700575 }
Craig Tillerb12d22a2016-04-23 12:50:21 -0700576 }
Craig Tiller1c51edc2016-05-07 16:18:43 -0700577 GRPC_ERROR_UNREF(op->disconnect_with_error);
Craig Tillera82950e2015-09-22 12:33:20 -0700578 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800579 GRPC_CHANNEL_STACK_UNREF(chand->owning_stack, "start_transport_op");
Craig Tillerd2e5cfc2017-02-09 13:02:20 -0800580
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800581 GRPC_CLOSURE_SCHED(op->on_consumed, GRPC_ERROR_NONE);
Craig Tillerbefafe62017-02-09 11:30:54 -0800582}
583
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800584static void cc_start_transport_op(grpc_channel_element* elem,
Craig Tillerbaa14a92017-11-03 09:09:36 -0700585 grpc_transport_op* op) {
Noah Eisenbe82e642018-02-09 09:16:55 -0800586 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Craig Tillerbefafe62017-02-09 11:30:54 -0800587
Craig Tillerbefafe62017-02-09 11:30:54 -0800588 GPR_ASSERT(op->set_accept_stream == false);
Craig Tiller4782d922017-11-10 09:53:21 -0800589 if (op->bind_pollset != nullptr) {
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800590 grpc_pollset_set_add_pollset(chand->interested_parties, op->bind_pollset);
Craig Tillerbefafe62017-02-09 11:30:54 -0800591 }
592
Craig Tillerc55c1022017-03-10 10:26:42 -0800593 op->handler_private.extra_arg = elem;
Craig Tillerd2e5cfc2017-02-09 13:02:20 -0800594 GRPC_CHANNEL_STACK_REF(chand->owning_stack, "start_transport_op");
ncteisen274bbbe2017-06-08 14:57:11 -0700595 GRPC_CLOSURE_SCHED(
ncteisen274bbbe2017-06-08 14:57:11 -0700596 GRPC_CLOSURE_INIT(&op->handler_private.closure, start_transport_op_locked,
Craig Tilleree4b1452017-05-12 10:56:03 -0700597 op, grpc_combiner_scheduler(chand->combiner)),
Craig Tillerbefafe62017-02-09 11:30:54 -0800598 GRPC_ERROR_NONE);
Craig Tillerca3e9d32015-06-27 18:37:27 -0700599}
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800600
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800601static void cc_get_channel_info(grpc_channel_element* elem,
Craig Tillerbaa14a92017-11-03 09:09:36 -0700602 const grpc_channel_info* info) {
Noah Eisenbe82e642018-02-09 09:16:55 -0800603 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Craig Tiller613dafa2017-02-09 12:00:43 -0800604 gpr_mu_lock(&chand->info_mu);
Craig Tiller4782d922017-11-10 09:53:21 -0800605 if (info->lb_policy_name != nullptr) {
606 *info->lb_policy_name = chand->info_lb_policy_name == nullptr
607 ? nullptr
Craig Tiller613dafa2017-02-09 12:00:43 -0800608 : gpr_strdup(chand->info_lb_policy_name);
Mark D. Rothb2d24882016-10-27 15:44:07 -0700609 }
Craig Tiller4782d922017-11-10 09:53:21 -0800610 if (info->service_config_json != nullptr) {
Craig Tiller613dafa2017-02-09 12:00:43 -0800611 *info->service_config_json =
Craig Tiller4782d922017-11-10 09:53:21 -0800612 chand->info_service_config_json == nullptr
613 ? nullptr
Craig Tiller613dafa2017-02-09 12:00:43 -0800614 : gpr_strdup(chand->info_service_config_json);
Mark D. Rothc625c7a2016-11-09 14:12:37 -0800615 }
Craig Tiller613dafa2017-02-09 12:00:43 -0800616 gpr_mu_unlock(&chand->info_mu);
Mark D. Rothb2d24882016-10-27 15:44:07 -0700617}
618
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700619/* Constructor for channel_data */
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800620static grpc_error* cc_init_channel_elem(grpc_channel_element* elem,
Craig Tillerbaa14a92017-11-03 09:09:36 -0700621 grpc_channel_element_args* args) {
Noah Eisenbe82e642018-02-09 09:16:55 -0800622 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700623 GPR_ASSERT(args->is_last);
624 GPR_ASSERT(elem->filter == &grpc_client_channel_filter);
Mark D. Roth21d4b2d2016-11-18 09:53:41 -0800625 // Initialize data members.
Craig Tilleree4b1452017-05-12 10:56:03 -0700626 chand->combiner = grpc_combiner_create();
Craig Tillerd85477512017-02-09 12:02:39 -0800627 gpr_mu_init(&chand->info_mu);
Alexander Polcync3b1f182017-04-18 13:51:36 -0700628 gpr_mu_init(&chand->external_connectivity_watcher_list_mu);
629
630 gpr_mu_lock(&chand->external_connectivity_watcher_list_mu);
Craig Tiller4782d922017-11-10 09:53:21 -0800631 chand->external_connectivity_watcher_list_head = nullptr;
Alexander Polcync3b1f182017-04-18 13:51:36 -0700632 gpr_mu_unlock(&chand->external_connectivity_watcher_list_mu);
633
Mark D. Roth21d4b2d2016-11-18 09:53:41 -0800634 chand->owning_stack = args->channel_stack;
ncteisen274bbbe2017-06-08 14:57:11 -0700635 GRPC_CLOSURE_INIT(&chand->on_resolver_result_changed,
Craig Tillerbefafe62017-02-09 11:30:54 -0800636 on_resolver_result_changed_locked, chand,
Craig Tilleree4b1452017-05-12 10:56:03 -0700637 grpc_combiner_scheduler(chand->combiner));
Mark D. Roth21d4b2d2016-11-18 09:53:41 -0800638 chand->interested_parties = grpc_pollset_set_create();
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700639 grpc_connectivity_state_init(&chand->state_tracker, GRPC_CHANNEL_IDLE,
640 "client_channel");
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800641 grpc_client_channel_start_backup_polling(chand->interested_parties);
Mark D. Roth718c8342018-02-28 13:00:04 -0800642 // Record max per-RPC retry buffer size.
643 const grpc_arg* arg = grpc_channel_args_find(
644 args->channel_args, GRPC_ARG_PER_RPC_RETRY_BUFFER_SIZE);
645 chand->per_rpc_retry_buffer_size = (size_t)grpc_channel_arg_get_integer(
646 arg, {DEFAULT_PER_RPC_RETRY_BUFFER_SIZE, 0, INT_MAX});
647 // Record enable_retries.
648 arg = grpc_channel_args_find(args->channel_args, GRPC_ARG_ENABLE_RETRIES);
649 chand->enable_retries = grpc_channel_arg_get_bool(arg, true);
Mark D. Roth21d4b2d2016-11-18 09:53:41 -0800650 // Record client channel factory.
Mark D. Roth718c8342018-02-28 13:00:04 -0800651 arg = grpc_channel_args_find(args->channel_args,
652 GRPC_ARG_CLIENT_CHANNEL_FACTORY);
Craig Tiller4782d922017-11-10 09:53:21 -0800653 if (arg == nullptr) {
David Garcia Quintas228a5142017-03-30 19:43:00 -0700654 return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
655 "Missing client channel factory in args for client channel filter");
656 }
657 if (arg->type != GRPC_ARG_POINTER) {
658 return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
659 "client channel factory arg must be a pointer");
660 }
Yash Tibrewalbc130da2017-09-12 22:44:08 -0700661 grpc_client_channel_factory_ref(
Noah Eisenbe82e642018-02-09 09:16:55 -0800662 static_cast<grpc_client_channel_factory*>(arg->value.pointer.p));
Yash Tibrewalca3c1c02017-09-07 22:47:16 -0700663 chand->client_channel_factory =
Noah Eisenbe82e642018-02-09 09:16:55 -0800664 static_cast<grpc_client_channel_factory*>(arg->value.pointer.p);
Mark D. Rothdc9bee72017-02-07 12:29:14 -0800665 // Get server name to resolve, using proxy mapper if needed.
Mark D. Roth86e90592016-11-18 09:56:40 -0800666 arg = grpc_channel_args_find(args->channel_args, GRPC_ARG_SERVER_URI);
Craig Tiller4782d922017-11-10 09:53:21 -0800667 if (arg == nullptr) {
David Garcia Quintas228a5142017-03-30 19:43:00 -0700668 return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
669 "Missing server uri in args for client channel filter");
670 }
671 if (arg->type != GRPC_ARG_STRING) {
672 return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
673 "server uri arg must be a string");
674 }
Craig Tiller4782d922017-11-10 09:53:21 -0800675 char* proxy_name = nullptr;
676 grpc_channel_args* new_args = nullptr;
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800677 grpc_proxy_mappers_map_name(arg->value.string, args->channel_args,
Mark D. Rothdc9bee72017-02-07 12:29:14 -0800678 &proxy_name, &new_args);
679 // Instantiate resolver.
Mark D. Roth209f6442018-02-08 10:26:46 -0800680 chand->resolver = grpc_core::ResolverRegistry::CreateResolver(
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800681 proxy_name != nullptr ? proxy_name : arg->value.string,
Craig Tiller4782d922017-11-10 09:53:21 -0800682 new_args != nullptr ? new_args : args->channel_args,
Craig Tiller972470b2017-02-09 15:05:36 -0800683 chand->interested_parties, chand->combiner);
Craig Tiller4782d922017-11-10 09:53:21 -0800684 if (proxy_name != nullptr) gpr_free(proxy_name);
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800685 if (new_args != nullptr) grpc_channel_args_destroy(new_args);
Craig Tiller4782d922017-11-10 09:53:21 -0800686 if (chand->resolver == nullptr) {
ncteisen4b36a3d2017-03-13 19:08:06 -0700687 return GRPC_ERROR_CREATE_FROM_STATIC_STRING("resolver creation failed");
Mark D. Roth5e2566e2016-11-18 10:53:13 -0800688 }
Craig Tiller3be7dd02017-04-03 14:30:03 -0700689 chand->deadline_checking_enabled =
690 grpc_deadline_checking_enabled(args->channel_args);
Mark D. Roth5e2566e2016-11-18 10:53:13 -0800691 return GRPC_ERROR_NONE;
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700692}
693
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800694static void shutdown_resolver_locked(void* arg, grpc_error* error) {
Mark D. Roth209f6442018-02-08 10:26:46 -0800695 grpc_core::Resolver* resolver = static_cast<grpc_core::Resolver*>(arg);
696 resolver->Orphan();
Craig Tiller972470b2017-02-09 15:05:36 -0800697}
698
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700699/* Destructor for channel_data */
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800700static void cc_destroy_channel_elem(grpc_channel_element* elem) {
Noah Eisenbe82e642018-02-09 09:16:55 -0800701 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Craig Tiller4782d922017-11-10 09:53:21 -0800702 if (chand->resolver != nullptr) {
ncteisen274bbbe2017-06-08 14:57:11 -0700703 GRPC_CLOSURE_SCHED(
Mark D. Roth209f6442018-02-08 10:26:46 -0800704 GRPC_CLOSURE_CREATE(shutdown_resolver_locked, chand->resolver.release(),
Yash Tibrewal0ee75742017-10-13 16:07:13 -0700705 grpc_combiner_scheduler(chand->combiner)),
Craig Tiller972470b2017-02-09 15:05:36 -0800706 GRPC_ERROR_NONE);
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700707 }
Craig Tiller4782d922017-11-10 09:53:21 -0800708 if (chand->client_channel_factory != nullptr) {
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800709 grpc_client_channel_factory_unref(chand->client_channel_factory);
Mark D. Roth0e48a9a2016-09-08 14:14:39 -0700710 }
Craig Tiller4782d922017-11-10 09:53:21 -0800711 if (chand->lb_policy != nullptr) {
Mark D. Rothc8875492018-02-20 08:33:48 -0800712 grpc_pollset_set_del_pollset_set(chand->lb_policy->interested_parties(),
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700713 chand->interested_parties);
Mark D. Rothc8875492018-02-20 08:33:48 -0800714 chand->lb_policy.reset();
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700715 }
Craig Tiller613dafa2017-02-09 12:00:43 -0800716 gpr_free(chand->info_lb_policy_name);
717 gpr_free(chand->info_service_config_json);
Craig Tiller4782d922017-11-10 09:53:21 -0800718 if (chand->retry_throttle_data != nullptr) {
Mark D. Rothd6d192d2017-02-23 08:58:42 -0800719 grpc_server_retry_throttle_data_unref(chand->retry_throttle_data);
720 }
Craig Tiller4782d922017-11-10 09:53:21 -0800721 if (chand->method_params_table != nullptr) {
Mark D. Roth3e7f2df2018-02-26 13:17:06 -0800722 chand->method_params_table.reset();
Mark D. Roth9fe284e2016-09-12 11:22:27 -0700723 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -0800724 grpc_client_channel_stop_backup_polling(chand->interested_parties);
725 grpc_connectivity_state_destroy(&chand->state_tracker);
726 grpc_pollset_set_destroy(chand->interested_parties);
727 GRPC_COMBINER_UNREF(chand->combiner, "client_channel");
Craig Tillerd85477512017-02-09 12:02:39 -0800728 gpr_mu_destroy(&chand->info_mu);
Alexander Polcync3b1f182017-04-18 13:51:36 -0700729 gpr_mu_destroy(&chand->external_connectivity_watcher_list_mu);
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700730}
731
732/*************************************************************************
733 * PER-CALL FUNCTIONS
734 */
735
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700736// Max number of batches that can be pending on a call at any given
Mark D. Roth718c8342018-02-28 13:00:04 -0800737// time. This includes one batch for each of the following ops:
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700738// recv_initial_metadata
739// send_initial_metadata
740// recv_message
741// send_message
742// recv_trailing_metadata
743// send_trailing_metadata
Mark D. Roth718c8342018-02-28 13:00:04 -0800744#define MAX_PENDING_BATCHES 6
745
746// Retry support:
747//
748// In order to support retries, we act as a proxy for stream op batches.
749// When we get a batch from the surface, we add it to our list of pending
750// batches, and we then use those batches to construct separate "child"
751// batches to be started on the subchannel call. When the child batches
752// return, we then decide which pending batches have been completed and
753// schedule their callbacks accordingly. If a subchannel call fails and
754// we want to retry it, we do a new pick and start again, constructing
755// new "child" batches for the new subchannel call.
756//
757// Note that retries are committed when receiving data from the server
758// (except for Trailers-Only responses). However, there may be many
759// send ops started before receiving any data, so we may have already
760// completed some number of send ops (and returned the completions up to
761// the surface) by the time we realize that we need to retry. To deal
762// with this, we cache data for send ops, so that we can replay them on a
763// different subchannel call even after we have completed the original
764// batches.
765//
766// There are two sets of data to maintain:
767// - In call_data (in the parent channel), we maintain a list of pending
768// ops and cached data for send ops.
769// - In the subchannel call, we maintain state to indicate what ops have
770// already been sent down to that call.
771//
772// When constructing the "child" batches, we compare those two sets of
773// data to see which batches need to be sent to the subchannel call.
774
775// TODO(roth): In subsequent PRs:
776// - add support for transparent retries (including initial metadata)
777// - figure out how to record stats in census for retries
778// (census filter is on top of this one)
779// - add census stats for retries
780
781// State used for starting a retryable batch on a subchannel call.
782// This provides its own grpc_transport_stream_op_batch and other data
783// structures needed to populate the ops in the batch.
784// We allocate one struct on the arena for each attempt at starting a
785// batch on a given subchannel call.
786typedef struct {
787 gpr_refcount refs;
788 grpc_call_element* elem;
789 grpc_subchannel_call* subchannel_call; // Holds a ref.
790 // The batch to use in the subchannel call.
791 // Its payload field points to subchannel_call_retry_state.batch_payload.
792 grpc_transport_stream_op_batch batch;
793 // For send_initial_metadata.
794 // Note that we need to make a copy of the initial metadata for each
795 // subchannel call instead of just referring to the copy in call_data,
796 // because filters in the subchannel stack will probably add entries,
797 // so we need to start in a pristine state for each attempt of the call.
798 grpc_linked_mdelem* send_initial_metadata_storage;
799 grpc_metadata_batch send_initial_metadata;
800 // For send_message.
Mark D. Roth3d8b32d2018-03-09 13:25:40 -0800801 grpc_core::ManualConstructor<grpc_core::ByteStreamCache::CachingByteStream>
802 send_message;
Mark D. Roth718c8342018-02-28 13:00:04 -0800803 // For send_trailing_metadata.
804 grpc_linked_mdelem* send_trailing_metadata_storage;
805 grpc_metadata_batch send_trailing_metadata;
806 // For intercepting recv_initial_metadata.
807 grpc_metadata_batch recv_initial_metadata;
808 grpc_closure recv_initial_metadata_ready;
809 bool trailing_metadata_available;
810 // For intercepting recv_message.
811 grpc_closure recv_message_ready;
Mark D. Roth3d8b32d2018-03-09 13:25:40 -0800812 grpc_core::OrphanablePtr<grpc_core::ByteStream> recv_message;
Mark D. Roth718c8342018-02-28 13:00:04 -0800813 // For intercepting recv_trailing_metadata.
814 grpc_metadata_batch recv_trailing_metadata;
815 grpc_transport_stream_stats collect_stats;
816 // For intercepting on_complete.
817 grpc_closure on_complete;
818} subchannel_batch_data;
819
820// Retry state associated with a subchannel call.
821// Stored in the parent_data of the subchannel call object.
822typedef struct {
823 // subchannel_batch_data.batch.payload points to this.
824 grpc_transport_stream_op_batch_payload batch_payload;
825 // These fields indicate which ops have been started and completed on
826 // this subchannel call.
827 size_t started_send_message_count;
828 size_t completed_send_message_count;
829 size_t started_recv_message_count;
830 size_t completed_recv_message_count;
831 bool started_send_initial_metadata : 1;
832 bool completed_send_initial_metadata : 1;
833 bool started_send_trailing_metadata : 1;
834 bool completed_send_trailing_metadata : 1;
835 bool started_recv_initial_metadata : 1;
836 bool completed_recv_initial_metadata : 1;
837 bool started_recv_trailing_metadata : 1;
838 bool completed_recv_trailing_metadata : 1;
839 // State for callback processing.
840 bool retry_dispatched : 1;
841 bool recv_initial_metadata_ready_deferred : 1;
842 bool recv_message_ready_deferred : 1;
843 grpc_error* recv_initial_metadata_error;
844 grpc_error* recv_message_error;
845} subchannel_call_retry_state;
846
847// Pending batches stored in call data.
848typedef struct {
849 // The pending batch. If nullptr, this slot is empty.
850 grpc_transport_stream_op_batch* batch;
851 // Indicates whether payload for send ops has been cached in call data.
852 bool send_ops_cached;
853} pending_batch;
Mark D. Roth0ca0be82017-06-20 07:49:33 -0700854
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700855/** Call data. Holds a pointer to grpc_subchannel_call and the
856 associated machinery to create such a pointer.
857 Handles queueing of stream ops until a call object is ready, waiting
858 for initial metadata before trying to create a call object,
859 and handling cancellation gracefully. */
860typedef struct client_channel_call_data {
Mark D. Roth72f6da82016-09-02 13:42:38 -0700861 // State for handling deadlines.
862 // The code in deadline_filter.c requires this to be the first field.
Mark D. Roth72f6da82016-09-02 13:42:38 -0700863 // TODO(roth): This is slightly sub-optimal in that grpc_deadline_state
Mark D. Roth66f3d2b2017-09-01 09:02:17 -0700864 // and this struct both independently store pointers to the call stack
865 // and call combiner. If/when we have time, find a way to avoid this
866 // without breaking the grpc_deadline_state abstraction.
Mark D. Roth72f6da82016-09-02 13:42:38 -0700867 grpc_deadline_state deadline_state;
Mark D. Rothf28763c2016-09-14 15:18:40 -0700868
Craig Tiller7c70b6c2017-01-23 07:48:42 -0800869 grpc_slice path; // Request path.
Mark D. Rothe40dd292016-10-05 14:58:37 -0700870 gpr_timespec call_start_time;
Craig Tiller89c14282017-07-19 15:32:27 -0700871 grpc_millis deadline;
Craig Tillerbaa14a92017-11-03 09:09:36 -0700872 gpr_arena* arena;
873 grpc_call_stack* owning_call;
874 grpc_call_combiner* call_combiner;
Mark D. Roth76e264b2017-08-25 09:03:33 -0700875
Craig Tillerbaa14a92017-11-03 09:09:36 -0700876 grpc_server_retry_throttle_data* retry_throttle_data;
Mark D. Roth3e7f2df2018-02-26 13:17:06 -0800877 grpc_core::RefCountedPtr<ClientChannelMethodParams> method_params;
Mark D. Rothaa850a72016-09-26 13:38:02 -0700878
Craig Tillerbaa14a92017-11-03 09:09:36 -0700879 grpc_subchannel_call* subchannel_call;
Mark D. Roth718c8342018-02-28 13:00:04 -0800880
881 // Set when we get a cancel_stream op.
882 grpc_error* cancel_error;
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700883
Mark D. Rothc8875492018-02-20 08:33:48 -0800884 grpc_core::LoadBalancingPolicy::PickState pick;
Mark D. Roth718c8342018-02-28 13:00:04 -0800885 grpc_closure pick_closure;
886 grpc_closure pick_cancel_closure;
Mark D. Roth60751fe2017-07-07 12:50:33 -0700887
Craig Tillerbaa14a92017-11-03 09:09:36 -0700888 grpc_polling_entity* pollent;
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700889
Mark D. Roth718c8342018-02-28 13:00:04 -0800890 // Batches are added to this list when received from above.
891 // They are removed when we are done handling the batch (i.e., when
892 // either we have invoked all of the batch's callbacks or we have
893 // passed the batch down to the subchannel call and are not
894 // intercepting any of its callbacks).
895 pending_batch pending_batches[MAX_PENDING_BATCHES];
896 bool pending_send_initial_metadata : 1;
897 bool pending_send_message : 1;
898 bool pending_send_trailing_metadata : 1;
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700899
Mark D. Roth718c8342018-02-28 13:00:04 -0800900 // Retry state.
901 bool enable_retries : 1;
902 bool retry_committed : 1;
903 bool last_attempt_got_server_pushback : 1;
904 int num_attempts_completed;
905 size_t bytes_buffered_for_retry;
906 grpc_core::ManualConstructor<grpc_core::BackOff> retry_backoff;
907 grpc_timer retry_timer;
David Garcia Quintasd1a47f12016-09-02 12:46:44 +0200908
Mark D. Roth718c8342018-02-28 13:00:04 -0800909 // Cached data for retrying send ops.
910 // send_initial_metadata
911 bool seen_send_initial_metadata;
912 grpc_linked_mdelem* send_initial_metadata_storage;
913 grpc_metadata_batch send_initial_metadata;
914 uint32_t send_initial_metadata_flags;
915 gpr_atm* peer_string;
916 // send_message
917 // When we get a send_message op, we replace the original byte stream
Mark D. Roth3d8b32d2018-03-09 13:25:40 -0800918 // with a CachingByteStream that caches the slices to a local buffer for
919 // use in retries.
Mark D. Roth718c8342018-02-28 13:00:04 -0800920 // Note: We inline the cache for the first 3 send_message ops and use
921 // dynamic allocation after that. This number was essentially picked
922 // at random; it could be changed in the future to tune performance.
Mark D. Roth3d8b32d2018-03-09 13:25:40 -0800923 grpc_core::InlinedVector<grpc_core::ByteStreamCache*, 3> send_messages;
Mark D. Roth718c8342018-02-28 13:00:04 -0800924 // send_trailing_metadata
925 bool seen_send_trailing_metadata;
926 grpc_linked_mdelem* send_trailing_metadata_storage;
927 grpc_metadata_batch send_trailing_metadata;
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700928} call_data;
929
Mark D. Roth718c8342018-02-28 13:00:04 -0800930// Forward declarations.
931static void retry_commit(grpc_call_element* elem,
932 subchannel_call_retry_state* retry_state);
933static void start_internal_recv_trailing_metadata(grpc_call_element* elem);
934static void on_complete(void* arg, grpc_error* error);
935static void start_retriable_subchannel_batches(void* arg, grpc_error* ignored);
936static void pick_after_resolver_result_start_locked(grpc_call_element* elem);
937static void start_pick_locked(void* arg, grpc_error* ignored);
Craig Tiller8b1d59c2016-12-27 15:15:30 -0800938
Mark D. Roth718c8342018-02-28 13:00:04 -0800939//
940// send op data caching
941//
942
943// Caches data for send ops so that it can be retried later, if not
944// already cached.
945static void maybe_cache_send_ops_for_batch(call_data* calld,
946 pending_batch* pending) {
947 if (pending->send_ops_cached) return;
948 pending->send_ops_cached = true;
949 grpc_transport_stream_op_batch* batch = pending->batch;
950 // Save a copy of metadata for send_initial_metadata ops.
Mark D. Roth76e264b2017-08-25 09:03:33 -0700951 if (batch->send_initial_metadata) {
Mark D. Roth718c8342018-02-28 13:00:04 -0800952 calld->seen_send_initial_metadata = true;
953 GPR_ASSERT(calld->send_initial_metadata_storage == nullptr);
954 grpc_metadata_batch* send_initial_metadata =
955 batch->payload->send_initial_metadata.send_initial_metadata;
956 calld->send_initial_metadata_storage = (grpc_linked_mdelem*)gpr_arena_alloc(
957 calld->arena,
958 sizeof(grpc_linked_mdelem) * send_initial_metadata->list.count);
959 grpc_metadata_batch_copy(send_initial_metadata,
960 &calld->send_initial_metadata,
961 calld->send_initial_metadata_storage);
962 calld->send_initial_metadata_flags =
963 batch->payload->send_initial_metadata.send_initial_metadata_flags;
964 calld->peer_string = batch->payload->send_initial_metadata.peer_string;
965 }
966 // Set up cache for send_message ops.
967 if (batch->send_message) {
Mark D. Roth3d8b32d2018-03-09 13:25:40 -0800968 grpc_core::ByteStreamCache* cache =
969 static_cast<grpc_core::ByteStreamCache*>(
970 gpr_arena_alloc(calld->arena, sizeof(grpc_core::ByteStreamCache)));
971 new (cache) grpc_core::ByteStreamCache(
972 std::move(batch->payload->send_message.send_message));
Mark D. Roth718c8342018-02-28 13:00:04 -0800973 calld->send_messages.push_back(cache);
974 }
975 // Save metadata batch for send_trailing_metadata ops.
976 if (batch->send_trailing_metadata) {
977 calld->seen_send_trailing_metadata = true;
978 GPR_ASSERT(calld->send_trailing_metadata_storage == nullptr);
979 grpc_metadata_batch* send_trailing_metadata =
980 batch->payload->send_trailing_metadata.send_trailing_metadata;
981 calld->send_trailing_metadata_storage =
982 (grpc_linked_mdelem*)gpr_arena_alloc(
983 calld->arena,
984 sizeof(grpc_linked_mdelem) * send_trailing_metadata->list.count);
985 grpc_metadata_batch_copy(send_trailing_metadata,
986 &calld->send_trailing_metadata,
987 calld->send_trailing_metadata_storage);
Mark D. Roth76e264b2017-08-25 09:03:33 -0700988 }
Mark D. Roth2a5959f2016-09-01 08:20:27 -0700989}
990
Mark D. Roth718c8342018-02-28 13:00:04 -0800991// Frees cached send ops that have already been completed after
992// committing the call.
993static void free_cached_send_op_data_after_commit(
994 grpc_call_element* elem, subchannel_call_retry_state* retry_state) {
Noah Eisenbe82e642018-02-09 09:16:55 -0800995 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
996 call_data* calld = static_cast<call_data*>(elem->call_data);
Mark D. Roth718c8342018-02-28 13:00:04 -0800997 if (retry_state->completed_send_initial_metadata) {
998 grpc_metadata_batch_destroy(&calld->send_initial_metadata);
Mark D. Roth60751fe2017-07-07 12:50:33 -0700999 }
Mark D. Roth718c8342018-02-28 13:00:04 -08001000 for (size_t i = 0; i < retry_state->completed_send_message_count; ++i) {
1001 if (grpc_client_channel_trace.enabled()) {
1002 gpr_log(GPR_DEBUG,
1003 "chand=%p calld=%p: destroying calld->send_messages[%" PRIuPTR
1004 "]",
1005 chand, calld, i);
1006 }
Mark D. Roth3d8b32d2018-03-09 13:25:40 -08001007 calld->send_messages[i]->Destroy();
Mark D. Roth2a5959f2016-09-01 08:20:27 -07001008 }
Mark D. Roth718c8342018-02-28 13:00:04 -08001009 if (retry_state->completed_send_trailing_metadata) {
1010 grpc_metadata_batch_destroy(&calld->send_trailing_metadata);
1011 }
Mark D. Roth2a5959f2016-09-01 08:20:27 -07001012}
1013
Mark D. Roth718c8342018-02-28 13:00:04 -08001014// Frees cached send ops that were completed by the completed batch in
1015// batch_data. Used when batches are completed after the call is committed.
1016static void free_cached_send_op_data_for_completed_batch(
1017 grpc_call_element* elem, subchannel_batch_data* batch_data,
1018 subchannel_call_retry_state* retry_state) {
Noah Eisenbe82e642018-02-09 09:16:55 -08001019 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1020 call_data* calld = static_cast<call_data*>(elem->call_data);
Mark D. Roth718c8342018-02-28 13:00:04 -08001021 if (batch_data->batch.send_initial_metadata) {
1022 grpc_metadata_batch_destroy(&calld->send_initial_metadata);
1023 }
1024 if (batch_data->batch.send_message) {
1025 if (grpc_client_channel_trace.enabled()) {
1026 gpr_log(GPR_DEBUG,
1027 "chand=%p calld=%p: destroying calld->send_messages[%" PRIuPTR
1028 "]",
1029 chand, calld, retry_state->completed_send_message_count - 1);
1030 }
Mark D. Roth3d8b32d2018-03-09 13:25:40 -08001031 calld->send_messages[retry_state->completed_send_message_count - 1]
1032 ->Destroy();
Mark D. Roth718c8342018-02-28 13:00:04 -08001033 }
1034 if (batch_data->batch.send_trailing_metadata) {
1035 grpc_metadata_batch_destroy(&calld->send_trailing_metadata);
1036 }
1037}
1038
1039//
1040// pending_batches management
1041//
1042
1043// Returns the index into calld->pending_batches to be used for batch.
1044static size_t get_batch_index(grpc_transport_stream_op_batch* batch) {
1045 // Note: It is important the send_initial_metadata be the first entry
1046 // here, since the code in pick_subchannel_locked() assumes it will be.
1047 if (batch->send_initial_metadata) return 0;
1048 if (batch->send_message) return 1;
1049 if (batch->send_trailing_metadata) return 2;
1050 if (batch->recv_initial_metadata) return 3;
1051 if (batch->recv_message) return 4;
1052 if (batch->recv_trailing_metadata) return 5;
1053 GPR_UNREACHABLE_CODE(return (size_t)-1);
1054}
1055
1056// This is called via the call combiner, so access to calld is synchronized.
1057static void pending_batches_add(grpc_call_element* elem,
1058 grpc_transport_stream_op_batch* batch) {
1059 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1060 call_data* calld = static_cast<call_data*>(elem->call_data);
1061 const size_t idx = get_batch_index(batch);
Craig Tiller6014e8a2017-10-16 13:50:29 -07001062 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth718c8342018-02-28 13:00:04 -08001063 gpr_log(GPR_DEBUG,
1064 "chand=%p calld=%p: adding pending batch at index %" PRIuPTR, chand,
1065 calld, idx);
Mark D. Roth60751fe2017-07-07 12:50:33 -07001066 }
Mark D. Roth718c8342018-02-28 13:00:04 -08001067 pending_batch* pending = &calld->pending_batches[idx];
1068 GPR_ASSERT(pending->batch == nullptr);
1069 pending->batch = batch;
1070 pending->send_ops_cached = false;
1071 if (calld->enable_retries) {
1072 // Update state in calld about pending batches.
1073 // Also check if the batch takes us over the retry buffer limit.
1074 // Note: We don't check the size of trailing metadata here, because
1075 // gRPC clients do not send trailing metadata.
1076 if (batch->send_initial_metadata) {
1077 calld->pending_send_initial_metadata = true;
1078 calld->bytes_buffered_for_retry += grpc_metadata_batch_size(
1079 batch->payload->send_initial_metadata.send_initial_metadata);
1080 }
1081 if (batch->send_message) {
1082 calld->pending_send_message = true;
1083 calld->bytes_buffered_for_retry +=
Mark D. Roth3d8b32d2018-03-09 13:25:40 -08001084 batch->payload->send_message.send_message->length();
Mark D. Roth718c8342018-02-28 13:00:04 -08001085 }
1086 if (batch->send_trailing_metadata) {
1087 calld->pending_send_trailing_metadata = true;
1088 }
1089 if (calld->bytes_buffered_for_retry > chand->per_rpc_retry_buffer_size) {
1090 if (grpc_client_channel_trace.enabled()) {
1091 gpr_log(GPR_DEBUG,
1092 "chand=%p calld=%p: exceeded retry buffer size, committing",
1093 chand, calld);
1094 }
1095 subchannel_call_retry_state* retry_state =
1096 calld->subchannel_call == nullptr
1097 ? nullptr
1098 : static_cast<subchannel_call_retry_state*>(
1099 grpc_connected_subchannel_call_get_parent_data(
1100 calld->subchannel_call));
1101 retry_commit(elem, retry_state);
1102 // If we are not going to retry and have not yet started, pretend
1103 // retries are disabled so that we don't bother with retry overhead.
1104 if (calld->num_attempts_completed == 0) {
1105 if (grpc_client_channel_trace.enabled()) {
1106 gpr_log(GPR_DEBUG,
1107 "chand=%p calld=%p: disabling retries before first attempt",
1108 chand, calld);
Mark D. Roth0ca0be82017-06-20 07:49:33 -07001109 }
Mark D. Roth718c8342018-02-28 13:00:04 -08001110 calld->enable_retries = false;
Craig Tiller11c17d42017-03-13 13:36:34 -07001111 }
1112 }
1113 }
Craig Tiller11c17d42017-03-13 13:36:34 -07001114}
Craig Tillerea4a4f12017-03-13 13:36:52 -07001115
Mark D. Roth718c8342018-02-28 13:00:04 -08001116static void pending_batch_clear(call_data* calld, pending_batch* pending) {
1117 if (calld->enable_retries) {
1118 if (pending->batch->send_initial_metadata) {
1119 calld->pending_send_initial_metadata = false;
1120 }
1121 if (pending->batch->send_message) {
1122 calld->pending_send_message = false;
1123 }
1124 if (pending->batch->send_trailing_metadata) {
1125 calld->pending_send_trailing_metadata = false;
1126 }
1127 }
1128 pending->batch = nullptr;
1129}
1130
1131// This is called via the call combiner, so access to calld is synchronized.
1132static void fail_pending_batch_in_call_combiner(void* arg, grpc_error* error) {
1133 grpc_transport_stream_op_batch* batch =
1134 static_cast<grpc_transport_stream_op_batch*>(arg);
1135 call_data* calld = static_cast<call_data*>(batch->handler_private.extra_arg);
1136 // Note: This will release the call combiner.
1137 grpc_transport_stream_op_batch_finish_with_failure(
1138 batch, GRPC_ERROR_REF(error), calld->call_combiner);
1139}
1140
1141// This is called via the call combiner, so access to calld is synchronized.
1142// If yield_call_combiner is true, assumes responsibility for yielding
1143// the call combiner.
1144static void pending_batches_fail(grpc_call_element* elem, grpc_error* error,
1145 bool yield_call_combiner) {
1146 GPR_ASSERT(error != GRPC_ERROR_NONE);
1147 call_data* calld = static_cast<call_data*>(elem->call_data);
1148 if (grpc_client_channel_trace.enabled()) {
1149 size_t num_batches = 0;
1150 for (size_t i = 0; i < GPR_ARRAY_SIZE(calld->pending_batches); ++i) {
1151 if (calld->pending_batches[i].batch != nullptr) ++num_batches;
1152 }
1153 gpr_log(GPR_DEBUG,
1154 "chand=%p calld=%p: failing %" PRIuPTR " pending batches: %s",
1155 elem->channel_data, calld, num_batches, grpc_error_string(error));
1156 }
1157 grpc_transport_stream_op_batch*
1158 batches[GPR_ARRAY_SIZE(calld->pending_batches)];
1159 size_t num_batches = 0;
1160 for (size_t i = 0; i < GPR_ARRAY_SIZE(calld->pending_batches); ++i) {
1161 pending_batch* pending = &calld->pending_batches[i];
1162 grpc_transport_stream_op_batch* batch = pending->batch;
1163 if (batch != nullptr) {
1164 batches[num_batches++] = batch;
1165 pending_batch_clear(calld, pending);
1166 }
1167 }
1168 for (size_t i = yield_call_combiner ? 1 : 0; i < num_batches; ++i) {
1169 grpc_transport_stream_op_batch* batch = batches[i];
1170 batch->handler_private.extra_arg = calld;
1171 GRPC_CLOSURE_INIT(&batch->handler_private.closure,
1172 fail_pending_batch_in_call_combiner, batch,
1173 grpc_schedule_on_exec_ctx);
1174 GRPC_CALL_COMBINER_START(calld->call_combiner,
1175 &batch->handler_private.closure,
1176 GRPC_ERROR_REF(error), "pending_batches_fail");
1177 }
1178 if (yield_call_combiner) {
1179 if (num_batches > 0) {
1180 // Note: This will release the call combiner.
1181 grpc_transport_stream_op_batch_finish_with_failure(
1182 batches[0], GRPC_ERROR_REF(error), calld->call_combiner);
1183 } else {
1184 GRPC_CALL_COMBINER_STOP(calld->call_combiner, "pending_batches_fail");
1185 }
1186 }
1187 GRPC_ERROR_UNREF(error);
1188}
1189
1190// This is called via the call combiner, so access to calld is synchronized.
1191static void resume_pending_batch_in_call_combiner(void* arg,
1192 grpc_error* ignored) {
1193 grpc_transport_stream_op_batch* batch =
1194 static_cast<grpc_transport_stream_op_batch*>(arg);
1195 grpc_subchannel_call* subchannel_call =
1196 static_cast<grpc_subchannel_call*>(batch->handler_private.extra_arg);
1197 // Note: This will release the call combiner.
1198 grpc_subchannel_call_process_op(subchannel_call, batch);
1199}
1200
1201// This is called via the call combiner, so access to calld is synchronized.
1202static void pending_batches_resume(grpc_call_element* elem) {
Noah Eisenbe82e642018-02-09 09:16:55 -08001203 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1204 call_data* calld = static_cast<call_data*>(elem->call_data);
Mark D. Roth718c8342018-02-28 13:00:04 -08001205 if (calld->enable_retries) {
1206 start_retriable_subchannel_batches(elem, GRPC_ERROR_NONE);
1207 return;
1208 }
1209 // Retries not enabled; send down batches as-is.
1210 if (grpc_client_channel_trace.enabled()) {
1211 size_t num_batches = 0;
1212 for (size_t i = 0; i < GPR_ARRAY_SIZE(calld->pending_batches); ++i) {
1213 if (calld->pending_batches[i].batch != nullptr) ++num_batches;
1214 }
1215 gpr_log(GPR_DEBUG,
1216 "chand=%p calld=%p: starting %" PRIuPTR
1217 " pending batches on subchannel_call=%p",
1218 chand, calld, num_batches, calld->subchannel_call);
1219 }
1220 grpc_transport_stream_op_batch*
1221 batches[GPR_ARRAY_SIZE(calld->pending_batches)];
1222 size_t num_batches = 0;
1223 for (size_t i = 0; i < GPR_ARRAY_SIZE(calld->pending_batches); ++i) {
1224 pending_batch* pending = &calld->pending_batches[i];
1225 grpc_transport_stream_op_batch* batch = pending->batch;
1226 if (batch != nullptr) {
1227 batches[num_batches++] = batch;
1228 pending_batch_clear(calld, pending);
1229 }
1230 }
1231 for (size_t i = 1; i < num_batches; ++i) {
1232 grpc_transport_stream_op_batch* batch = batches[i];
1233 batch->handler_private.extra_arg = calld->subchannel_call;
1234 GRPC_CLOSURE_INIT(&batch->handler_private.closure,
1235 resume_pending_batch_in_call_combiner, batch,
1236 grpc_schedule_on_exec_ctx);
1237 GRPC_CALL_COMBINER_START(calld->call_combiner,
1238 &batch->handler_private.closure, GRPC_ERROR_NONE,
1239 "pending_batches_resume");
1240 }
1241 GPR_ASSERT(num_batches > 0);
1242 // Note: This will release the call combiner.
1243 grpc_subchannel_call_process_op(calld->subchannel_call, batches[0]);
1244}
1245
1246static void maybe_clear_pending_batch(grpc_call_element* elem,
1247 pending_batch* pending) {
1248 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1249 call_data* calld = static_cast<call_data*>(elem->call_data);
1250 grpc_transport_stream_op_batch* batch = pending->batch;
1251 // We clear the pending batch if all of its callbacks have been
1252 // scheduled and reset to nullptr.
1253 if (batch->on_complete == nullptr &&
1254 (!batch->recv_initial_metadata ||
1255 batch->payload->recv_initial_metadata.recv_initial_metadata_ready ==
1256 nullptr) &&
1257 (!batch->recv_message ||
1258 batch->payload->recv_message.recv_message_ready == nullptr)) {
1259 if (grpc_client_channel_trace.enabled()) {
1260 gpr_log(GPR_DEBUG, "chand=%p calld=%p: clearing pending batch", chand,
1261 calld);
1262 }
1263 pending_batch_clear(calld, pending);
1264 }
1265}
1266
1267// Returns true if all ops in the pending batch have been completed.
1268static bool pending_batch_is_completed(
1269 pending_batch* pending, call_data* calld,
1270 subchannel_call_retry_state* retry_state) {
1271 if (pending->batch == nullptr || pending->batch->on_complete == nullptr) {
1272 return false;
1273 }
1274 if (pending->batch->send_initial_metadata &&
1275 !retry_state->completed_send_initial_metadata) {
1276 return false;
1277 }
1278 if (pending->batch->send_message &&
1279 retry_state->completed_send_message_count < calld->send_messages.size()) {
1280 return false;
1281 }
1282 if (pending->batch->send_trailing_metadata &&
1283 !retry_state->completed_send_trailing_metadata) {
1284 return false;
1285 }
1286 if (pending->batch->recv_initial_metadata &&
1287 !retry_state->completed_recv_initial_metadata) {
1288 return false;
1289 }
1290 if (pending->batch->recv_message &&
1291 retry_state->completed_recv_message_count <
1292 retry_state->started_recv_message_count) {
1293 return false;
1294 }
1295 if (pending->batch->recv_trailing_metadata &&
1296 !retry_state->completed_recv_trailing_metadata) {
1297 return false;
1298 }
1299 return true;
1300}
1301
1302// Returns true if any op in the batch was not yet started.
1303static bool pending_batch_is_unstarted(
1304 pending_batch* pending, call_data* calld,
1305 subchannel_call_retry_state* retry_state) {
1306 if (pending->batch == nullptr || pending->batch->on_complete == nullptr) {
1307 return false;
1308 }
1309 if (pending->batch->send_initial_metadata &&
1310 !retry_state->started_send_initial_metadata) {
1311 return true;
1312 }
1313 if (pending->batch->send_message &&
1314 retry_state->started_send_message_count < calld->send_messages.size()) {
1315 return true;
1316 }
1317 if (pending->batch->send_trailing_metadata &&
1318 !retry_state->started_send_trailing_metadata) {
1319 return true;
1320 }
1321 if (pending->batch->recv_initial_metadata &&
1322 !retry_state->started_recv_initial_metadata) {
1323 return true;
1324 }
1325 if (pending->batch->recv_message &&
1326 retry_state->completed_recv_message_count ==
1327 retry_state->started_recv_message_count) {
1328 return true;
1329 }
1330 if (pending->batch->recv_trailing_metadata &&
1331 !retry_state->started_recv_trailing_metadata) {
1332 return true;
1333 }
1334 return false;
1335}
1336
1337//
1338// retry code
1339//
1340
1341// Commits the call so that no further retry attempts will be performed.
1342static void retry_commit(grpc_call_element* elem,
1343 subchannel_call_retry_state* retry_state) {
1344 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1345 call_data* calld = static_cast<call_data*>(elem->call_data);
1346 if (calld->retry_committed) return;
1347 calld->retry_committed = true;
1348 if (grpc_client_channel_trace.enabled()) {
1349 gpr_log(GPR_DEBUG, "chand=%p calld=%p: committing retries", chand, calld);
1350 }
1351 if (retry_state != nullptr) {
1352 free_cached_send_op_data_after_commit(elem, retry_state);
1353 }
1354}
1355
1356// Starts a retry after appropriate back-off.
1357static void do_retry(grpc_call_element* elem,
1358 subchannel_call_retry_state* retry_state,
1359 grpc_millis server_pushback_ms) {
1360 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1361 call_data* calld = static_cast<call_data*>(elem->call_data);
1362 GPR_ASSERT(calld->method_params != nullptr);
1363 const ClientChannelMethodParams::RetryPolicy* retry_policy =
1364 calld->method_params->retry_policy();
1365 GPR_ASSERT(retry_policy != nullptr);
1366 // Reset subchannel call and connected subchannel.
1367 if (calld->subchannel_call != nullptr) {
1368 GRPC_SUBCHANNEL_CALL_UNREF(calld->subchannel_call,
1369 "client_channel_call_retry");
1370 calld->subchannel_call = nullptr;
1371 }
1372 if (calld->pick.connected_subchannel != nullptr) {
1373 calld->pick.connected_subchannel.reset();
1374 }
1375 // Compute backoff delay.
1376 grpc_millis next_attempt_time;
1377 if (server_pushback_ms >= 0) {
1378 next_attempt_time = grpc_core::ExecCtx::Get()->Now() + server_pushback_ms;
1379 calld->last_attempt_got_server_pushback = true;
1380 } else {
1381 if (calld->num_attempts_completed == 1 ||
1382 calld->last_attempt_got_server_pushback) {
1383 calld->retry_backoff.Init(
1384 grpc_core::BackOff::Options()
1385 .set_initial_backoff(retry_policy->initial_backoff)
1386 .set_multiplier(retry_policy->backoff_multiplier)
1387 .set_jitter(RETRY_BACKOFF_JITTER)
1388 .set_max_backoff(retry_policy->max_backoff));
1389 calld->last_attempt_got_server_pushback = false;
1390 }
1391 next_attempt_time = calld->retry_backoff->NextAttemptTime();
1392 }
1393 if (grpc_client_channel_trace.enabled()) {
1394 gpr_log(GPR_DEBUG,
1395 "chand=%p calld=%p: retrying failed call in %" PRIuPTR " ms", chand,
1396 calld, next_attempt_time - grpc_core::ExecCtx::Get()->Now());
1397 }
1398 // Schedule retry after computed delay.
1399 GRPC_CLOSURE_INIT(&calld->pick_closure, start_pick_locked, elem,
1400 grpc_combiner_scheduler(chand->combiner));
1401 grpc_timer_init(&calld->retry_timer, next_attempt_time, &calld->pick_closure);
1402 // Update bookkeeping.
1403 if (retry_state != nullptr) retry_state->retry_dispatched = true;
1404}
1405
1406// Returns true if the call is being retried.
1407static bool maybe_retry(grpc_call_element* elem,
1408 subchannel_batch_data* batch_data,
1409 grpc_status_code status,
1410 grpc_mdelem* server_pushback_md) {
1411 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1412 call_data* calld = static_cast<call_data*>(elem->call_data);
1413 // Get retry policy.
1414 if (calld->method_params == nullptr) return false;
1415 const ClientChannelMethodParams::RetryPolicy* retry_policy =
1416 calld->method_params->retry_policy();
1417 if (retry_policy == nullptr) return false;
1418 // If we've already dispatched a retry from this call, return true.
1419 // This catches the case where the batch has multiple callbacks
1420 // (i.e., it includes either recv_message or recv_initial_metadata).
1421 subchannel_call_retry_state* retry_state = nullptr;
1422 if (batch_data != nullptr) {
1423 retry_state = static_cast<subchannel_call_retry_state*>(
1424 grpc_connected_subchannel_call_get_parent_data(
1425 batch_data->subchannel_call));
1426 if (retry_state->retry_dispatched) {
1427 if (grpc_client_channel_trace.enabled()) {
1428 gpr_log(GPR_DEBUG, "chand=%p calld=%p: retry already dispatched", chand,
1429 calld);
1430 }
1431 return true;
1432 }
1433 }
1434 // Check status.
1435 if (status == GRPC_STATUS_OK) {
1436 grpc_server_retry_throttle_data_record_success(calld->retry_throttle_data);
1437 if (grpc_client_channel_trace.enabled()) {
1438 gpr_log(GPR_DEBUG, "chand=%p calld=%p: call succeeded", chand, calld);
1439 }
1440 return false;
1441 }
1442 // Status is not OK. Check whether the status is retryable.
1443 if (!retry_policy->retryable_status_codes.Contains(status)) {
1444 if (grpc_client_channel_trace.enabled()) {
1445 gpr_log(GPR_DEBUG,
1446 "chand=%p calld=%p: status %s not configured as retryable", chand,
1447 calld, grpc_status_code_to_string(status));
1448 }
1449 return false;
1450 }
1451 // Record the failure and check whether retries are throttled.
1452 // Note that it's important for this check to come after the status
1453 // code check above, since we should only record failures whose statuses
1454 // match the configured retryable status codes, so that we don't count
1455 // things like failures due to malformed requests (INVALID_ARGUMENT).
1456 // Conversely, it's important for this to come before the remaining
1457 // checks, so that we don't fail to record failures due to other factors.
1458 if (!grpc_server_retry_throttle_data_record_failure(
1459 calld->retry_throttle_data)) {
1460 if (grpc_client_channel_trace.enabled()) {
1461 gpr_log(GPR_DEBUG, "chand=%p calld=%p: retries throttled", chand, calld);
1462 }
1463 return false;
1464 }
1465 // Check whether the call is committed.
1466 if (calld->retry_committed) {
1467 if (grpc_client_channel_trace.enabled()) {
1468 gpr_log(GPR_DEBUG, "chand=%p calld=%p: retries already committed", chand,
1469 calld);
1470 }
1471 return false;
1472 }
1473 // Check whether we have retries remaining.
1474 ++calld->num_attempts_completed;
1475 if (calld->num_attempts_completed >= retry_policy->max_attempts) {
1476 if (grpc_client_channel_trace.enabled()) {
1477 gpr_log(GPR_DEBUG, "chand=%p calld=%p: exceeded %d retry attempts", chand,
1478 calld, retry_policy->max_attempts);
1479 }
1480 return false;
1481 }
1482 // If the call was cancelled from the surface, don't retry.
1483 if (calld->cancel_error != GRPC_ERROR_NONE) {
1484 if (grpc_client_channel_trace.enabled()) {
1485 gpr_log(GPR_DEBUG,
1486 "chand=%p calld=%p: call cancelled from surface, not retrying",
1487 chand, calld);
1488 }
1489 return false;
1490 }
1491 // Check server push-back.
1492 grpc_millis server_pushback_ms = -1;
1493 if (server_pushback_md != nullptr) {
1494 // If the value is "-1" or any other unparseable string, we do not retry.
1495 uint32_t ms;
1496 if (!grpc_parse_slice_to_uint32(GRPC_MDVALUE(*server_pushback_md), &ms)) {
1497 if (grpc_client_channel_trace.enabled()) {
1498 gpr_log(GPR_DEBUG,
1499 "chand=%p calld=%p: not retrying due to server push-back",
1500 chand, calld);
1501 }
1502 return false;
1503 } else {
1504 if (grpc_client_channel_trace.enabled()) {
1505 gpr_log(GPR_DEBUG,
1506 "chand=%p calld=%p: server push-back: retry in %u ms", chand,
1507 calld, ms);
1508 }
1509 server_pushback_ms = (grpc_millis)ms;
1510 }
1511 }
1512 do_retry(elem, retry_state, server_pushback_ms);
1513 return true;
1514}
1515
1516//
1517// subchannel_batch_data
1518//
1519
1520static subchannel_batch_data* batch_data_create(grpc_call_element* elem,
1521 int refcount) {
1522 call_data* calld = static_cast<call_data*>(elem->call_data);
1523 subchannel_call_retry_state* retry_state =
1524 static_cast<subchannel_call_retry_state*>(
1525 grpc_connected_subchannel_call_get_parent_data(
1526 calld->subchannel_call));
1527 subchannel_batch_data* batch_data = static_cast<subchannel_batch_data*>(
1528 gpr_arena_alloc(calld->arena, sizeof(*batch_data)));
1529 batch_data->elem = elem;
1530 batch_data->subchannel_call =
1531 GRPC_SUBCHANNEL_CALL_REF(calld->subchannel_call, "batch_data_create");
1532 batch_data->batch.payload = &retry_state->batch_payload;
1533 gpr_ref_init(&batch_data->refs, refcount);
1534 GRPC_CLOSURE_INIT(&batch_data->on_complete, on_complete, batch_data,
1535 grpc_schedule_on_exec_ctx);
1536 batch_data->batch.on_complete = &batch_data->on_complete;
1537 GRPC_CALL_STACK_REF(calld->owning_call, "batch_data");
1538 return batch_data;
1539}
1540
1541static void batch_data_unref(subchannel_batch_data* batch_data) {
1542 if (gpr_unref(&batch_data->refs)) {
1543 if (batch_data->send_initial_metadata_storage != nullptr) {
1544 grpc_metadata_batch_destroy(&batch_data->send_initial_metadata);
1545 }
1546 if (batch_data->send_trailing_metadata_storage != nullptr) {
1547 grpc_metadata_batch_destroy(&batch_data->send_trailing_metadata);
1548 }
1549 if (batch_data->batch.recv_initial_metadata) {
1550 grpc_metadata_batch_destroy(&batch_data->recv_initial_metadata);
1551 }
1552 if (batch_data->batch.recv_trailing_metadata) {
1553 grpc_metadata_batch_destroy(&batch_data->recv_trailing_metadata);
1554 }
1555 GRPC_SUBCHANNEL_CALL_UNREF(batch_data->subchannel_call, "batch_data_unref");
1556 call_data* calld = static_cast<call_data*>(batch_data->elem->call_data);
1557 GRPC_CALL_STACK_UNREF(calld->owning_call, "batch_data");
1558 }
1559}
1560
1561//
1562// recv_initial_metadata callback handling
1563//
1564
1565// Invokes recv_initial_metadata_ready for a subchannel batch.
1566static void invoke_recv_initial_metadata_callback(void* arg,
1567 grpc_error* error) {
1568 subchannel_batch_data* batch_data = static_cast<subchannel_batch_data*>(arg);
1569 channel_data* chand =
1570 static_cast<channel_data*>(batch_data->elem->channel_data);
1571 call_data* calld = static_cast<call_data*>(batch_data->elem->call_data);
1572 // Find pending batch.
1573 pending_batch* pending = nullptr;
1574 for (size_t i = 0; i < GPR_ARRAY_SIZE(calld->pending_batches); ++i) {
1575 grpc_transport_stream_op_batch* batch = calld->pending_batches[i].batch;
1576 if (batch != nullptr && batch->recv_initial_metadata &&
1577 batch->payload->recv_initial_metadata.recv_initial_metadata_ready !=
1578 nullptr) {
1579 if (grpc_client_channel_trace.enabled()) {
1580 gpr_log(GPR_DEBUG,
1581 "chand=%p calld=%p: invoking recv_initial_metadata_ready for "
1582 "pending batch at index %" PRIuPTR,
1583 chand, calld, i);
1584 }
1585 pending = &calld->pending_batches[i];
1586 break;
1587 }
1588 }
1589 GPR_ASSERT(pending != nullptr);
1590 // Return metadata.
1591 grpc_metadata_batch_move(
1592 &batch_data->recv_initial_metadata,
1593 pending->batch->payload->recv_initial_metadata.recv_initial_metadata);
1594 // Update bookkeeping.
1595 // Note: Need to do this before invoking the callback, since invoking
1596 // the callback will result in yielding the call combiner.
1597 grpc_closure* recv_initial_metadata_ready =
1598 pending->batch->payload->recv_initial_metadata
1599 .recv_initial_metadata_ready;
1600 pending->batch->payload->recv_initial_metadata.recv_initial_metadata_ready =
1601 nullptr;
1602 maybe_clear_pending_batch(batch_data->elem, pending);
1603 batch_data_unref(batch_data);
1604 // Invoke callback.
1605 GRPC_CLOSURE_RUN(recv_initial_metadata_ready, GRPC_ERROR_REF(error));
1606}
1607
1608// Intercepts recv_initial_metadata_ready callback for retries.
1609// Commits the call and returns the initial metadata up the stack.
1610static void recv_initial_metadata_ready(void* arg, grpc_error* error) {
1611 subchannel_batch_data* batch_data = static_cast<subchannel_batch_data*>(arg);
1612 grpc_call_element* elem = batch_data->elem;
1613 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1614 call_data* calld = static_cast<call_data*>(elem->call_data);
1615 if (grpc_client_channel_trace.enabled()) {
1616 gpr_log(GPR_DEBUG,
1617 "chand=%p calld=%p: got recv_initial_metadata_ready, error=%s",
1618 chand, calld, grpc_error_string(error));
1619 }
1620 subchannel_call_retry_state* retry_state =
1621 static_cast<subchannel_call_retry_state*>(
1622 grpc_connected_subchannel_call_get_parent_data(
1623 batch_data->subchannel_call));
1624 // If we got an error or a Trailers-Only response and have not yet gotten
1625 // the recv_trailing_metadata on_complete callback, then defer
1626 // propagating this callback back to the surface. We can evaluate whether
1627 // to retry when recv_trailing_metadata comes back.
1628 if ((batch_data->trailing_metadata_available || error != GRPC_ERROR_NONE) &&
1629 !retry_state->completed_recv_trailing_metadata) {
1630 if (grpc_client_channel_trace.enabled()) {
1631 gpr_log(GPR_DEBUG,
1632 "chand=%p calld=%p: deferring recv_initial_metadata_ready "
1633 "(Trailers-Only)",
1634 chand, calld);
1635 }
1636 retry_state->recv_initial_metadata_ready_deferred = true;
1637 retry_state->recv_initial_metadata_error = GRPC_ERROR_REF(error);
1638 if (!retry_state->started_recv_trailing_metadata) {
1639 // recv_trailing_metadata not yet started by application; start it
1640 // ourselves to get status.
1641 start_internal_recv_trailing_metadata(elem);
1642 } else {
1643 GRPC_CALL_COMBINER_STOP(
1644 calld->call_combiner,
1645 "recv_initial_metadata_ready trailers-only or error");
1646 }
1647 return;
1648 }
1649 // Received valid initial metadata, so commit the call.
1650 retry_commit(elem, retry_state);
1651 // Manually invoking a callback function; it does not take ownership of error.
1652 invoke_recv_initial_metadata_callback(batch_data, error);
1653 GRPC_ERROR_UNREF(error);
1654}
1655
1656//
1657// recv_message callback handling
1658//
1659
1660// Invokes recv_message_ready for a subchannel batch.
1661static void invoke_recv_message_callback(void* arg, grpc_error* error) {
1662 subchannel_batch_data* batch_data = static_cast<subchannel_batch_data*>(arg);
1663 channel_data* chand =
1664 static_cast<channel_data*>(batch_data->elem->channel_data);
1665 call_data* calld = static_cast<call_data*>(batch_data->elem->call_data);
1666 // Find pending op.
1667 pending_batch* pending = nullptr;
1668 for (size_t i = 0; i < GPR_ARRAY_SIZE(calld->pending_batches); ++i) {
1669 grpc_transport_stream_op_batch* batch = calld->pending_batches[i].batch;
1670 if (batch != nullptr && batch->recv_message &&
1671 batch->payload->recv_message.recv_message_ready != nullptr) {
1672 if (grpc_client_channel_trace.enabled()) {
1673 gpr_log(GPR_DEBUG,
1674 "chand=%p calld=%p: invoking recv_message_ready for "
1675 "pending batch at index %" PRIuPTR,
1676 chand, calld, i);
1677 }
1678 pending = &calld->pending_batches[i];
1679 break;
1680 }
1681 }
1682 GPR_ASSERT(pending != nullptr);
1683 // Return payload.
1684 *pending->batch->payload->recv_message.recv_message =
Mark D. Roth3d8b32d2018-03-09 13:25:40 -08001685 std::move(batch_data->recv_message);
Mark D. Roth718c8342018-02-28 13:00:04 -08001686 // Update bookkeeping.
1687 // Note: Need to do this before invoking the callback, since invoking
1688 // the callback will result in yielding the call combiner.
1689 grpc_closure* recv_message_ready =
1690 pending->batch->payload->recv_message.recv_message_ready;
1691 pending->batch->payload->recv_message.recv_message_ready = nullptr;
1692 maybe_clear_pending_batch(batch_data->elem, pending);
1693 batch_data_unref(batch_data);
1694 // Invoke callback.
1695 GRPC_CLOSURE_RUN(recv_message_ready, GRPC_ERROR_REF(error));
1696}
1697
1698// Intercepts recv_message_ready callback for retries.
1699// Commits the call and returns the message up the stack.
1700static void recv_message_ready(void* arg, grpc_error* error) {
1701 subchannel_batch_data* batch_data = static_cast<subchannel_batch_data*>(arg);
1702 grpc_call_element* elem = batch_data->elem;
1703 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1704 call_data* calld = static_cast<call_data*>(elem->call_data);
1705 if (grpc_client_channel_trace.enabled()) {
1706 gpr_log(GPR_DEBUG, "chand=%p calld=%p: got recv_message_ready, error=%s",
1707 chand, calld, grpc_error_string(error));
1708 }
1709 subchannel_call_retry_state* retry_state =
1710 static_cast<subchannel_call_retry_state*>(
1711 grpc_connected_subchannel_call_get_parent_data(
1712 batch_data->subchannel_call));
1713 // If we got an error or the payload was nullptr and we have not yet gotten
1714 // the recv_trailing_metadata on_complete callback, then defer
1715 // propagating this callback back to the surface. We can evaluate whether
1716 // to retry when recv_trailing_metadata comes back.
1717 if ((batch_data->recv_message == nullptr || error != GRPC_ERROR_NONE) &&
1718 !retry_state->completed_recv_trailing_metadata) {
1719 if (grpc_client_channel_trace.enabled()) {
1720 gpr_log(GPR_DEBUG,
1721 "chand=%p calld=%p: deferring recv_message_ready (nullptr "
1722 "message and recv_trailing_metadata pending)",
1723 chand, calld);
1724 }
1725 retry_state->recv_message_ready_deferred = true;
1726 retry_state->recv_message_error = GRPC_ERROR_REF(error);
1727 if (!retry_state->started_recv_trailing_metadata) {
1728 // recv_trailing_metadata not yet started by application; start it
1729 // ourselves to get status.
1730 start_internal_recv_trailing_metadata(elem);
1731 } else {
1732 GRPC_CALL_COMBINER_STOP(calld->call_combiner, "recv_message_ready null");
1733 }
1734 return;
1735 }
1736 // Received a valid message, so commit the call.
1737 retry_commit(elem, retry_state);
1738 // Manually invoking a callback function; it does not take ownership of error.
1739 invoke_recv_message_callback(batch_data, error);
1740 GRPC_ERROR_UNREF(error);
1741}
1742
1743//
1744// on_complete callback handling
1745//
1746
1747// Updates retry_state to reflect the ops completed in batch_data.
1748static void update_retry_state_for_completed_batch(
1749 subchannel_batch_data* batch_data,
1750 subchannel_call_retry_state* retry_state) {
1751 if (batch_data->batch.send_initial_metadata) {
1752 retry_state->completed_send_initial_metadata = true;
1753 }
1754 if (batch_data->batch.send_message) {
1755 ++retry_state->completed_send_message_count;
1756 }
1757 if (batch_data->batch.send_trailing_metadata) {
1758 retry_state->completed_send_trailing_metadata = true;
1759 }
1760 if (batch_data->batch.recv_initial_metadata) {
1761 retry_state->completed_recv_initial_metadata = true;
1762 }
1763 if (batch_data->batch.recv_message) {
1764 ++retry_state->completed_recv_message_count;
1765 }
1766 if (batch_data->batch.recv_trailing_metadata) {
1767 retry_state->completed_recv_trailing_metadata = true;
1768 }
1769}
1770
1771// Represents a closure that needs to run as a result of a completed batch.
1772typedef struct {
1773 grpc_closure* closure;
1774 grpc_error* error;
1775 const char* reason;
1776} closure_to_execute;
1777
1778// Adds any necessary closures for deferred recv_initial_metadata and
1779// recv_message callbacks to closures, updating *num_closures as needed.
1780static void add_closures_for_deferred_recv_callbacks(
1781 subchannel_batch_data* batch_data, subchannel_call_retry_state* retry_state,
1782 closure_to_execute* closures, size_t* num_closures) {
1783 if (batch_data->batch.recv_trailing_metadata &&
1784 retry_state->recv_initial_metadata_ready_deferred) {
1785 closure_to_execute* closure = &closures[(*num_closures)++];
1786 closure->closure =
1787 GRPC_CLOSURE_INIT(&batch_data->recv_initial_metadata_ready,
1788 invoke_recv_initial_metadata_callback, batch_data,
1789 grpc_schedule_on_exec_ctx);
1790 closure->error = retry_state->recv_initial_metadata_error;
1791 closure->reason = "resuming recv_initial_metadata_ready";
1792 }
1793 if (batch_data->batch.recv_trailing_metadata &&
1794 retry_state->recv_message_ready_deferred) {
1795 closure_to_execute* closure = &closures[(*num_closures)++];
1796 closure->closure = GRPC_CLOSURE_INIT(&batch_data->recv_message_ready,
1797 invoke_recv_message_callback,
1798 batch_data, grpc_schedule_on_exec_ctx);
1799 closure->error = retry_state->recv_message_error;
1800 closure->reason = "resuming recv_message_ready";
1801 }
1802}
1803
1804// If there are any cached ops to replay or pending ops to start on the
1805// subchannel call, adds a closure to closures to invoke
1806// start_retriable_subchannel_batches(), updating *num_closures as needed.
1807static void add_closures_for_replay_or_pending_send_ops(
1808 grpc_call_element* elem, subchannel_batch_data* batch_data,
1809 subchannel_call_retry_state* retry_state, closure_to_execute* closures,
1810 size_t* num_closures) {
1811 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1812 call_data* calld = static_cast<call_data*>(elem->call_data);
1813 bool have_pending_send_message_ops =
1814 retry_state->started_send_message_count < calld->send_messages.size();
1815 bool have_pending_send_trailing_metadata_op =
1816 calld->seen_send_trailing_metadata &&
1817 !retry_state->started_send_trailing_metadata;
1818 if (!have_pending_send_message_ops &&
1819 !have_pending_send_trailing_metadata_op) {
1820 for (size_t i = 0; i < GPR_ARRAY_SIZE(calld->pending_batches); ++i) {
1821 pending_batch* pending = &calld->pending_batches[i];
1822 grpc_transport_stream_op_batch* batch = pending->batch;
1823 if (batch == nullptr || pending->send_ops_cached) continue;
1824 if (batch->send_message) have_pending_send_message_ops = true;
1825 if (batch->send_trailing_metadata) {
1826 have_pending_send_trailing_metadata_op = true;
1827 }
1828 }
1829 }
1830 if (have_pending_send_message_ops || have_pending_send_trailing_metadata_op) {
1831 if (grpc_client_channel_trace.enabled()) {
1832 gpr_log(GPR_DEBUG,
1833 "chand=%p calld=%p: starting next batch for pending send op(s)",
1834 chand, calld);
1835 }
1836 closure_to_execute* closure = &closures[(*num_closures)++];
1837 closure->closure = GRPC_CLOSURE_INIT(
1838 &batch_data->batch.handler_private.closure,
1839 start_retriable_subchannel_batches, elem, grpc_schedule_on_exec_ctx);
1840 closure->error = GRPC_ERROR_NONE;
1841 closure->reason = "starting next batch for send_* op(s)";
1842 }
1843}
1844
1845// For any pending batch completed in batch_data, adds the necessary
1846// completion closures to closures, updating *num_closures as needed.
1847static void add_closures_for_completed_pending_batches(
1848 grpc_call_element* elem, subchannel_batch_data* batch_data,
1849 subchannel_call_retry_state* retry_state, grpc_error* error,
1850 closure_to_execute* closures, size_t* num_closures) {
1851 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1852 call_data* calld = static_cast<call_data*>(elem->call_data);
1853 for (size_t i = 0; i < GPR_ARRAY_SIZE(calld->pending_batches); ++i) {
1854 pending_batch* pending = &calld->pending_batches[i];
1855 if (pending_batch_is_completed(pending, calld, retry_state)) {
1856 if (grpc_client_channel_trace.enabled()) {
1857 gpr_log(GPR_DEBUG,
1858 "chand=%p calld=%p: pending batch completed at index %" PRIuPTR,
1859 chand, calld, i);
1860 }
1861 // Copy the trailing metadata to return it to the surface.
1862 if (batch_data->batch.recv_trailing_metadata) {
1863 grpc_metadata_batch_move(&batch_data->recv_trailing_metadata,
1864 pending->batch->payload->recv_trailing_metadata
1865 .recv_trailing_metadata);
1866 }
1867 closure_to_execute* closure = &closures[(*num_closures)++];
1868 closure->closure = pending->batch->on_complete;
1869 closure->error = GRPC_ERROR_REF(error);
1870 closure->reason = "on_complete for pending batch";
1871 pending->batch->on_complete = nullptr;
1872 maybe_clear_pending_batch(elem, pending);
1873 }
1874 }
1875 GRPC_ERROR_UNREF(error);
1876}
1877
1878// For any pending batch containing an op that has not yet been started,
1879// adds the pending batch's completion closures to closures, updating
1880// *num_closures as needed.
1881static void add_closures_to_fail_unstarted_pending_batches(
1882 grpc_call_element* elem, subchannel_call_retry_state* retry_state,
1883 grpc_error* error, closure_to_execute* closures, size_t* num_closures) {
1884 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1885 call_data* calld = static_cast<call_data*>(elem->call_data);
1886 for (size_t i = 0; i < GPR_ARRAY_SIZE(calld->pending_batches); ++i) {
1887 pending_batch* pending = &calld->pending_batches[i];
1888 if (pending_batch_is_unstarted(pending, calld, retry_state)) {
1889 if (grpc_client_channel_trace.enabled()) {
1890 gpr_log(GPR_DEBUG,
1891 "chand=%p calld=%p: failing unstarted pending batch at index "
1892 "%" PRIuPTR,
1893 chand, calld, i);
1894 }
1895 if (pending->batch->recv_initial_metadata) {
1896 closure_to_execute* closure = &closures[(*num_closures)++];
1897 closure->closure = pending->batch->payload->recv_initial_metadata
1898 .recv_initial_metadata_ready;
1899 closure->error = GRPC_ERROR_REF(error);
1900 closure->reason =
1901 "failing recv_initial_metadata_ready for pending batch";
1902 pending->batch->payload->recv_initial_metadata
1903 .recv_initial_metadata_ready = nullptr;
1904 }
1905 if (pending->batch->recv_message) {
1906 *pending->batch->payload->recv_message.recv_message = nullptr;
1907 closure_to_execute* closure = &closures[(*num_closures)++];
1908 closure->closure =
1909 pending->batch->payload->recv_message.recv_message_ready;
1910 closure->error = GRPC_ERROR_REF(error);
1911 closure->reason = "failing recv_message_ready for pending batch";
1912 pending->batch->payload->recv_message.recv_message_ready = nullptr;
1913 }
1914 closure_to_execute* closure = &closures[(*num_closures)++];
1915 closure->closure = pending->batch->on_complete;
1916 closure->error = GRPC_ERROR_REF(error);
1917 closure->reason = "failing on_complete for pending batch";
1918 pending->batch->on_complete = nullptr;
1919 maybe_clear_pending_batch(elem, pending);
1920 }
1921 }
1922 GRPC_ERROR_UNREF(error);
1923}
1924
1925// Callback used to intercept on_complete from subchannel calls.
1926// Called only when retries are enabled.
1927static void on_complete(void* arg, grpc_error* error) {
1928 subchannel_batch_data* batch_data = static_cast<subchannel_batch_data*>(arg);
1929 grpc_call_element* elem = batch_data->elem;
1930 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
1931 call_data* calld = static_cast<call_data*>(elem->call_data);
1932 if (grpc_client_channel_trace.enabled()) {
1933 char* batch_str = grpc_transport_stream_op_batch_string(&batch_data->batch);
1934 gpr_log(GPR_DEBUG, "chand=%p calld=%p: got on_complete, error=%s, batch=%s",
1935 chand, calld, grpc_error_string(error), batch_str);
1936 gpr_free(batch_str);
1937 }
1938 subchannel_call_retry_state* retry_state =
1939 static_cast<subchannel_call_retry_state*>(
1940 grpc_connected_subchannel_call_get_parent_data(
1941 batch_data->subchannel_call));
1942 // If we have previously completed recv_trailing_metadata, then the
1943 // call is finished.
1944 bool call_finished = retry_state->completed_recv_trailing_metadata;
1945 // Update bookkeeping in retry_state.
1946 update_retry_state_for_completed_batch(batch_data, retry_state);
1947 if (call_finished) {
1948 if (grpc_client_channel_trace.enabled()) {
1949 gpr_log(GPR_DEBUG, "chand=%p calld=%p: call already finished", chand,
1950 calld);
1951 }
1952 } else {
1953 // Check if this batch finished the call, and if so, get its status.
1954 // The call is finished if either (a) this callback was invoked with
1955 // an error or (b) we receive status.
1956 grpc_status_code status = GRPC_STATUS_OK;
1957 grpc_mdelem* server_pushback_md = nullptr;
1958 if (error != GRPC_ERROR_NONE) { // Case (a).
1959 call_finished = true;
1960 grpc_error_get_status(error, calld->deadline, &status, nullptr, nullptr,
1961 nullptr);
1962 } else if (batch_data->batch.recv_trailing_metadata) { // Case (b).
1963 call_finished = true;
1964 grpc_metadata_batch* md_batch =
1965 batch_data->batch.payload->recv_trailing_metadata
1966 .recv_trailing_metadata;
1967 GPR_ASSERT(md_batch->idx.named.grpc_status != nullptr);
1968 status = grpc_get_status_code_from_metadata(
1969 md_batch->idx.named.grpc_status->md);
1970 if (md_batch->idx.named.grpc_retry_pushback_ms != nullptr) {
1971 server_pushback_md = &md_batch->idx.named.grpc_retry_pushback_ms->md;
1972 }
1973 } else if (retry_state->completed_recv_trailing_metadata) {
1974 call_finished = true;
1975 }
1976 if (call_finished && grpc_client_channel_trace.enabled()) {
1977 gpr_log(GPR_DEBUG, "chand=%p calld=%p: call finished, status=%s", chand,
1978 calld, grpc_status_code_to_string(status));
1979 }
1980 // If the call is finished, check if we should retry.
1981 if (call_finished &&
1982 maybe_retry(elem, batch_data, status, server_pushback_md)) {
1983 // Unref batch_data for deferred recv_initial_metadata_ready or
1984 // recv_message_ready callbacks, if any.
1985 if (batch_data->batch.recv_trailing_metadata &&
1986 retry_state->recv_initial_metadata_ready_deferred) {
1987 batch_data_unref(batch_data);
1988 GRPC_ERROR_UNREF(retry_state->recv_initial_metadata_error);
1989 }
1990 if (batch_data->batch.recv_trailing_metadata &&
1991 retry_state->recv_message_ready_deferred) {
1992 batch_data_unref(batch_data);
1993 GRPC_ERROR_UNREF(retry_state->recv_message_error);
1994 }
1995 batch_data_unref(batch_data);
1996 return;
1997 }
1998 }
1999 // If the call is finished or retries are committed, free cached data for
2000 // send ops that we've just completed.
2001 if (call_finished || calld->retry_committed) {
2002 free_cached_send_op_data_for_completed_batch(elem, batch_data, retry_state);
2003 }
2004 // Call not being retried.
2005 // Construct list of closures to execute.
2006 // Max number of closures is number of pending batches plus one for
2007 // each of:
2008 // - recv_initial_metadata_ready (either deferred or unstarted)
2009 // - recv_message_ready (either deferred or unstarted)
2010 // - starting a new batch for pending send ops
2011 closure_to_execute closures[GPR_ARRAY_SIZE(calld->pending_batches) + 3];
2012 size_t num_closures = 0;
2013 // If there are deferred recv_initial_metadata_ready or recv_message_ready
2014 // callbacks, add them to closures.
2015 add_closures_for_deferred_recv_callbacks(batch_data, retry_state, closures,
2016 &num_closures);
2017 // Find pending batches whose ops are now complete and add their
2018 // on_complete callbacks to closures.
2019 add_closures_for_completed_pending_batches(elem, batch_data, retry_state,
2020 GRPC_ERROR_REF(error), closures,
2021 &num_closures);
2022 // Add closures to handle any pending batches that have not yet been started.
2023 // If the call is finished, we fail these batches; otherwise, we add a
2024 // callback to start_retriable_subchannel_batches() to start them on
2025 // the subchannel call.
2026 if (call_finished) {
2027 add_closures_to_fail_unstarted_pending_batches(
2028 elem, retry_state, GRPC_ERROR_REF(error), closures, &num_closures);
2029 } else {
2030 add_closures_for_replay_or_pending_send_ops(elem, batch_data, retry_state,
2031 closures, &num_closures);
2032 }
2033 // Don't need batch_data anymore.
2034 batch_data_unref(batch_data);
2035 // Schedule all of the closures identified above.
2036 // Note that the call combiner will be yielded for each closure that
2037 // we schedule. We're already running in the call combiner, so one of
2038 // the closures can be scheduled directly, but the others will
2039 // have to re-enter the call combiner.
2040 if (num_closures > 0) {
2041 GRPC_CLOSURE_SCHED(closures[0].closure, closures[0].error);
2042 for (size_t i = 1; i < num_closures; ++i) {
2043 GRPC_CALL_COMBINER_START(calld->call_combiner, closures[i].closure,
2044 closures[i].error, closures[i].reason);
2045 }
2046 } else {
2047 GRPC_CALL_COMBINER_STOP(calld->call_combiner,
2048 "no closures to run for on_complete");
2049 }
2050}
2051
2052//
2053// subchannel batch construction
2054//
2055
2056// Helper function used to start a subchannel batch in the call combiner.
2057static void start_batch_in_call_combiner(void* arg, grpc_error* ignored) {
2058 grpc_transport_stream_op_batch* batch =
2059 static_cast<grpc_transport_stream_op_batch*>(arg);
2060 grpc_subchannel_call* subchannel_call =
2061 static_cast<grpc_subchannel_call*>(batch->handler_private.extra_arg);
2062 // Note: This will release the call combiner.
2063 grpc_subchannel_call_process_op(subchannel_call, batch);
2064}
2065
2066// Adds retriable send_initial_metadata op to batch_data.
2067static void add_retriable_send_initial_metadata_op(
2068 call_data* calld, subchannel_call_retry_state* retry_state,
2069 subchannel_batch_data* batch_data) {
2070 // Maps the number of retries to the corresponding metadata value slice.
2071 static const grpc_slice* retry_count_strings[] = {
2072 &GRPC_MDSTR_1, &GRPC_MDSTR_2, &GRPC_MDSTR_3, &GRPC_MDSTR_4};
2073 // We need to make a copy of the metadata batch for each attempt, since
2074 // the filters in the subchannel stack may modify this batch, and we don't
2075 // want those modifications to be passed forward to subsequent attempts.
2076 //
2077 // If we've already completed one or more attempts, add the
2078 // grpc-retry-attempts header.
2079 batch_data->send_initial_metadata_storage =
2080 static_cast<grpc_linked_mdelem*>(gpr_arena_alloc(
2081 calld->arena, sizeof(grpc_linked_mdelem) *
2082 (calld->send_initial_metadata.list.count +
2083 (calld->num_attempts_completed > 0))));
2084 grpc_metadata_batch_copy(&calld->send_initial_metadata,
2085 &batch_data->send_initial_metadata,
2086 batch_data->send_initial_metadata_storage);
2087 if (batch_data->send_initial_metadata.idx.named.grpc_previous_rpc_attempts !=
2088 nullptr) {
2089 grpc_metadata_batch_remove(
2090 &batch_data->send_initial_metadata,
2091 batch_data->send_initial_metadata.idx.named.grpc_previous_rpc_attempts);
2092 }
2093 if (calld->num_attempts_completed > 0) {
2094 grpc_mdelem retry_md = grpc_mdelem_from_slices(
2095 GRPC_MDSTR_GRPC_PREVIOUS_RPC_ATTEMPTS,
2096 *retry_count_strings[calld->num_attempts_completed - 1]);
2097 grpc_error* error = grpc_metadata_batch_add_tail(
2098 &batch_data->send_initial_metadata,
2099 &batch_data->send_initial_metadata_storage[calld->send_initial_metadata
2100 .list.count],
2101 retry_md);
2102 if (error != GRPC_ERROR_NONE) {
2103 gpr_log(GPR_ERROR, "error adding retry metadata: %s",
2104 grpc_error_string(error));
2105 GPR_ASSERT(false);
2106 }
2107 }
2108 retry_state->started_send_initial_metadata = true;
2109 batch_data->batch.send_initial_metadata = true;
2110 batch_data->batch.payload->send_initial_metadata.send_initial_metadata =
2111 &batch_data->send_initial_metadata;
2112 batch_data->batch.payload->send_initial_metadata.send_initial_metadata_flags =
2113 calld->send_initial_metadata_flags;
2114 batch_data->batch.payload->send_initial_metadata.peer_string =
2115 calld->peer_string;
2116}
2117
2118// Adds retriable send_message op to batch_data.
2119static void add_retriable_send_message_op(
2120 grpc_call_element* elem, subchannel_call_retry_state* retry_state,
2121 subchannel_batch_data* batch_data) {
2122 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2123 call_data* calld = static_cast<call_data*>(elem->call_data);
2124 if (grpc_client_channel_trace.enabled()) {
2125 gpr_log(GPR_DEBUG,
2126 "chand=%p calld=%p: starting calld->send_messages[%" PRIuPTR "]",
2127 chand, calld, retry_state->started_send_message_count);
2128 }
Mark D. Roth3d8b32d2018-03-09 13:25:40 -08002129 grpc_core::ByteStreamCache* cache =
Mark D. Roth718c8342018-02-28 13:00:04 -08002130 calld->send_messages[retry_state->started_send_message_count];
2131 ++retry_state->started_send_message_count;
Mark D. Roth3d8b32d2018-03-09 13:25:40 -08002132 batch_data->send_message.Init(cache);
Mark D. Roth718c8342018-02-28 13:00:04 -08002133 batch_data->batch.send_message = true;
Mark D. Roth3d8b32d2018-03-09 13:25:40 -08002134 batch_data->batch.payload->send_message.send_message.reset(
2135 batch_data->send_message.get());
Mark D. Roth718c8342018-02-28 13:00:04 -08002136}
2137
2138// Adds retriable send_trailing_metadata op to batch_data.
2139static void add_retriable_send_trailing_metadata_op(
2140 call_data* calld, subchannel_call_retry_state* retry_state,
2141 subchannel_batch_data* batch_data) {
2142 // We need to make a copy of the metadata batch for each attempt, since
2143 // the filters in the subchannel stack may modify this batch, and we don't
2144 // want those modifications to be passed forward to subsequent attempts.
2145 batch_data->send_trailing_metadata_storage =
2146 static_cast<grpc_linked_mdelem*>(gpr_arena_alloc(
2147 calld->arena, sizeof(grpc_linked_mdelem) *
2148 calld->send_trailing_metadata.list.count));
2149 grpc_metadata_batch_copy(&calld->send_trailing_metadata,
2150 &batch_data->send_trailing_metadata,
2151 batch_data->send_trailing_metadata_storage);
2152 retry_state->started_send_trailing_metadata = true;
2153 batch_data->batch.send_trailing_metadata = true;
2154 batch_data->batch.payload->send_trailing_metadata.send_trailing_metadata =
2155 &batch_data->send_trailing_metadata;
2156}
2157
2158// Adds retriable recv_initial_metadata op to batch_data.
2159static void add_retriable_recv_initial_metadata_op(
2160 call_data* calld, subchannel_call_retry_state* retry_state,
2161 subchannel_batch_data* batch_data) {
2162 retry_state->started_recv_initial_metadata = true;
2163 batch_data->batch.recv_initial_metadata = true;
2164 grpc_metadata_batch_init(&batch_data->recv_initial_metadata);
2165 batch_data->batch.payload->recv_initial_metadata.recv_initial_metadata =
2166 &batch_data->recv_initial_metadata;
2167 batch_data->batch.payload->recv_initial_metadata.trailing_metadata_available =
2168 &batch_data->trailing_metadata_available;
2169 GRPC_CLOSURE_INIT(&batch_data->recv_initial_metadata_ready,
2170 recv_initial_metadata_ready, batch_data,
2171 grpc_schedule_on_exec_ctx);
2172 batch_data->batch.payload->recv_initial_metadata.recv_initial_metadata_ready =
2173 &batch_data->recv_initial_metadata_ready;
2174}
2175
2176// Adds retriable recv_message op to batch_data.
2177static void add_retriable_recv_message_op(
2178 call_data* calld, subchannel_call_retry_state* retry_state,
2179 subchannel_batch_data* batch_data) {
2180 ++retry_state->started_recv_message_count;
2181 batch_data->batch.recv_message = true;
2182 batch_data->batch.payload->recv_message.recv_message =
2183 &batch_data->recv_message;
2184 GRPC_CLOSURE_INIT(&batch_data->recv_message_ready, recv_message_ready,
2185 batch_data, grpc_schedule_on_exec_ctx);
2186 batch_data->batch.payload->recv_message.recv_message_ready =
2187 &batch_data->recv_message_ready;
2188}
2189
2190// Adds retriable recv_trailing_metadata op to batch_data.
2191static void add_retriable_recv_trailing_metadata_op(
2192 call_data* calld, subchannel_call_retry_state* retry_state,
2193 subchannel_batch_data* batch_data) {
2194 retry_state->started_recv_trailing_metadata = true;
2195 batch_data->batch.recv_trailing_metadata = true;
2196 grpc_metadata_batch_init(&batch_data->recv_trailing_metadata);
2197 batch_data->batch.payload->recv_trailing_metadata.recv_trailing_metadata =
2198 &batch_data->recv_trailing_metadata;
2199 batch_data->batch.collect_stats = true;
2200 batch_data->batch.payload->collect_stats.collect_stats =
2201 &batch_data->collect_stats;
2202}
2203
2204// Helper function used to start a recv_trailing_metadata batch. This
2205// is used in the case where a recv_initial_metadata or recv_message
2206// op fails in a way that we know the call is over but when the application
2207// has not yet started its own recv_trailing_metadata op.
2208static void start_internal_recv_trailing_metadata(grpc_call_element* elem) {
2209 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2210 call_data* calld = static_cast<call_data*>(elem->call_data);
2211 if (grpc_client_channel_trace.enabled()) {
2212 gpr_log(GPR_DEBUG,
2213 "chand=%p calld=%p: call failed but recv_trailing_metadata not "
2214 "started; starting it internally",
2215 chand, calld);
2216 }
2217 subchannel_call_retry_state* retry_state =
2218 static_cast<subchannel_call_retry_state*>(
2219 grpc_connected_subchannel_call_get_parent_data(
2220 calld->subchannel_call));
2221 subchannel_batch_data* batch_data = batch_data_create(elem, 1);
2222 add_retriable_recv_trailing_metadata_op(calld, retry_state, batch_data);
2223 // Note: This will release the call combiner.
2224 grpc_subchannel_call_process_op(calld->subchannel_call, &batch_data->batch);
2225}
2226
2227// If there are any cached send ops that need to be replayed on the
2228// current subchannel call, creates and returns a new subchannel batch
2229// to replay those ops. Otherwise, returns nullptr.
2230static subchannel_batch_data* maybe_create_subchannel_batch_for_replay(
2231 grpc_call_element* elem, subchannel_call_retry_state* retry_state) {
2232 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2233 call_data* calld = static_cast<call_data*>(elem->call_data);
2234 subchannel_batch_data* replay_batch_data = nullptr;
2235 // send_initial_metadata.
2236 if (calld->seen_send_initial_metadata &&
2237 !retry_state->started_send_initial_metadata &&
2238 !calld->pending_send_initial_metadata) {
2239 if (grpc_client_channel_trace.enabled()) {
2240 gpr_log(GPR_DEBUG,
2241 "chand=%p calld=%p: replaying previously completed "
2242 "send_initial_metadata op",
2243 chand, calld);
2244 }
2245 replay_batch_data = batch_data_create(elem, 1);
2246 add_retriable_send_initial_metadata_op(calld, retry_state,
2247 replay_batch_data);
2248 }
2249 // send_message.
2250 // Note that we can only have one send_message op in flight at a time.
2251 if (retry_state->started_send_message_count < calld->send_messages.size() &&
2252 retry_state->started_send_message_count ==
2253 retry_state->completed_send_message_count &&
2254 !calld->pending_send_message) {
2255 if (grpc_client_channel_trace.enabled()) {
2256 gpr_log(GPR_DEBUG,
2257 "chand=%p calld=%p: replaying previously completed "
2258 "send_message op",
2259 chand, calld);
2260 }
2261 if (replay_batch_data == nullptr) {
2262 replay_batch_data = batch_data_create(elem, 1);
2263 }
2264 add_retriable_send_message_op(elem, retry_state, replay_batch_data);
2265 }
2266 // send_trailing_metadata.
2267 // Note that we only add this op if we have no more send_message ops
2268 // to start, since we can't send down any more send_message ops after
2269 // send_trailing_metadata.
2270 if (calld->seen_send_trailing_metadata &&
2271 retry_state->started_send_message_count == calld->send_messages.size() &&
2272 !retry_state->started_send_trailing_metadata &&
2273 !calld->pending_send_trailing_metadata) {
2274 if (grpc_client_channel_trace.enabled()) {
2275 gpr_log(GPR_DEBUG,
2276 "chand=%p calld=%p: replaying previously completed "
2277 "send_trailing_metadata op",
2278 chand, calld);
2279 }
2280 if (replay_batch_data == nullptr) {
2281 replay_batch_data = batch_data_create(elem, 1);
2282 }
2283 add_retriable_send_trailing_metadata_op(calld, retry_state,
2284 replay_batch_data);
2285 }
2286 return replay_batch_data;
2287}
2288
2289// Adds subchannel batches for pending batches to batches, updating
2290// *num_batches as needed.
2291static void add_subchannel_batches_for_pending_batches(
2292 grpc_call_element* elem, subchannel_call_retry_state* retry_state,
2293 grpc_transport_stream_op_batch** batches, size_t* num_batches) {
2294 call_data* calld = static_cast<call_data*>(elem->call_data);
2295 for (size_t i = 0; i < GPR_ARRAY_SIZE(calld->pending_batches); ++i) {
2296 pending_batch* pending = &calld->pending_batches[i];
2297 grpc_transport_stream_op_batch* batch = pending->batch;
2298 if (batch == nullptr) continue;
2299 // Skip any batch that either (a) has already been started on this
2300 // subchannel call or (b) we can't start yet because we're still
2301 // replaying send ops that need to be completed first.
2302 // TODO(roth): Note that if any one op in the batch can't be sent
2303 // yet due to ops that we're replaying, we don't start any of the ops
2304 // in the batch. This is probably okay, but it could conceivably
2305 // lead to increased latency in some cases -- e.g., we could delay
2306 // starting a recv op due to it being in the same batch with a send
2307 // op. If/when we revamp the callback protocol in
2308 // transport_stream_op_batch, we may be able to fix this.
2309 if (batch->send_initial_metadata &&
2310 retry_state->started_send_initial_metadata) {
2311 continue;
2312 }
2313 if (batch->send_message && retry_state->completed_send_message_count <
2314 retry_state->started_send_message_count) {
2315 continue;
2316 }
2317 // Note that we only start send_trailing_metadata if we have no more
2318 // send_message ops to start, since we can't send down any more
2319 // send_message ops after send_trailing_metadata.
2320 if (batch->send_trailing_metadata &&
2321 (retry_state->started_send_message_count + batch->send_message <
2322 calld->send_messages.size() ||
2323 retry_state->started_send_trailing_metadata)) {
2324 continue;
2325 }
2326 if (batch->recv_initial_metadata &&
2327 retry_state->started_recv_initial_metadata) {
2328 continue;
2329 }
2330 if (batch->recv_message && retry_state->completed_recv_message_count <
2331 retry_state->started_recv_message_count) {
2332 continue;
2333 }
2334 if (batch->recv_trailing_metadata &&
2335 retry_state->started_recv_trailing_metadata) {
2336 continue;
2337 }
2338 // If we're not retrying, just send the batch as-is.
2339 if (calld->method_params == nullptr ||
2340 calld->method_params->retry_policy() == nullptr ||
2341 calld->retry_committed) {
2342 batches[(*num_batches)++] = batch;
2343 pending_batch_clear(calld, pending);
2344 continue;
2345 }
2346 // Create batch with the right number of callbacks.
2347 const int num_callbacks =
2348 1 + batch->recv_initial_metadata + batch->recv_message;
2349 subchannel_batch_data* batch_data = batch_data_create(elem, num_callbacks);
2350 // Cache send ops if needed.
2351 maybe_cache_send_ops_for_batch(calld, pending);
2352 // send_initial_metadata.
2353 if (batch->send_initial_metadata) {
2354 add_retriable_send_initial_metadata_op(calld, retry_state, batch_data);
2355 }
2356 // send_message.
2357 if (batch->send_message) {
2358 add_retriable_send_message_op(elem, retry_state, batch_data);
2359 }
2360 // send_trailing_metadata.
2361 if (batch->send_trailing_metadata) {
2362 add_retriable_send_trailing_metadata_op(calld, retry_state, batch_data);
2363 }
2364 // recv_initial_metadata.
2365 if (batch->recv_initial_metadata) {
2366 // recv_flags is only used on the server side.
2367 GPR_ASSERT(batch->payload->recv_initial_metadata.recv_flags == nullptr);
2368 add_retriable_recv_initial_metadata_op(calld, retry_state, batch_data);
2369 }
2370 // recv_message.
2371 if (batch->recv_message) {
2372 add_retriable_recv_message_op(calld, retry_state, batch_data);
2373 }
2374 // recv_trailing_metadata.
2375 if (batch->recv_trailing_metadata) {
2376 GPR_ASSERT(batch->collect_stats);
2377 add_retriable_recv_trailing_metadata_op(calld, retry_state, batch_data);
2378 }
2379 batches[(*num_batches)++] = &batch_data->batch;
2380 }
2381}
2382
2383// Constructs and starts whatever subchannel batches are needed on the
2384// subchannel call.
2385static void start_retriable_subchannel_batches(void* arg, grpc_error* ignored) {
2386 grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
2387 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2388 call_data* calld = static_cast<call_data*>(elem->call_data);
2389 if (grpc_client_channel_trace.enabled()) {
2390 gpr_log(GPR_DEBUG, "chand=%p calld=%p: constructing retriable batches",
2391 chand, calld);
2392 }
2393 subchannel_call_retry_state* retry_state =
2394 static_cast<subchannel_call_retry_state*>(
2395 grpc_connected_subchannel_call_get_parent_data(
2396 calld->subchannel_call));
2397 // We can start up to 6 batches.
2398 grpc_transport_stream_op_batch*
2399 batches[GPR_ARRAY_SIZE(calld->pending_batches)];
2400 size_t num_batches = 0;
2401 // Replay previously-returned send_* ops if needed.
2402 subchannel_batch_data* replay_batch_data =
2403 maybe_create_subchannel_batch_for_replay(elem, retry_state);
2404 if (replay_batch_data != nullptr) {
2405 batches[num_batches++] = &replay_batch_data->batch;
2406 }
2407 // Now add pending batches.
2408 add_subchannel_batches_for_pending_batches(elem, retry_state, batches,
2409 &num_batches);
2410 // Start batches on subchannel call.
2411 // Note that the call combiner will be yielded for each batch that we
2412 // send down. We're already running in the call combiner, so one of
2413 // the batches can be started directly, but the others will have to
2414 // re-enter the call combiner.
2415 if (grpc_client_channel_trace.enabled()) {
2416 gpr_log(GPR_DEBUG,
2417 "chand=%p calld=%p: starting %" PRIuPTR
2418 " retriable batches on subchannel_call=%p",
2419 chand, calld, num_batches, calld->subchannel_call);
2420 }
2421 if (num_batches == 0) {
2422 // This should be fairly rare, but it can happen when (e.g.) an
2423 // attempt completes before it has finished replaying all
2424 // previously sent messages.
2425 GRPC_CALL_COMBINER_STOP(calld->call_combiner,
2426 "no retriable subchannel batches to start");
2427 } else {
2428 for (size_t i = 1; i < num_batches; ++i) {
2429 if (grpc_client_channel_trace.enabled()) {
2430 char* batch_str = grpc_transport_stream_op_batch_string(batches[i]);
2431 gpr_log(GPR_DEBUG,
2432 "chand=%p calld=%p: starting batch in call combiner: %s", chand,
2433 calld, batch_str);
2434 gpr_free(batch_str);
2435 }
2436 batches[i]->handler_private.extra_arg = calld->subchannel_call;
2437 GRPC_CLOSURE_INIT(&batches[i]->handler_private.closure,
2438 start_batch_in_call_combiner, batches[i],
2439 grpc_schedule_on_exec_ctx);
2440 GRPC_CALL_COMBINER_START(calld->call_combiner,
2441 &batches[i]->handler_private.closure,
2442 GRPC_ERROR_NONE, "start_subchannel_batch");
2443 }
2444 if (grpc_client_channel_trace.enabled()) {
2445 char* batch_str = grpc_transport_stream_op_batch_string(batches[0]);
2446 gpr_log(GPR_DEBUG, "chand=%p calld=%p: starting batch: %s", chand, calld,
2447 batch_str);
2448 gpr_free(batch_str);
2449 }
2450 // Note: This will release the call combiner.
2451 grpc_subchannel_call_process_op(calld->subchannel_call, batches[0]);
2452 }
2453}
2454
2455//
2456// LB pick
2457//
2458
2459static void create_subchannel_call(grpc_call_element* elem, grpc_error* error) {
2460 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2461 call_data* calld = static_cast<call_data*>(elem->call_data);
2462 const size_t parent_data_size =
2463 calld->enable_retries ? sizeof(subchannel_call_retry_state) : 0;
David Garcia Quintasbaf1ac72018-01-09 14:24:32 -08002464 const grpc_core::ConnectedSubchannel::CallArgs call_args = {
Mark D. Rothc0febd32018-01-09 10:25:24 -08002465 calld->pollent, // pollent
2466 calld->path, // path
2467 calld->call_start_time, // start_time
2468 calld->deadline, // deadline
2469 calld->arena, // arena
2470 calld->pick.subchannel_call_context, // context
Mark D. Roth718c8342018-02-28 13:00:04 -08002471 calld->call_combiner, // call_combiner
2472 parent_data_size // parent_data_size
Yash Tibrewald8b84a22017-09-25 13:38:03 -07002473 };
David Garcia Quintas70fbe622018-01-09 19:27:46 -08002474 grpc_error* new_error = calld->pick.connected_subchannel->CreateCall(
David Garcia Quintasbaf1ac72018-01-09 14:24:32 -08002475 call_args, &calld->subchannel_call);
Craig Tiller6014e8a2017-10-16 13:50:29 -07002476 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth60751fe2017-07-07 12:50:33 -07002477 gpr_log(GPR_DEBUG, "chand=%p calld=%p: create subchannel_call=%p: error=%s",
Mark D. Roth76e264b2017-08-25 09:03:33 -07002478 chand, calld, calld->subchannel_call, grpc_error_string(new_error));
Mark D. Roth60751fe2017-07-07 12:50:33 -07002479 }
Mark D. Roth0ca0be82017-06-20 07:49:33 -07002480 if (new_error != GRPC_ERROR_NONE) {
2481 new_error = grpc_error_add_child(new_error, error);
Mark D. Roth718c8342018-02-28 13:00:04 -08002482 pending_batches_fail(elem, new_error, true /* yield_call_combiner */);
Mark D. Roth0ca0be82017-06-20 07:49:33 -07002483 } else {
Mark D. Roth718c8342018-02-28 13:00:04 -08002484 if (parent_data_size > 0) {
2485 subchannel_call_retry_state* retry_state =
2486 static_cast<subchannel_call_retry_state*>(
2487 grpc_connected_subchannel_call_get_parent_data(
2488 calld->subchannel_call));
2489 retry_state->batch_payload.context = calld->pick.subchannel_call_context;
2490 }
2491 pending_batches_resume(elem);
Craig Tiller11c17d42017-03-13 13:36:34 -07002492 }
Mark D. Roth0ca0be82017-06-20 07:49:33 -07002493 GRPC_ERROR_UNREF(error);
Craig Tiller11c17d42017-03-13 13:36:34 -07002494}
2495
Mark D. Rothb2929602017-09-11 09:31:11 -07002496// Invoked when a pick is completed, on both success or failure.
Mark D. Roth718c8342018-02-28 13:00:04 -08002497static void pick_done(void* arg, grpc_error* error) {
2498 grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
Noah Eisenbe82e642018-02-09 09:16:55 -08002499 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Mark D. Roth718c8342018-02-28 13:00:04 -08002500 call_data* calld = static_cast<call_data*>(elem->call_data);
David Garcia Quintasbe1b7f92018-01-12 14:01:38 -08002501 if (calld->pick.connected_subchannel == nullptr) {
Mark D. Roth0ca0be82017-06-20 07:49:33 -07002502 // Failed to create subchannel.
Mark D. Roth718c8342018-02-28 13:00:04 -08002503 // If there was no error, this is an LB policy drop, in which case
2504 // we return an error; otherwise, we may retry.
2505 grpc_status_code status = GRPC_STATUS_OK;
2506 grpc_error_get_status(error, calld->deadline, &status, nullptr, nullptr,
2507 nullptr);
2508 if (error == GRPC_ERROR_NONE || !calld->enable_retries ||
2509 !maybe_retry(elem, nullptr /* batch_data */, status,
2510 nullptr /* server_pushback_md */)) {
2511 grpc_error* new_error =
2512 error == GRPC_ERROR_NONE
2513 ? GRPC_ERROR_CREATE_FROM_STATIC_STRING(
2514 "Call dropped by load balancing policy")
2515 : GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
2516 "Failed to create subchannel", &error, 1);
2517 if (grpc_client_channel_trace.enabled()) {
2518 gpr_log(GPR_DEBUG,
2519 "chand=%p calld=%p: failed to create subchannel: error=%s",
2520 chand, calld, grpc_error_string(new_error));
2521 }
2522 pending_batches_fail(elem, new_error, true /* yield_call_combiner */);
Mark D. Roth60751fe2017-07-07 12:50:33 -07002523 }
Mark D. Roth2a5959f2016-09-01 08:20:27 -07002524 } else {
Mark D. Roth9fe284e2016-09-12 11:22:27 -07002525 /* Create call on subchannel. */
Mark D. Roth718c8342018-02-28 13:00:04 -08002526 create_subchannel_call(elem, GRPC_ERROR_REF(error));
Mark D. Roth2a5959f2016-09-01 08:20:27 -07002527 }
Mark D. Roth718c8342018-02-28 13:00:04 -08002528}
2529
2530// Invoked when a pick is completed to leave the client_channel combiner
2531// and continue processing in the call combiner.
2532static void pick_done_locked(grpc_call_element* elem, grpc_error* error) {
2533 call_data* calld = static_cast<call_data*>(elem->call_data);
2534 GRPC_CLOSURE_INIT(&calld->pick_closure, pick_done, elem,
2535 grpc_schedule_on_exec_ctx);
2536 GRPC_CLOSURE_SCHED(&calld->pick_closure, error);
Mark D. Roth2a5959f2016-09-01 08:20:27 -07002537}
2538
Mark D. Rothb2929602017-09-11 09:31:11 -07002539// A wrapper around pick_done_locked() that is used in cases where
2540// either (a) the pick was deferred pending a resolver result or (b) the
2541// pick was done asynchronously. Removes the call's polling entity from
2542// chand->interested_parties before invoking pick_done_locked().
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002543static void async_pick_done_locked(grpc_call_element* elem, grpc_error* error) {
Noah Eisenbe82e642018-02-09 09:16:55 -08002544 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2545 call_data* calld = static_cast<call_data*>(elem->call_data);
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002546 grpc_polling_entity_del_from_pollset_set(calld->pollent,
Mark D. Rothb2929602017-09-11 09:31:11 -07002547 chand->interested_parties);
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002548 pick_done_locked(elem, error);
Mark D. Rothb2929602017-09-11 09:31:11 -07002549}
2550
2551// Note: This runs under the client_channel combiner, but will NOT be
2552// holding the call combiner.
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002553static void pick_callback_cancel_locked(void* arg, grpc_error* error) {
Noah Eisenbe82e642018-02-09 09:16:55 -08002554 grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
2555 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2556 call_data* calld = static_cast<call_data*>(elem->call_data);
Mark D. Rothc0febd32018-01-09 10:25:24 -08002557 // Note: chand->lb_policy may have changed since we started our pick,
2558 // in which case we will be cancelling the pick on a policy other than
2559 // the one we started it on. However, this will just be a no-op.
2560 if (error != GRPC_ERROR_NONE && chand->lb_policy != nullptr) {
Craig Tiller6014e8a2017-10-16 13:50:29 -07002561 if (grpc_client_channel_trace.enabled()) {
Mark D. Rothb2929602017-09-11 09:31:11 -07002562 gpr_log(GPR_DEBUG, "chand=%p calld=%p: cancelling pick from LB policy %p",
Mark D. Rothc8875492018-02-20 08:33:48 -08002563 chand, calld, chand->lb_policy.get());
Mark D. Rothb2929602017-09-11 09:31:11 -07002564 }
Mark D. Rothc8875492018-02-20 08:33:48 -08002565 chand->lb_policy->CancelPickLocked(&calld->pick, GRPC_ERROR_REF(error));
Mark D. Rothb2929602017-09-11 09:31:11 -07002566 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002567 GRPC_CALL_STACK_UNREF(calld->owning_call, "pick_callback_cancel");
Mark D. Rothb2929602017-09-11 09:31:11 -07002568}
2569
Mark D. Rothc8875492018-02-20 08:33:48 -08002570// Callback invoked by LoadBalancingPolicy::PickLocked() for async picks.
Mark D. Rothb2929602017-09-11 09:31:11 -07002571// Unrefs the LB policy and invokes async_pick_done_locked().
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002572static void pick_callback_done_locked(void* arg, grpc_error* error) {
Noah Eisenbe82e642018-02-09 09:16:55 -08002573 grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
2574 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2575 call_data* calld = static_cast<call_data*>(elem->call_data);
Craig Tiller6014e8a2017-10-16 13:50:29 -07002576 if (grpc_client_channel_trace.enabled()) {
Mark D. Rothb2929602017-09-11 09:31:11 -07002577 gpr_log(GPR_DEBUG, "chand=%p calld=%p: pick completed asynchronously",
2578 chand, calld);
2579 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002580 async_pick_done_locked(elem, GRPC_ERROR_REF(error));
Ken Paysonf069dd42018-02-05 09:15:05 -08002581 GRPC_CALL_STACK_UNREF(calld->owning_call, "pick_callback");
Mark D. Rothb2929602017-09-11 09:31:11 -07002582}
2583
Mark D. Roth718c8342018-02-28 13:00:04 -08002584// Applies service config to the call. Must be invoked once we know
2585// that the resolver has returned results to the channel.
2586static void apply_service_config_to_call_locked(grpc_call_element* elem) {
2587 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2588 call_data* calld = static_cast<call_data*>(elem->call_data);
2589 if (grpc_client_channel_trace.enabled()) {
2590 gpr_log(GPR_DEBUG, "chand=%p calld=%p: applying service config to call",
2591 chand, calld);
2592 }
2593 if (chand->retry_throttle_data != nullptr) {
2594 calld->retry_throttle_data =
2595 grpc_server_retry_throttle_data_ref(chand->retry_throttle_data);
2596 }
2597 if (chand->method_params_table != nullptr) {
2598 calld->method_params = grpc_core::ServiceConfig::MethodConfigTableLookup(
2599 *chand->method_params_table, calld->path);
2600 if (calld->method_params != nullptr) {
2601 // If the deadline from the service config is shorter than the one
2602 // from the client API, reset the deadline timer.
2603 if (chand->deadline_checking_enabled &&
2604 calld->method_params->timeout() != 0) {
2605 const grpc_millis per_method_deadline =
2606 grpc_timespec_to_millis_round_up(calld->call_start_time) +
2607 calld->method_params->timeout();
2608 if (per_method_deadline < calld->deadline) {
2609 calld->deadline = per_method_deadline;
2610 grpc_deadline_state_reset(elem, calld->deadline);
2611 }
2612 }
2613 }
2614 }
2615 // If no retry policy, disable retries.
2616 // TODO(roth): Remove this when adding support for transparent retries.
2617 if (calld->method_params == nullptr ||
2618 calld->method_params->retry_policy() == nullptr) {
2619 calld->enable_retries = false;
2620 }
2621}
2622
Mark D. Rothc8875492018-02-20 08:33:48 -08002623// Starts a pick on chand->lb_policy.
2624// Returns true if pick is completed synchronously.
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002625static bool pick_callback_start_locked(grpc_call_element* elem) {
Noah Eisenbe82e642018-02-09 09:16:55 -08002626 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2627 call_data* calld = static_cast<call_data*>(elem->call_data);
Craig Tiller6014e8a2017-10-16 13:50:29 -07002628 if (grpc_client_channel_trace.enabled()) {
Mark D. Rothb2929602017-09-11 09:31:11 -07002629 gpr_log(GPR_DEBUG, "chand=%p calld=%p: starting pick on lb_policy=%p",
Mark D. Rothc8875492018-02-20 08:33:48 -08002630 chand, calld, chand->lb_policy.get());
Mark D. Rothb2929602017-09-11 09:31:11 -07002631 }
Mark D. Roth718c8342018-02-28 13:00:04 -08002632 // Only get service config data on the first attempt.
2633 if (calld->num_attempts_completed == 0) {
2634 apply_service_config_to_call_locked(elem);
2635 }
Mark D. Rothb2929602017-09-11 09:31:11 -07002636 // If the application explicitly set wait_for_ready, use that.
2637 // Otherwise, if the service config specified a value for this
2638 // method, use that.
Mark D. Roth718c8342018-02-28 13:00:04 -08002639 //
2640 // The send_initial_metadata batch will be the first one in the list,
2641 // as set by get_batch_index() above.
2642 calld->pick.initial_metadata =
2643 calld->seen_send_initial_metadata
2644 ? &calld->send_initial_metadata
2645 : calld->pending_batches[0]
2646 .batch->payload->send_initial_metadata.send_initial_metadata;
2647 uint32_t send_initial_metadata_flags =
2648 calld->seen_send_initial_metadata
2649 ? calld->send_initial_metadata_flags
2650 : calld->pending_batches[0]
2651 .batch->payload->send_initial_metadata
2652 .send_initial_metadata_flags;
Mark D. Rothb2929602017-09-11 09:31:11 -07002653 const bool wait_for_ready_set_from_api =
Mark D. Roth718c8342018-02-28 13:00:04 -08002654 send_initial_metadata_flags &
Mark D. Rothb2929602017-09-11 09:31:11 -07002655 GRPC_INITIAL_METADATA_WAIT_FOR_READY_EXPLICITLY_SET;
2656 const bool wait_for_ready_set_from_service_config =
Craig Tiller4782d922017-11-10 09:53:21 -08002657 calld->method_params != nullptr &&
Mark D. Roth3e7f2df2018-02-26 13:17:06 -08002658 calld->method_params->wait_for_ready() !=
2659 ClientChannelMethodParams::WAIT_FOR_READY_UNSET;
Mark D. Rothb2929602017-09-11 09:31:11 -07002660 if (!wait_for_ready_set_from_api && wait_for_ready_set_from_service_config) {
Mark D. Roth3e7f2df2018-02-26 13:17:06 -08002661 if (calld->method_params->wait_for_ready() ==
2662 ClientChannelMethodParams::WAIT_FOR_READY_TRUE) {
Mark D. Roth718c8342018-02-28 13:00:04 -08002663 send_initial_metadata_flags |= GRPC_INITIAL_METADATA_WAIT_FOR_READY;
Mark D. Rothb2929602017-09-11 09:31:11 -07002664 } else {
Mark D. Roth718c8342018-02-28 13:00:04 -08002665 send_initial_metadata_flags &= ~GRPC_INITIAL_METADATA_WAIT_FOR_READY;
Mark D. Rothb2929602017-09-11 09:31:11 -07002666 }
2667 }
Mark D. Roth718c8342018-02-28 13:00:04 -08002668 calld->pick.initial_metadata_flags = send_initial_metadata_flags;
2669 GRPC_CLOSURE_INIT(&calld->pick_closure, pick_callback_done_locked, elem,
Mark D. Rothb2929602017-09-11 09:31:11 -07002670 grpc_combiner_scheduler(chand->combiner));
Mark D. Roth718c8342018-02-28 13:00:04 -08002671 calld->pick.on_complete = &calld->pick_closure;
Ken Paysonf069dd42018-02-05 09:15:05 -08002672 GRPC_CALL_STACK_REF(calld->owning_call, "pick_callback");
Mark D. Rothc8875492018-02-20 08:33:48 -08002673 const bool pick_done = chand->lb_policy->PickLocked(&calld->pick);
Mark D. Rothb2929602017-09-11 09:31:11 -07002674 if (pick_done) {
Mark D. Rothc8875492018-02-20 08:33:48 -08002675 // Pick completed synchronously.
Craig Tiller6014e8a2017-10-16 13:50:29 -07002676 if (grpc_client_channel_trace.enabled()) {
Mark D. Rothb2929602017-09-11 09:31:11 -07002677 gpr_log(GPR_DEBUG, "chand=%p calld=%p: pick completed synchronously",
2678 chand, calld);
2679 }
Ken Paysonf069dd42018-02-05 09:15:05 -08002680 GRPC_CALL_STACK_UNREF(calld->owning_call, "pick_callback");
Mark D. Rothb2929602017-09-11 09:31:11 -07002681 } else {
2682 GRPC_CALL_STACK_REF(calld->owning_call, "pick_callback_cancel");
2683 grpc_call_combiner_set_notify_on_cancel(
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002684 calld->call_combiner,
Mark D. Roth718c8342018-02-28 13:00:04 -08002685 GRPC_CLOSURE_INIT(&calld->pick_cancel_closure,
Mark D. Rothb2929602017-09-11 09:31:11 -07002686 pick_callback_cancel_locked, elem,
2687 grpc_combiner_scheduler(chand->combiner)));
2688 }
2689 return pick_done;
2690}
Mark D. Roth0ca0be82017-06-20 07:49:33 -07002691
Craig Tiller577c9b22015-11-02 14:11:15 -08002692typedef struct {
Craig Tillerbaa14a92017-11-03 09:09:36 -07002693 grpc_call_element* elem;
Mark D. Roth66f3d2b2017-09-01 09:02:17 -07002694 bool finished;
Craig Tiller577c9b22015-11-02 14:11:15 -08002695 grpc_closure closure;
Mark D. Roth66f3d2b2017-09-01 09:02:17 -07002696 grpc_closure cancel_closure;
Mark D. Roth0ca0be82017-06-20 07:49:33 -07002697} pick_after_resolver_result_args;
Craig Tiller577c9b22015-11-02 14:11:15 -08002698
Mark D. Roth76e264b2017-08-25 09:03:33 -07002699// Note: This runs under the client_channel combiner, but will NOT be
2700// holding the call combiner.
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002701static void pick_after_resolver_result_cancel_locked(void* arg,
Craig Tillerbaa14a92017-11-03 09:09:36 -07002702 grpc_error* error) {
Noah Eisen4d20a662018-02-09 09:34:04 -08002703 pick_after_resolver_result_args* args =
2704 static_cast<pick_after_resolver_result_args*>(arg);
Mark D. Roth66f3d2b2017-09-01 09:02:17 -07002705 if (args->finished) {
2706 gpr_free(args);
Mark D. Rothb2b9a0f2017-09-01 09:06:47 -07002707 return;
Mark D. Roth764cf042017-09-01 09:00:06 -07002708 }
Mark D. Roth76e264b2017-08-25 09:03:33 -07002709 // If we don't yet have a resolver result, then a closure for
2710 // pick_after_resolver_result_done_locked() will have been added to
2711 // chand->waiting_for_resolver_result_closures, and it may not be invoked
2712 // until after this call has been destroyed. We mark the operation as
Mark D. Rothb2b9a0f2017-09-01 09:06:47 -07002713 // finished, so that when pick_after_resolver_result_done_locked()
Mark D. Roth76e264b2017-08-25 09:03:33 -07002714 // is called, it will be a no-op. We also immediately invoke
Mark D. Rothb2929602017-09-11 09:31:11 -07002715 // async_pick_done_locked() to propagate the error back to the caller.
2716 args->finished = true;
Craig Tillerbaa14a92017-11-03 09:09:36 -07002717 grpc_call_element* elem = args->elem;
Noah Eisenbe82e642018-02-09 09:16:55 -08002718 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2719 call_data* calld = static_cast<call_data*>(elem->call_data);
Craig Tiller6014e8a2017-10-16 13:50:29 -07002720 if (grpc_client_channel_trace.enabled()) {
Mark D. Rothb2b9a0f2017-09-01 09:06:47 -07002721 gpr_log(GPR_DEBUG,
2722 "chand=%p calld=%p: cancelling pick waiting for resolver result",
2723 chand, calld);
Mark D. Roth76e264b2017-08-25 09:03:33 -07002724 }
Mark D. Rothb2b9a0f2017-09-01 09:06:47 -07002725 // Note: Although we are not in the call combiner here, we are
2726 // basically stealing the call combiner from the pending pick, so
Mark D. Rothb2929602017-09-11 09:31:11 -07002727 // it's safe to call async_pick_done_locked() here -- we are
Mark D. Rothb2b9a0f2017-09-01 09:06:47 -07002728 // essentially calling it here instead of calling it in
2729 // pick_after_resolver_result_done_locked().
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002730 async_pick_done_locked(elem, GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
2731 "Pick cancelled", &error, 1));
Mark D. Roth76e264b2017-08-25 09:03:33 -07002732}
2733
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002734static void pick_after_resolver_result_done_locked(void* arg,
Craig Tillerbaa14a92017-11-03 09:09:36 -07002735 grpc_error* error) {
Noah Eisen4d20a662018-02-09 09:34:04 -08002736 pick_after_resolver_result_args* args =
2737 static_cast<pick_after_resolver_result_args*>(arg);
Mark D. Roth66f3d2b2017-09-01 09:02:17 -07002738 if (args->finished) {
Craig Tiller577c9b22015-11-02 14:11:15 -08002739 /* cancelled, do nothing */
Craig Tiller6014e8a2017-10-16 13:50:29 -07002740 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth60751fe2017-07-07 12:50:33 -07002741 gpr_log(GPR_DEBUG, "call cancelled before resolver result");
2742 }
Mark D. Roth66f3d2b2017-09-01 09:02:17 -07002743 gpr_free(args);
Mark D. Rothb2b9a0f2017-09-01 09:06:47 -07002744 return;
2745 }
2746 args->finished = true;
Craig Tillerbaa14a92017-11-03 09:09:36 -07002747 grpc_call_element* elem = args->elem;
Noah Eisenbe82e642018-02-09 09:16:55 -08002748 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2749 call_data* calld = static_cast<call_data*>(elem->call_data);
Mark D. Rothb2b9a0f2017-09-01 09:06:47 -07002750 if (error != GRPC_ERROR_NONE) {
Craig Tiller6014e8a2017-10-16 13:50:29 -07002751 if (grpc_client_channel_trace.enabled()) {
Mark D. Rothb2b9a0f2017-09-01 09:06:47 -07002752 gpr_log(GPR_DEBUG, "chand=%p calld=%p: resolver failed to return data",
2753 chand, calld);
2754 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002755 async_pick_done_locked(elem, GRPC_ERROR_REF(error));
Craig Tiller4782d922017-11-10 09:53:21 -08002756 } else if (chand->lb_policy != nullptr) {
Craig Tiller6014e8a2017-10-16 13:50:29 -07002757 if (grpc_client_channel_trace.enabled()) {
Mark D. Rothb2b9a0f2017-09-01 09:06:47 -07002758 gpr_log(GPR_DEBUG, "chand=%p calld=%p: resolver returned, doing pick",
2759 chand, calld);
2760 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002761 if (pick_callback_start_locked(elem)) {
Mark D. Rothb2929602017-09-11 09:31:11 -07002762 // Even if the LB policy returns a result synchronously, we have
2763 // already added our polling entity to chand->interested_parties
2764 // in order to wait for the resolver result, so we need to
2765 // remove it here. Therefore, we call async_pick_done_locked()
2766 // instead of pick_done_locked().
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002767 async_pick_done_locked(elem, GRPC_ERROR_NONE);
Mark D. Roth9dab7d52016-10-07 07:48:03 -07002768 }
Craig Tiller577c9b22015-11-02 14:11:15 -08002769 }
Mark D. Roth718c8342018-02-28 13:00:04 -08002770 // TODO(roth): It should be impossible for chand->lb_policy to be nullptr
Mark D. Roth48be9de2017-10-23 12:27:37 -07002771 // here, so the rest of this code should never actually be executed.
2772 // However, we have reports of a crash on iOS that triggers this case,
2773 // so we are temporarily adding this to restore branches that were
2774 // removed in https://github.com/grpc/grpc/pull/12297. Need to figure
2775 // out what is actually causing this to occur and then figure out the
2776 // right way to deal with it.
Craig Tiller4782d922017-11-10 09:53:21 -08002777 else if (chand->resolver != nullptr) {
Mark D. Roth48be9de2017-10-23 12:27:37 -07002778 // No LB policy, so try again.
ncteisen72afb762017-11-10 12:23:12 -08002779 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth48be9de2017-10-23 12:27:37 -07002780 gpr_log(GPR_DEBUG,
2781 "chand=%p calld=%p: resolver returned but no LB policy, "
2782 "trying again",
2783 chand, calld);
2784 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002785 pick_after_resolver_result_start_locked(elem);
Mark D. Roth48be9de2017-10-23 12:27:37 -07002786 } else {
ncteisen72afb762017-11-10 12:23:12 -08002787 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth48be9de2017-10-23 12:27:37 -07002788 gpr_log(GPR_DEBUG, "chand=%p calld=%p: resolver disconnected", chand,
2789 calld);
2790 }
2791 async_pick_done_locked(
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002792 elem, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Disconnected"));
Mark D. Roth48be9de2017-10-23 12:27:37 -07002793 }
Craig Tiller577c9b22015-11-02 14:11:15 -08002794}
2795
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002796static void pick_after_resolver_result_start_locked(grpc_call_element* elem) {
Noah Eisenbe82e642018-02-09 09:16:55 -08002797 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
2798 call_data* calld = static_cast<call_data*>(elem->call_data);
Craig Tiller6014e8a2017-10-16 13:50:29 -07002799 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth60751fe2017-07-07 12:50:33 -07002800 gpr_log(GPR_DEBUG,
2801 "chand=%p calld=%p: deferring pick pending resolver result", chand,
2802 calld);
Mark D. Roth64a317c2017-05-02 08:27:08 -07002803 }
Craig Tillerbaa14a92017-11-03 09:09:36 -07002804 pick_after_resolver_result_args* args =
Noah Eisenbe82e642018-02-09 09:16:55 -08002805 static_cast<pick_after_resolver_result_args*>(gpr_zalloc(sizeof(*args)));
Mark D. Roth60751fe2017-07-07 12:50:33 -07002806 args->elem = elem;
2807 GRPC_CLOSURE_INIT(&args->closure, pick_after_resolver_result_done_locked,
2808 args, grpc_combiner_scheduler(chand->combiner));
2809 grpc_closure_list_append(&chand->waiting_for_resolver_result_closures,
2810 &args->closure, GRPC_ERROR_NONE);
Mark D. Roth76e264b2017-08-25 09:03:33 -07002811 grpc_call_combiner_set_notify_on_cancel(
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002812 calld->call_combiner,
Mark D. Roth66f3d2b2017-09-01 09:02:17 -07002813 GRPC_CLOSURE_INIT(&args->cancel_closure,
2814 pick_after_resolver_result_cancel_locked, args,
Mark D. Roth76e264b2017-08-25 09:03:33 -07002815 grpc_combiner_scheduler(chand->combiner)));
Mark D. Roth60751fe2017-07-07 12:50:33 -07002816}
2817
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002818static void start_pick_locked(void* arg, grpc_error* ignored) {
Noah Eisenbe82e642018-02-09 09:16:55 -08002819 grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
2820 call_data* calld = static_cast<call_data*>(elem->call_data);
2821 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
David Garcia Quintasbe1b7f92018-01-12 14:01:38 -08002822 GPR_ASSERT(calld->pick.connected_subchannel == nullptr);
Mark D. Roth718c8342018-02-28 13:00:04 -08002823 GPR_ASSERT(calld->subchannel_call == nullptr);
Craig Tiller4782d922017-11-10 09:53:21 -08002824 if (chand->lb_policy != nullptr) {
Mark D. Rothb2929602017-09-11 09:31:11 -07002825 // We already have an LB policy, so ask it for a pick.
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002826 if (pick_callback_start_locked(elem)) {
Mark D. Rothb2929602017-09-11 09:31:11 -07002827 // Pick completed synchronously.
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002828 pick_done_locked(elem, GRPC_ERROR_NONE);
Mark D. Rothb2929602017-09-11 09:31:11 -07002829 return;
Mark D. Roth2a5959f2016-09-01 08:20:27 -07002830 }
Mark D. Roth76e264b2017-08-25 09:03:33 -07002831 } else {
Mark D. Rothb2929602017-09-11 09:31:11 -07002832 // We do not yet have an LB policy, so wait for a resolver result.
Craig Tiller4782d922017-11-10 09:53:21 -08002833 if (chand->resolver == nullptr) {
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002834 pick_done_locked(elem,
Mark D. Rothb2929602017-09-11 09:31:11 -07002835 GRPC_ERROR_CREATE_FROM_STATIC_STRING("Disconnected"));
2836 return;
2837 }
2838 if (!chand->started_resolving) {
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002839 start_resolving_locked(chand);
Mark D. Rothb2929602017-09-11 09:31:11 -07002840 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002841 pick_after_resolver_result_start_locked(elem);
Mark D. Roth2a5959f2016-09-01 08:20:27 -07002842 }
Mark D. Rothb2929602017-09-11 09:31:11 -07002843 // We need to wait for either a resolver result or for an async result
2844 // from the LB policy. Add the polling entity from call_data to the
2845 // channel_data's interested_parties, so that the I/O of the LB policy
2846 // and resolver can be done under it. The polling entity will be
2847 // removed in async_pick_done_locked().
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002848 grpc_polling_entity_add_to_pollset_set(calld->pollent,
Mark D. Rothb2929602017-09-11 09:31:11 -07002849 chand->interested_parties);
Craig Tillera11bfc82017-02-14 09:56:33 -08002850}
2851
Mark D. Roth718c8342018-02-28 13:00:04 -08002852//
2853// filter call vtable functions
2854//
Mark D. Rothd6d192d2017-02-23 08:58:42 -08002855
Craig Tillere1b51da2017-03-31 15:44:33 -07002856static void cc_start_transport_stream_op_batch(
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002857 grpc_call_element* elem, grpc_transport_stream_op_batch* batch) {
yang-gce1cfea2018-01-31 15:59:50 -08002858 GPR_TIMER_SCOPE("cc_start_transport_stream_op_batch", 0);
Noah Eisenbe82e642018-02-09 09:16:55 -08002859 call_data* calld = static_cast<call_data*>(elem->call_data);
2860 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Craig Tiller3be7dd02017-04-03 14:30:03 -07002861 if (chand->deadline_checking_enabled) {
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002862 grpc_deadline_state_client_start_transport_stream_op_batch(elem, batch);
Craig Tiller3be7dd02017-04-03 14:30:03 -07002863 }
Mark D. Roth76e264b2017-08-25 09:03:33 -07002864 // If we've previously been cancelled, immediately fail any new batches.
Mark D. Roth718c8342018-02-28 13:00:04 -08002865 if (calld->cancel_error != GRPC_ERROR_NONE) {
Craig Tiller6014e8a2017-10-16 13:50:29 -07002866 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth76e264b2017-08-25 09:03:33 -07002867 gpr_log(GPR_DEBUG, "chand=%p calld=%p: failing batch with error: %s",
Mark D. Roth718c8342018-02-28 13:00:04 -08002868 chand, calld, grpc_error_string(calld->cancel_error));
Mark D. Roth76e264b2017-08-25 09:03:33 -07002869 }
Mark D. Roth718c8342018-02-28 13:00:04 -08002870 // Note: This will release the call combiner.
Mark D. Roth76e264b2017-08-25 09:03:33 -07002871 grpc_transport_stream_op_batch_finish_with_failure(
Mark D. Roth718c8342018-02-28 13:00:04 -08002872 batch, GRPC_ERROR_REF(calld->cancel_error), calld->call_combiner);
yang-gce1cfea2018-01-31 15:59:50 -08002873 return;
Mark D. Roth76e264b2017-08-25 09:03:33 -07002874 }
Mark D. Roth718c8342018-02-28 13:00:04 -08002875 // Handle cancellation.
Mark D. Roth76e264b2017-08-25 09:03:33 -07002876 if (batch->cancel_stream) {
2877 // Stash a copy of cancel_error in our call data, so that we can use
2878 // it for subsequent operations. This ensures that if the call is
2879 // cancelled before any batches are passed down (e.g., if the deadline
2880 // is in the past when the call starts), we can return the right
2881 // error to the caller when the first batch does get passed down.
Mark D. Roth718c8342018-02-28 13:00:04 -08002882 GRPC_ERROR_UNREF(calld->cancel_error);
2883 calld->cancel_error =
2884 GRPC_ERROR_REF(batch->payload->cancel_stream.cancel_error);
Craig Tiller6014e8a2017-10-16 13:50:29 -07002885 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth76e264b2017-08-25 09:03:33 -07002886 gpr_log(GPR_DEBUG, "chand=%p calld=%p: recording cancel_error=%s", chand,
Mark D. Roth718c8342018-02-28 13:00:04 -08002887 calld, grpc_error_string(calld->cancel_error));
Mark D. Roth76e264b2017-08-25 09:03:33 -07002888 }
Mark D. Roth718c8342018-02-28 13:00:04 -08002889 // If we do not have a subchannel call (i.e., a pick has not yet
2890 // been started), fail all pending batches. Otherwise, send the
2891 // cancellation down to the subchannel call.
2892 if (calld->subchannel_call == nullptr) {
2893 pending_batches_fail(elem, GRPC_ERROR_REF(calld->cancel_error),
2894 false /* yield_call_combiner */);
2895 // Note: This will release the call combiner.
2896 grpc_transport_stream_op_batch_finish_with_failure(
2897 batch, GRPC_ERROR_REF(calld->cancel_error), calld->call_combiner);
Mark D. Roth76e264b2017-08-25 09:03:33 -07002898 } else {
Mark D. Roth718c8342018-02-28 13:00:04 -08002899 // Note: This will release the call combiner.
2900 grpc_subchannel_call_process_op(calld->subchannel_call, batch);
Mark D. Roth76e264b2017-08-25 09:03:33 -07002901 }
yang-gce1cfea2018-01-31 15:59:50 -08002902 return;
Mark D. Roth76e264b2017-08-25 09:03:33 -07002903 }
Mark D. Roth718c8342018-02-28 13:00:04 -08002904 // Add the batch to the pending list.
2905 pending_batches_add(elem, batch);
Mark D. Roth76e264b2017-08-25 09:03:33 -07002906 // Check if we've already gotten a subchannel call.
2907 // Note that once we have completed the pick, we do not need to enter
2908 // the channel combiner, which is more efficient (especially for
2909 // streaming calls).
Craig Tiller4782d922017-11-10 09:53:21 -08002910 if (calld->subchannel_call != nullptr) {
Craig Tiller6014e8a2017-10-16 13:50:29 -07002911 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth60751fe2017-07-07 12:50:33 -07002912 gpr_log(GPR_DEBUG,
Mark D. Roth718c8342018-02-28 13:00:04 -08002913 "chand=%p calld=%p: starting batch on subchannel_call=%p", chand,
Mark D. Roth76e264b2017-08-25 09:03:33 -07002914 calld, calld->subchannel_call);
Mark D. Roth60751fe2017-07-07 12:50:33 -07002915 }
Mark D. Roth718c8342018-02-28 13:00:04 -08002916 pending_batches_resume(elem);
yang-gce1cfea2018-01-31 15:59:50 -08002917 return;
Mark D. Roth2a5959f2016-09-01 08:20:27 -07002918 }
Mark D. Roth76e264b2017-08-25 09:03:33 -07002919 // We do not yet have a subchannel call.
Mark D. Roth76e264b2017-08-25 09:03:33 -07002920 // For batches containing a send_initial_metadata op, enter the channel
2921 // combiner to start a pick.
2922 if (batch->send_initial_metadata) {
Craig Tiller6014e8a2017-10-16 13:50:29 -07002923 if (grpc_client_channel_trace.enabled()) {
Mark D. Rothb2929602017-09-11 09:31:11 -07002924 gpr_log(GPR_DEBUG, "chand=%p calld=%p: entering client_channel combiner",
2925 chand, calld);
Mark D. Roth76e264b2017-08-25 09:03:33 -07002926 }
2927 GRPC_CLOSURE_SCHED(
Mark D. Roth76e264b2017-08-25 09:03:33 -07002928 GRPC_CLOSURE_INIT(&batch->handler_private.closure, start_pick_locked,
2929 elem, grpc_combiner_scheduler(chand->combiner)),
2930 GRPC_ERROR_NONE);
2931 } else {
2932 // For all other batches, release the call combiner.
Craig Tiller6014e8a2017-10-16 13:50:29 -07002933 if (grpc_client_channel_trace.enabled()) {
Mark D. Roth76e264b2017-08-25 09:03:33 -07002934 gpr_log(GPR_DEBUG,
2935 "chand=%p calld=%p: saved batch, yeilding call combiner", chand,
2936 calld);
2937 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002938 GRPC_CALL_COMBINER_STOP(calld->call_combiner,
Mark D. Roth76e264b2017-08-25 09:03:33 -07002939 "batch does not include send_initial_metadata");
Mark D. Roth60751fe2017-07-07 12:50:33 -07002940 }
Mark D. Roth2a5959f2016-09-01 08:20:27 -07002941}
2942
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -08002943/* Constructor for call_data */
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002944static grpc_error* cc_init_call_elem(grpc_call_element* elem,
Craig Tillerbaa14a92017-11-03 09:09:36 -07002945 const grpc_call_element_args* args) {
Noah Eisenbe82e642018-02-09 09:16:55 -08002946 call_data* calld = static_cast<call_data*>(elem->call_data);
2947 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Mark D. Rothe40dd292016-10-05 14:58:37 -07002948 // Initialize data members.
Craig Tiller7c70b6c2017-01-23 07:48:42 -08002949 calld->path = grpc_slice_ref_internal(args->path);
Mark D. Rothff08f332016-10-14 13:01:01 -07002950 calld->call_start_time = args->start_time;
Craig Tiller89c14282017-07-19 15:32:27 -07002951 calld->deadline = args->deadline;
Craig Tillerd426cac2017-03-13 12:30:45 -07002952 calld->arena = args->arena;
Mark D. Roth66f3d2b2017-09-01 09:02:17 -07002953 calld->owning_call = args->call_stack;
Mark D. Roth76e264b2017-08-25 09:03:33 -07002954 calld->call_combiner = args->call_combiner;
Craig Tiller3be7dd02017-04-03 14:30:03 -07002955 if (chand->deadline_checking_enabled) {
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002956 grpc_deadline_state_init(elem, args->call_stack, args->call_combiner,
2957 calld->deadline);
Craig Tiller3be7dd02017-04-03 14:30:03 -07002958 }
Mark D. Roth718c8342018-02-28 13:00:04 -08002959 calld->enable_retries = chand->enable_retries;
Mark D. Roth0badbe82016-06-23 10:15:12 -07002960 return GRPC_ERROR_NONE;
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -08002961}
2962
2963/* Destructor for call_data */
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002964static void cc_destroy_call_elem(grpc_call_element* elem,
Craig Tillerbaa14a92017-11-03 09:09:36 -07002965 const grpc_call_final_info* final_info,
2966 grpc_closure* then_schedule_closure) {
Noah Eisenbe82e642018-02-09 09:16:55 -08002967 call_data* calld = static_cast<call_data*>(elem->call_data);
2968 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Craig Tiller3be7dd02017-04-03 14:30:03 -07002969 if (chand->deadline_checking_enabled) {
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002970 grpc_deadline_state_destroy(elem);
Craig Tiller3be7dd02017-04-03 14:30:03 -07002971 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002972 grpc_slice_unref_internal(calld->path);
Mark D. Roth3e7f2df2018-02-26 13:17:06 -08002973 calld->method_params.reset();
Mark D. Roth718c8342018-02-28 13:00:04 -08002974 GRPC_ERROR_UNREF(calld->cancel_error);
Craig Tiller4782d922017-11-10 09:53:21 -08002975 if (calld->subchannel_call != nullptr) {
Mark D. Roth76e264b2017-08-25 09:03:33 -07002976 grpc_subchannel_call_set_cleanup_closure(calld->subchannel_call,
Craig Tillerf7c8c9f2017-05-17 15:22:05 -07002977 then_schedule_closure);
Craig Tiller4782d922017-11-10 09:53:21 -08002978 then_schedule_closure = nullptr;
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002979 GRPC_SUBCHANNEL_CALL_UNREF(calld->subchannel_call,
Craig Tillerf7c8c9f2017-05-17 15:22:05 -07002980 "client_channel_destroy_call");
Mark D. Roth4c0fe492016-08-31 13:51:55 -07002981 }
Mark D. Roth718c8342018-02-28 13:00:04 -08002982 for (size_t i = 0; i < GPR_ARRAY_SIZE(calld->pending_batches); ++i) {
2983 GPR_ASSERT(calld->pending_batches[i].batch == nullptr);
2984 }
David Garcia Quintasbe1b7f92018-01-12 14:01:38 -08002985 if (calld->pick.connected_subchannel != nullptr) {
David Garcia Quintasdfa28512018-01-11 18:31:13 -08002986 calld->pick.connected_subchannel.reset();
Craig Tiller693d3942016-10-27 16:51:25 -07002987 }
Mark D. Roth09e458c2017-05-02 08:13:26 -07002988 for (size_t i = 0; i < GRPC_CONTEXT_COUNT; ++i) {
Mark D. Rothc0febd32018-01-09 10:25:24 -08002989 if (calld->pick.subchannel_call_context[i].value != nullptr) {
2990 calld->pick.subchannel_call_context[i].destroy(
2991 calld->pick.subchannel_call_context[i].value);
Mark D. Roth09e458c2017-05-02 08:13:26 -07002992 }
2993 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002994 GRPC_CLOSURE_SCHED(then_schedule_closure, GRPC_ERROR_NONE);
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -08002995}
2996
Yash Tibrewal8cf14702017-12-06 09:47:54 -08002997static void cc_set_pollset_or_pollset_set(grpc_call_element* elem,
Craig Tillerbaa14a92017-11-03 09:09:36 -07002998 grpc_polling_entity* pollent) {
Noah Eisenbe82e642018-02-09 09:16:55 -08002999 call_data* calld = static_cast<call_data*>(elem->call_data);
David Garcia Quintas2a50dfe2016-05-31 15:09:12 -07003000 calld->pollent = pollent;
Craig Tiller577c9b22015-11-02 14:11:15 -08003001}
3002
Mark D. Roth2a5959f2016-09-01 08:20:27 -07003003/*************************************************************************
3004 * EXPORTED SYMBOLS
3005 */
3006
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -08003007const grpc_channel_filter grpc_client_channel_filter = {
Craig Tillera0f3abd2017-03-31 15:42:16 -07003008 cc_start_transport_stream_op_batch,
Craig Tillerf40df232016-03-25 13:38:14 -07003009 cc_start_transport_op,
3010 sizeof(call_data),
Mark D. Roth2a5959f2016-09-01 08:20:27 -07003011 cc_init_call_elem,
David Garcia Quintas4afce7e2016-04-18 16:25:17 -07003012 cc_set_pollset_or_pollset_set,
Mark D. Roth2a5959f2016-09-01 08:20:27 -07003013 cc_destroy_call_elem,
Craig Tillerf40df232016-03-25 13:38:14 -07003014 sizeof(channel_data),
Mark D. Roth2a5959f2016-09-01 08:20:27 -07003015 cc_init_channel_elem,
3016 cc_destroy_channel_elem,
Mark D. Rothb2d24882016-10-27 15:44:07 -07003017 cc_get_channel_info,
Craig Tillerf40df232016-03-25 13:38:14 -07003018 "client-channel",
Craig Tiller87d5b192015-04-16 14:37:57 -07003019};
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -08003020
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003021static void try_to_connect_locked(void* arg, grpc_error* error_ignored) {
Noah Eisenbe82e642018-02-09 09:16:55 -08003022 channel_data* chand = static_cast<channel_data*>(arg);
Craig Tiller4782d922017-11-10 09:53:21 -08003023 if (chand->lb_policy != nullptr) {
Mark D. Rothc8875492018-02-20 08:33:48 -08003024 chand->lb_policy->ExitIdleLocked();
Craig Tiller613dafa2017-02-09 12:00:43 -08003025 } else {
3026 chand->exit_idle_when_lb_policy_arrives = true;
Craig Tiller4782d922017-11-10 09:53:21 -08003027 if (!chand->started_resolving && chand->resolver != nullptr) {
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003028 start_resolving_locked(chand);
Craig Tiller613dafa2017-02-09 12:00:43 -08003029 }
3030 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003031 GRPC_CHANNEL_STACK_UNREF(chand->owning_stack, "try_to_connect");
Craig Tiller613dafa2017-02-09 12:00:43 -08003032}
3033
Craig Tillera82950e2015-09-22 12:33:20 -07003034grpc_connectivity_state grpc_client_channel_check_connectivity_state(
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003035 grpc_channel_element* elem, int try_to_connect) {
Noah Eisenbe82e642018-02-09 09:16:55 -08003036 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Craig Tillera8610c02017-02-14 10:05:11 -08003037 grpc_connectivity_state out =
3038 grpc_connectivity_state_check(&chand->state_tracker);
Craig Tillera82950e2015-09-22 12:33:20 -07003039 if (out == GRPC_CHANNEL_IDLE && try_to_connect) {
Craig Tillerd2e5cfc2017-02-09 13:02:20 -08003040 GRPC_CHANNEL_STACK_REF(chand->owning_stack, "try_to_connect");
ncteisen274bbbe2017-06-08 14:57:11 -07003041 GRPC_CLOSURE_SCHED(
Yash Tibrewal0ee75742017-10-13 16:07:13 -07003042 GRPC_CLOSURE_CREATE(try_to_connect_locked, chand,
3043 grpc_combiner_scheduler(chand->combiner)),
Craig Tiller613dafa2017-02-09 12:00:43 -08003044 GRPC_ERROR_NONE);
Craig Tillera82950e2015-09-22 12:33:20 -07003045 }
Craig Tiller48cb07c2015-07-15 16:16:15 -07003046 return out;
3047}
3048
Alexander Polcync3b1f182017-04-18 13:51:36 -07003049typedef struct external_connectivity_watcher {
Craig Tillerbaa14a92017-11-03 09:09:36 -07003050 channel_data* chand;
David Garcia Quintas87d5a312017-06-06 19:45:58 -07003051 grpc_polling_entity pollent;
Craig Tillerbaa14a92017-11-03 09:09:36 -07003052 grpc_closure* on_complete;
3053 grpc_closure* watcher_timer_init;
3054 grpc_connectivity_state* state;
Craig Tiller86c99582015-11-25 15:22:26 -08003055 grpc_closure my_closure;
Craig Tillerbaa14a92017-11-03 09:09:36 -07003056 struct external_connectivity_watcher* next;
Craig Tiller86c99582015-11-25 15:22:26 -08003057} external_connectivity_watcher;
3058
Craig Tillerbaa14a92017-11-03 09:09:36 -07003059static external_connectivity_watcher* lookup_external_connectivity_watcher(
3060 channel_data* chand, grpc_closure* on_complete) {
Alexander Polcync3b1f182017-04-18 13:51:36 -07003061 gpr_mu_lock(&chand->external_connectivity_watcher_list_mu);
Craig Tillerbaa14a92017-11-03 09:09:36 -07003062 external_connectivity_watcher* w =
Alexander Polcync3b1f182017-04-18 13:51:36 -07003063 chand->external_connectivity_watcher_list_head;
Craig Tiller4782d922017-11-10 09:53:21 -08003064 while (w != nullptr && w->on_complete != on_complete) {
Alexander Polcync3b1f182017-04-18 13:51:36 -07003065 w = w->next;
3066 }
3067 gpr_mu_unlock(&chand->external_connectivity_watcher_list_mu);
3068 return w;
3069}
3070
3071static void external_connectivity_watcher_list_append(
Craig Tillerbaa14a92017-11-03 09:09:36 -07003072 channel_data* chand, external_connectivity_watcher* w) {
Alexander Polcync3b1f182017-04-18 13:51:36 -07003073 GPR_ASSERT(!lookup_external_connectivity_watcher(chand, w->on_complete));
3074
3075 gpr_mu_lock(&w->chand->external_connectivity_watcher_list_mu);
3076 GPR_ASSERT(!w->next);
3077 w->next = chand->external_connectivity_watcher_list_head;
3078 chand->external_connectivity_watcher_list_head = w;
3079 gpr_mu_unlock(&w->chand->external_connectivity_watcher_list_mu);
3080}
3081
3082static void external_connectivity_watcher_list_remove(
Craig Tillerbaa14a92017-11-03 09:09:36 -07003083 channel_data* chand, external_connectivity_watcher* too_remove) {
Alexander Polcync3b1f182017-04-18 13:51:36 -07003084 GPR_ASSERT(
3085 lookup_external_connectivity_watcher(chand, too_remove->on_complete));
3086 gpr_mu_lock(&chand->external_connectivity_watcher_list_mu);
3087 if (too_remove == chand->external_connectivity_watcher_list_head) {
3088 chand->external_connectivity_watcher_list_head = too_remove->next;
3089 gpr_mu_unlock(&chand->external_connectivity_watcher_list_mu);
3090 return;
3091 }
Craig Tillerbaa14a92017-11-03 09:09:36 -07003092 external_connectivity_watcher* w =
Alexander Polcync3b1f182017-04-18 13:51:36 -07003093 chand->external_connectivity_watcher_list_head;
Craig Tiller4782d922017-11-10 09:53:21 -08003094 while (w != nullptr) {
Alexander Polcync3b1f182017-04-18 13:51:36 -07003095 if (w->next == too_remove) {
3096 w->next = w->next->next;
3097 gpr_mu_unlock(&chand->external_connectivity_watcher_list_mu);
3098 return;
3099 }
3100 w = w->next;
3101 }
3102 GPR_UNREACHABLE_CODE(return );
3103}
3104
3105int grpc_client_channel_num_external_connectivity_watchers(
Craig Tillerbaa14a92017-11-03 09:09:36 -07003106 grpc_channel_element* elem) {
Noah Eisenbe82e642018-02-09 09:16:55 -08003107 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Alexander Polcync3b1f182017-04-18 13:51:36 -07003108 int count = 0;
3109
3110 gpr_mu_lock(&chand->external_connectivity_watcher_list_mu);
Craig Tillerbaa14a92017-11-03 09:09:36 -07003111 external_connectivity_watcher* w =
Alexander Polcync3b1f182017-04-18 13:51:36 -07003112 chand->external_connectivity_watcher_list_head;
Craig Tiller4782d922017-11-10 09:53:21 -08003113 while (w != nullptr) {
Alexander Polcync3b1f182017-04-18 13:51:36 -07003114 count++;
3115 w = w->next;
3116 }
3117 gpr_mu_unlock(&chand->external_connectivity_watcher_list_mu);
3118
3119 return count;
3120}
3121
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003122static void on_external_watch_complete_locked(void* arg, grpc_error* error) {
Noah Eisen4d20a662018-02-09 09:34:04 -08003123 external_connectivity_watcher* w =
3124 static_cast<external_connectivity_watcher*>(arg);
Craig Tillerbaa14a92017-11-03 09:09:36 -07003125 grpc_closure* follow_up = w->on_complete;
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003126 grpc_polling_entity_del_from_pollset_set(&w->pollent,
David Garcia Quintas87d5a312017-06-06 19:45:58 -07003127 w->chand->interested_parties);
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003128 GRPC_CHANNEL_STACK_UNREF(w->chand->owning_stack,
Craig Tiller1d881fb2015-12-01 07:39:04 -08003129 "external_connectivity_watcher");
Alexander Polcync3b1f182017-04-18 13:51:36 -07003130 external_connectivity_watcher_list_remove(w->chand, w);
Craig Tiller86c99582015-11-25 15:22:26 -08003131 gpr_free(w);
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003132 GRPC_CLOSURE_RUN(follow_up, GRPC_ERROR_REF(error));
Craig Tiller613dafa2017-02-09 12:00:43 -08003133}
3134
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003135static void watch_connectivity_state_locked(void* arg,
Craig Tillerbaa14a92017-11-03 09:09:36 -07003136 grpc_error* error_ignored) {
Noah Eisen4d20a662018-02-09 09:34:04 -08003137 external_connectivity_watcher* w =
3138 static_cast<external_connectivity_watcher*>(arg);
Craig Tiller4782d922017-11-10 09:53:21 -08003139 external_connectivity_watcher* found = nullptr;
3140 if (w->state != nullptr) {
Alexander Polcync3b1f182017-04-18 13:51:36 -07003141 external_connectivity_watcher_list_append(w->chand, w);
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003142 GRPC_CLOSURE_RUN(w->watcher_timer_init, GRPC_ERROR_NONE);
Alexander Polcyn2004e392017-10-16 15:14:46 -07003143 GRPC_CLOSURE_INIT(&w->my_closure, on_external_watch_complete_locked, w,
3144 grpc_combiner_scheduler(w->chand->combiner));
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003145 grpc_connectivity_state_notify_on_state_change(&w->chand->state_tracker,
3146 w->state, &w->my_closure);
Alexander Polcync3b1f182017-04-18 13:51:36 -07003147 } else {
Craig Tiller4782d922017-11-10 09:53:21 -08003148 GPR_ASSERT(w->watcher_timer_init == nullptr);
Alexander Polcync3b1f182017-04-18 13:51:36 -07003149 found = lookup_external_connectivity_watcher(w->chand, w->on_complete);
3150 if (found) {
3151 GPR_ASSERT(found->on_complete == w->on_complete);
3152 grpc_connectivity_state_notify_on_state_change(
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003153 &found->chand->state_tracker, nullptr, &found->my_closure);
Alexander Polcync3b1f182017-04-18 13:51:36 -07003154 }
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003155 grpc_polling_entity_del_from_pollset_set(&w->pollent,
David Garcia Quintas87d5a312017-06-06 19:45:58 -07003156 w->chand->interested_parties);
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003157 GRPC_CHANNEL_STACK_UNREF(w->chand->owning_stack,
Alexander Polcync3b1f182017-04-18 13:51:36 -07003158 "external_connectivity_watcher");
3159 gpr_free(w);
3160 }
Craig Tiller86c99582015-11-25 15:22:26 -08003161}
3162
Craig Tillera82950e2015-09-22 12:33:20 -07003163void grpc_client_channel_watch_connectivity_state(
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003164 grpc_channel_element* elem, grpc_polling_entity pollent,
3165 grpc_connectivity_state* state, grpc_closure* closure,
3166 grpc_closure* watcher_timer_init) {
Noah Eisenbe82e642018-02-09 09:16:55 -08003167 channel_data* chand = static_cast<channel_data*>(elem->channel_data);
Craig Tillerbaa14a92017-11-03 09:09:36 -07003168 external_connectivity_watcher* w =
Noah Eisenbe82e642018-02-09 09:16:55 -08003169 static_cast<external_connectivity_watcher*>(gpr_zalloc(sizeof(*w)));
Craig Tiller86c99582015-11-25 15:22:26 -08003170 w->chand = chand;
David Garcia Quintas87d5a312017-06-06 19:45:58 -07003171 w->pollent = pollent;
Mark D. Roth92210832017-05-02 15:04:39 -07003172 w->on_complete = closure;
Craig Tiller613dafa2017-02-09 12:00:43 -08003173 w->state = state;
Alexander Polcync3b1f182017-04-18 13:51:36 -07003174 w->watcher_timer_init = watcher_timer_init;
Yash Tibrewal8cf14702017-12-06 09:47:54 -08003175 grpc_polling_entity_add_to_pollset_set(&w->pollent,
David Garcia Quintas87d5a312017-06-06 19:45:58 -07003176 chand->interested_parties);
Craig Tiller1d881fb2015-12-01 07:39:04 -08003177 GRPC_CHANNEL_STACK_REF(w->chand->owning_stack,
3178 "external_connectivity_watcher");
ncteisen274bbbe2017-06-08 14:57:11 -07003179 GRPC_CLOSURE_SCHED(
ncteisen274bbbe2017-06-08 14:57:11 -07003180 GRPC_CLOSURE_INIT(&w->my_closure, watch_connectivity_state_locked, w,
Craig Tilleree4b1452017-05-12 10:56:03 -07003181 grpc_combiner_scheduler(chand->combiner)),
Craig Tiller613dafa2017-02-09 12:00:43 -08003182 GRPC_ERROR_NONE);
Craig Tiller48cb07c2015-07-15 16:16:15 -07003183}
Mark D. Roth718c8342018-02-28 13:00:04 -08003184
3185grpc_subchannel_call* grpc_client_channel_get_subchannel_call(
3186 grpc_call_element* elem) {
3187 call_data* calld = static_cast<call_data*>(elem->call_data);
3188 return calld->subchannel_call;
3189}