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 <grpcpp/channel.h>
20
21 #include <cstring>
22 #include <memory>
23
24 #include <grpc/grpc.h>
25 #include <grpc/slice.h>
26 #include <grpc/support/alloc.h>
27 #include <grpc/support/log.h>
28 #include <grpc/support/sync.h>
29 #include <grpc/support/time.h>
30 #include <grpcpp/client_context.h>
31 #include <grpcpp/completion_queue.h>
32 #include <grpcpp/impl/call.h>
33 #include <grpcpp/impl/codegen/call_op_set.h>
34 #include <grpcpp/impl/codegen/completion_queue_tag.h>
35 #include <grpcpp/impl/grpc_library.h>
36 #include <grpcpp/impl/rpc_method.h>
37 #include <grpcpp/security/credentials.h>
38 #include <grpcpp/support/channel_arguments.h>
39 #include <grpcpp/support/config.h>
40 #include <grpcpp/support/status.h>
41 #include "src/core/lib/gpr/string.h"
42 #include "src/core/lib/surface/completion_queue.h"
43
44 namespace grpc {
45
46 static ::grpc::internal::GrpcLibraryInitializer g_gli_initializer;
Channel(const std::string & host,grpc_channel * channel,std::vector<std::unique_ptr<::grpc::experimental::ClientInterceptorFactoryInterface>> interceptor_creators)47 Channel::Channel(const std::string& host, grpc_channel* channel,
48 std::vector<std::unique_ptr<
49 ::grpc::experimental::ClientInterceptorFactoryInterface>>
50 interceptor_creators)
51 : host_(host), c_channel_(channel) {
52 interceptor_creators_ = std::move(interceptor_creators);
53 g_gli_initializer.summon();
54 }
55
~Channel()56 Channel::~Channel() {
57 grpc_channel_destroy(c_channel_);
58 if (callback_cq_ != nullptr) {
59 callback_cq_->Shutdown();
60 }
61 }
62
63 namespace {
64
SliceFromArray(const char * arr,size_t len)65 inline grpc_slice SliceFromArray(const char* arr, size_t len) {
66 return g_core_codegen_interface->grpc_slice_from_copied_buffer(arr, len);
67 }
68
GetChannelInfoField(grpc_channel * channel,grpc_channel_info * channel_info,char *** channel_info_field)69 std::string GetChannelInfoField(grpc_channel* channel,
70 grpc_channel_info* channel_info,
71 char*** channel_info_field) {
72 char* value = nullptr;
73 memset(channel_info, 0, sizeof(*channel_info));
74 *channel_info_field = &value;
75 grpc_channel_get_info(channel, channel_info);
76 if (value == nullptr) return "";
77 std::string result = value;
78 gpr_free(value);
79 return result;
80 }
81
82 } // namespace
83
GetLoadBalancingPolicyName() const84 std::string Channel::GetLoadBalancingPolicyName() const {
85 grpc_channel_info channel_info;
86 return GetChannelInfoField(c_channel_, &channel_info,
87 &channel_info.lb_policy_name);
88 }
89
GetServiceConfigJSON() const90 std::string Channel::GetServiceConfigJSON() const {
91 grpc_channel_info channel_info;
92 return GetChannelInfoField(c_channel_, &channel_info,
93 &channel_info.service_config_json);
94 }
95
96 namespace experimental {
97
ChannelResetConnectionBackoff(Channel * channel)98 void ChannelResetConnectionBackoff(Channel* channel) {
99 grpc_channel_reset_connect_backoff(channel->c_channel_);
100 }
101
102 } // namespace experimental
103
CreateCallInternal(const::grpc::internal::RpcMethod & method,::grpc::ClientContext * context,::grpc::CompletionQueue * cq,size_t interceptor_pos)104 ::grpc::internal::Call Channel::CreateCallInternal(
105 const ::grpc::internal::RpcMethod& method, ::grpc::ClientContext* context,
106 ::grpc::CompletionQueue* cq, size_t interceptor_pos) {
107 const bool kRegistered = method.channel_tag() && context->authority().empty();
108 grpc_call* c_call = nullptr;
109 if (kRegistered) {
110 c_call = grpc_channel_create_registered_call(
111 c_channel_, context->propagate_from_call_,
112 context->propagation_options_.c_bitmask(), cq->cq(),
113 method.channel_tag(), context->raw_deadline(), nullptr);
114 } else {
115 const ::std::string* host_str = nullptr;
116 if (!context->authority_.empty()) {
117 host_str = &context->authority_;
118 } else if (!host_.empty()) {
119 host_str = &host_;
120 }
121 grpc_slice method_slice =
122 SliceFromArray(method.name(), strlen(method.name()));
123 grpc_slice host_slice;
124 if (host_str != nullptr) {
125 host_slice = ::grpc::SliceFromCopiedString(*host_str);
126 }
127 c_call = grpc_channel_create_call(
128 c_channel_, context->propagate_from_call_,
129 context->propagation_options_.c_bitmask(), cq->cq(), method_slice,
130 host_str == nullptr ? nullptr : &host_slice, context->raw_deadline(),
131 nullptr);
132 grpc_slice_unref(method_slice);
133 if (host_str != nullptr) {
134 grpc_slice_unref(host_slice);
135 }
136 }
137 grpc_census_call_set_context(c_call, context->census_context());
138
139 // ClientRpcInfo should be set before call because set_call also checks
140 // whether the call has been cancelled, and if the call was cancelled, we
141 // should notify the interceptors too.
142 auto* info =
143 context->set_client_rpc_info(method.name(), method.method_type(), this,
144 interceptor_creators_, interceptor_pos);
145 context->set_call(c_call, shared_from_this());
146
147 return ::grpc::internal::Call(c_call, this, cq, info);
148 }
149
CreateCall(const::grpc::internal::RpcMethod & method,::grpc::ClientContext * context,CompletionQueue * cq)150 ::grpc::internal::Call Channel::CreateCall(
151 const ::grpc::internal::RpcMethod& method, ::grpc::ClientContext* context,
152 CompletionQueue* cq) {
153 return CreateCallInternal(method, context, cq, 0);
154 }
155
PerformOpsOnCall(::grpc::internal::CallOpSetInterface * ops,::grpc::internal::Call * call)156 void Channel::PerformOpsOnCall(::grpc::internal::CallOpSetInterface* ops,
157 ::grpc::internal::Call* call) {
158 ops->FillOps(
159 call); // Make a copy of call. It's fine since Call just has pointers
160 }
161
RegisterMethod(const char * method)162 void* Channel::RegisterMethod(const char* method) {
163 return grpc_channel_register_call(
164 c_channel_, method, host_.empty() ? nullptr : host_.c_str(), nullptr);
165 }
166
GetState(bool try_to_connect)167 grpc_connectivity_state Channel::GetState(bool try_to_connect) {
168 return grpc_channel_check_connectivity_state(c_channel_, try_to_connect);
169 }
170
171 namespace {
172
173 class TagSaver final : public ::grpc::internal::CompletionQueueTag {
174 public:
TagSaver(void * tag)175 explicit TagSaver(void* tag) : tag_(tag) {}
~TagSaver()176 ~TagSaver() override {}
FinalizeResult(void ** tag,bool *)177 bool FinalizeResult(void** tag, bool* /*status*/) override {
178 *tag = tag_;
179 delete this;
180 return true;
181 }
182
183 private:
184 void* tag_;
185 };
186
187 } // namespace
188
NotifyOnStateChangeImpl(grpc_connectivity_state last_observed,gpr_timespec deadline,::grpc::CompletionQueue * cq,void * tag)189 void Channel::NotifyOnStateChangeImpl(grpc_connectivity_state last_observed,
190 gpr_timespec deadline,
191 ::grpc::CompletionQueue* cq, void* tag) {
192 TagSaver* tag_saver = new TagSaver(tag);
193 grpc_channel_watch_connectivity_state(c_channel_, last_observed, deadline,
194 cq->cq(), tag_saver);
195 }
196
WaitForStateChangeImpl(grpc_connectivity_state last_observed,gpr_timespec deadline)197 bool Channel::WaitForStateChangeImpl(grpc_connectivity_state last_observed,
198 gpr_timespec deadline) {
199 ::grpc::CompletionQueue cq;
200 bool ok = false;
201 void* tag = nullptr;
202 NotifyOnStateChangeImpl(last_observed, deadline, &cq, nullptr);
203 cq.Next(&tag, &ok);
204 GPR_ASSERT(tag == nullptr);
205 return ok;
206 }
207
208 namespace {
209 class ShutdownCallback : public grpc_experimental_completion_queue_functor {
210 public:
ShutdownCallback()211 ShutdownCallback() {
212 functor_run = &ShutdownCallback::Run;
213 // Set inlineable to true since this callback is trivial and thus does not
214 // need to be run from the executor (triggering a thread hop). This should
215 // only be used by internal callbacks like this and not by user application
216 // code.
217 inlineable = true;
218 }
219 // TakeCQ takes ownership of the cq into the shutdown callback
220 // so that the shutdown callback will be responsible for destroying it
TakeCQ(::grpc::CompletionQueue * cq)221 void TakeCQ(::grpc::CompletionQueue* cq) { cq_ = cq; }
222
223 // The Run function will get invoked by the completion queue library
224 // when the shutdown is actually complete
Run(grpc_experimental_completion_queue_functor * cb,int)225 static void Run(grpc_experimental_completion_queue_functor* cb, int) {
226 auto* callback = static_cast<ShutdownCallback*>(cb);
227 delete callback->cq_;
228 delete callback;
229 }
230
231 private:
232 ::grpc::CompletionQueue* cq_ = nullptr;
233 };
234 } // namespace
235
CallbackCQ()236 ::grpc::CompletionQueue* Channel::CallbackCQ() {
237 // TODO(vjpai): Consider using a single global CQ for the default CQ
238 // if there is no explicit per-channel CQ registered
239 grpc::internal::MutexLock l(&mu_);
240 if (callback_cq_ == nullptr) {
241 auto* shutdown_callback = new ShutdownCallback;
242 callback_cq_ = new ::grpc::CompletionQueue(grpc_completion_queue_attributes{
243 GRPC_CQ_CURRENT_VERSION, GRPC_CQ_CALLBACK, GRPC_CQ_DEFAULT_POLLING,
244 shutdown_callback});
245
246 // Transfer ownership of the new cq to its own shutdown callback
247 shutdown_callback->TakeCQ(callback_cq_);
248 }
249 return callback_cq_;
250 }
251
252 } // namespace grpc
253