1 //
2 //
3 // Copyright 2015 gRPC authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 // http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 //
18
19 #include <atomic>
20 #include <cstring>
21 #include <memory>
22 #include <string>
23 #include <utility>
24 #include <vector>
25
26 #include <grpc/grpc.h>
27 #include <grpc/impl/connectivity_state.h>
28 #include <grpc/slice.h>
29 #include <grpc/support/alloc.h>
30 #include <grpc/support/log.h>
31 #include <grpc/support/time.h>
32 #include <grpcpp/channel.h>
33 #include <grpcpp/client_context.h>
34 #include <grpcpp/completion_queue.h>
35 #include <grpcpp/impl/call.h>
36 #include <grpcpp/impl/call_op_set_interface.h>
37 #include <grpcpp/impl/completion_queue_tag.h>
38 #include <grpcpp/impl/rpc_method.h>
39 #include <grpcpp/impl/sync.h>
40 #include <grpcpp/support/client_interceptor.h>
41 #include <grpcpp/support/slice.h>
42
43 #include "src/core/lib/iomgr/iomgr.h"
44
45 namespace grpc {
46
Channel(const std::string & host,grpc_channel * channel,std::vector<std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>> interceptor_creators)47 Channel::Channel(
48 const std::string& host, grpc_channel* channel,
49 std::vector<
50 std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>>
51 interceptor_creators)
52 : host_(host), c_channel_(channel) {
53 interceptor_creators_ = std::move(interceptor_creators);
54 }
55
~Channel()56 Channel::~Channel() {
57 grpc_channel_destroy(c_channel_);
58 CompletionQueue* callback_cq = callback_cq_.load(std::memory_order_relaxed);
59 if (callback_cq != nullptr) {
60 if (grpc_iomgr_run_in_background()) {
61 // gRPC-core provides the backing needed for the preferred CQ type
62 callback_cq->Shutdown();
63 } else {
64 CompletionQueue::ReleaseCallbackAlternativeCQ(callback_cq);
65 }
66 }
67 }
68
69 namespace {
70
SliceFromArray(const char * arr,size_t len)71 inline grpc_slice SliceFromArray(const char* arr, size_t len) {
72 return grpc_slice_from_copied_buffer(arr, len);
73 }
74
GetChannelInfoField(grpc_channel * channel,grpc_channel_info * channel_info,char *** channel_info_field)75 std::string GetChannelInfoField(grpc_channel* channel,
76 grpc_channel_info* channel_info,
77 char*** channel_info_field) {
78 char* value = nullptr;
79 memset(channel_info, 0, sizeof(*channel_info));
80 *channel_info_field = &value;
81 grpc_channel_get_info(channel, channel_info);
82 if (value == nullptr) return "";
83 std::string result = value;
84 gpr_free(value);
85 return result;
86 }
87
88 } // namespace
89
GetLoadBalancingPolicyName() const90 std::string Channel::GetLoadBalancingPolicyName() const {
91 grpc_channel_info channel_info;
92 return GetChannelInfoField(c_channel_, &channel_info,
93 &channel_info.lb_policy_name);
94 }
95
GetServiceConfigJSON() const96 std::string Channel::GetServiceConfigJSON() const {
97 grpc_channel_info channel_info;
98 return GetChannelInfoField(c_channel_, &channel_info,
99 &channel_info.service_config_json);
100 }
101
102 namespace experimental {
103
ChannelResetConnectionBackoff(Channel * channel)104 void ChannelResetConnectionBackoff(Channel* channel) {
105 grpc_channel_reset_connect_backoff(channel->c_channel_);
106 }
107
108 } // namespace experimental
109
CreateCallInternal(const grpc::internal::RpcMethod & method,grpc::ClientContext * context,grpc::CompletionQueue * cq,size_t interceptor_pos)110 grpc::internal::Call Channel::CreateCallInternal(
111 const grpc::internal::RpcMethod& method, grpc::ClientContext* context,
112 grpc::CompletionQueue* cq, size_t interceptor_pos) {
113 const bool kRegistered = method.channel_tag() && context->authority().empty();
114 grpc_call* c_call = nullptr;
115 if (kRegistered) {
116 c_call = grpc_channel_create_registered_call(
117 c_channel_, context->propagate_from_call_,
118 context->propagation_options_.c_bitmask(), cq->cq(),
119 method.channel_tag(), context->raw_deadline(), nullptr);
120 } else {
121 const ::std::string* host_str = nullptr;
122 if (!context->authority_.empty()) {
123 host_str = &context->authority_;
124 } else if (!host_.empty()) {
125 host_str = &host_;
126 }
127 grpc_slice method_slice =
128 SliceFromArray(method.name(), strlen(method.name()));
129 grpc_slice host_slice;
130 if (host_str != nullptr) {
131 host_slice = grpc::SliceFromCopiedString(*host_str);
132 }
133 c_call = grpc_channel_create_call(
134 c_channel_, context->propagate_from_call_,
135 context->propagation_options_.c_bitmask(), cq->cq(), method_slice,
136 host_str == nullptr ? nullptr : &host_slice, context->raw_deadline(),
137 nullptr);
138 grpc_slice_unref(method_slice);
139 if (host_str != nullptr) {
140 grpc_slice_unref(host_slice);
141 }
142 }
143 grpc_census_call_set_context(c_call, context->census_context());
144
145 // ClientRpcInfo should be set before call because set_call also checks
146 // whether the call has been cancelled, and if the call was cancelled, we
147 // should notify the interceptors too.
148 auto* info = context->set_client_rpc_info(
149 method.name(), method.suffix_for_stats(), method.method_type(), this,
150 interceptor_creators_, interceptor_pos);
151 context->set_call(c_call, shared_from_this());
152
153 return grpc::internal::Call(c_call, this, cq, info);
154 }
155
CreateCall(const grpc::internal::RpcMethod & method,grpc::ClientContext * context,CompletionQueue * cq)156 grpc::internal::Call Channel::CreateCall(
157 const grpc::internal::RpcMethod& method, grpc::ClientContext* context,
158 CompletionQueue* cq) {
159 return CreateCallInternal(method, context, cq, 0);
160 }
161
PerformOpsOnCall(grpc::internal::CallOpSetInterface * ops,grpc::internal::Call * call)162 void Channel::PerformOpsOnCall(grpc::internal::CallOpSetInterface* ops,
163 grpc::internal::Call* call) {
164 ops->FillOps(
165 call); // Make a copy of call. It's fine since Call just has pointers
166 }
167
RegisterMethod(const char * method)168 void* Channel::RegisterMethod(const char* method) {
169 return grpc_channel_register_call(
170 c_channel_, method, host_.empty() ? nullptr : host_.c_str(), nullptr);
171 }
172
GetState(bool try_to_connect)173 grpc_connectivity_state Channel::GetState(bool try_to_connect) {
174 return grpc_channel_check_connectivity_state(c_channel_, try_to_connect);
175 }
176
177 namespace {
178
179 class TagSaver final : public grpc::internal::CompletionQueueTag {
180 public:
TagSaver(void * tag)181 explicit TagSaver(void* tag) : tag_(tag) {}
~TagSaver()182 ~TagSaver() override {}
FinalizeResult(void ** tag,bool *)183 bool FinalizeResult(void** tag, bool* /*status*/) override {
184 *tag = tag_;
185 delete this;
186 return true;
187 }
188
189 private:
190 void* tag_;
191 };
192
193 } // namespace
194
NotifyOnStateChangeImpl(grpc_connectivity_state last_observed,gpr_timespec deadline,grpc::CompletionQueue * cq,void * tag)195 void Channel::NotifyOnStateChangeImpl(grpc_connectivity_state last_observed,
196 gpr_timespec deadline,
197 grpc::CompletionQueue* cq, void* tag) {
198 TagSaver* tag_saver = new TagSaver(tag);
199 grpc_channel_watch_connectivity_state(c_channel_, last_observed, deadline,
200 cq->cq(), tag_saver);
201 }
202
WaitForStateChangeImpl(grpc_connectivity_state last_observed,gpr_timespec deadline)203 bool Channel::WaitForStateChangeImpl(grpc_connectivity_state last_observed,
204 gpr_timespec deadline) {
205 grpc::CompletionQueue cq;
206 bool ok = false;
207 void* tag = nullptr;
208 NotifyOnStateChangeImpl(last_observed, deadline, &cq, nullptr);
209 cq.Next(&tag, &ok);
210 GPR_ASSERT(tag == nullptr);
211 return ok;
212 }
213
214 namespace {
215 class ShutdownCallback : public grpc_completion_queue_functor {
216 public:
ShutdownCallback()217 ShutdownCallback() {
218 functor_run = &ShutdownCallback::Run;
219 // Set inlineable to true since this callback is trivial and thus does not
220 // need to be run from the executor (triggering a thread hop). This should
221 // only be used by internal callbacks like this and not by user application
222 // code.
223 inlineable = true;
224 }
225 // TakeCQ takes ownership of the cq into the shutdown callback
226 // so that the shutdown callback will be responsible for destroying it
TakeCQ(grpc::CompletionQueue * cq)227 void TakeCQ(grpc::CompletionQueue* cq) { cq_ = cq; }
228
229 // The Run function will get invoked by the completion queue library
230 // when the shutdown is actually complete
Run(grpc_completion_queue_functor * cb,int)231 static void Run(grpc_completion_queue_functor* cb, int) {
232 auto* callback = static_cast<ShutdownCallback*>(cb);
233 delete callback->cq_;
234 delete callback;
235 }
236
237 private:
238 grpc::CompletionQueue* cq_ = nullptr;
239 };
240 } // namespace
241
CallbackCQ()242 ::grpc::CompletionQueue* Channel::CallbackCQ() {
243 // TODO(vjpai): Consider using a single global CQ for the default CQ
244 // if there is no explicit per-channel CQ registered
245 CompletionQueue* callback_cq = callback_cq_.load(std::memory_order_acquire);
246 if (callback_cq != nullptr) {
247 return callback_cq;
248 }
249 // The callback_cq_ wasn't already set, so grab a lock and set it up exactly
250 // once for this channel.
251 grpc::internal::MutexLock l(&mu_);
252 callback_cq = callback_cq_.load(std::memory_order_relaxed);
253 if (callback_cq == nullptr) {
254 if (grpc_iomgr_run_in_background()) {
255 // gRPC-core provides the backing needed for the preferred CQ type
256
257 auto* shutdown_callback = new ShutdownCallback;
258 callback_cq = new grpc::CompletionQueue(grpc_completion_queue_attributes{
259 GRPC_CQ_CURRENT_VERSION, GRPC_CQ_CALLBACK, GRPC_CQ_DEFAULT_POLLING,
260 shutdown_callback});
261
262 // Transfer ownership of the new cq to its own shutdown callback
263 shutdown_callback->TakeCQ(callback_cq);
264 } else {
265 // Otherwise we need to use the alternative CQ variant
266 callback_cq = CompletionQueue::CallbackAlternativeCQ();
267 }
268 callback_cq_.store(callback_cq, std::memory_order_release);
269 }
270 return callback_cq;
271 }
272
273 } // namespace grpc
274