3 * Copyright 2015 gRPC authors.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <grpcpp/channel.h>
25 #include <grpc/grpc.h>
26 #include <grpc/slice.h>
27 #include <grpc/support/alloc.h>
28 #include <grpc/support/log.h>
29 #include <grpc/support/sync.h>
30 #include <grpc/support/time.h>
31 #include <grpcpp/client_context.h>
32 #include <grpcpp/completion_queue.h>
33 #include <grpcpp/impl/call.h>
34 #include <grpcpp/impl/codegen/call_op_set.h>
35 #include <grpcpp/impl/codegen/completion_queue_tag.h>
36 #include <grpcpp/impl/grpc_library.h>
37 #include <grpcpp/impl/rpc_method.h>
38 #include <grpcpp/security/credentials.h>
39 #include <grpcpp/support/channel_arguments.h>
40 #include <grpcpp/support/config.h>
41 #include <grpcpp/support/status.h>
42 #include "src/core/lib/gpr/string.h"
43 #include "src/core/lib/surface/completion_queue.h"
47 static internal::GrpcLibraryInitializer g_gli_initializer;
49 const grpc::string& host, grpc_channel* channel,
51 std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
53 : host_(host), c_channel_(channel) {
54 interceptor_creators_ = std::move(interceptor_creators);
55 g_gli_initializer.summon();
59 grpc_channel_destroy(c_channel_);
60 if (callback_cq_ != nullptr) {
61 callback_cq_->Shutdown();
67 inline grpc_slice SliceFromArray(const char* arr, size_t len) {
68 return g_core_codegen_interface->grpc_slice_from_copied_buffer(arr, len);
71 grpc::string GetChannelInfoField(grpc_channel* channel,
72 grpc_channel_info* channel_info,
73 char*** channel_info_field) {
74 char* value = nullptr;
75 memset(channel_info, 0, sizeof(*channel_info));
76 *channel_info_field = &value;
77 grpc_channel_get_info(channel, channel_info);
78 if (value == nullptr) return "";
79 grpc::string result = value;
86 grpc::string Channel::GetLoadBalancingPolicyName() const {
87 grpc_channel_info channel_info;
88 return GetChannelInfoField(c_channel_, &channel_info,
89 &channel_info.lb_policy_name);
92 grpc::string Channel::GetServiceConfigJSON() const {
93 grpc_channel_info channel_info;
94 return GetChannelInfoField(c_channel_, &channel_info,
95 &channel_info.service_config_json);
98 namespace experimental {
100 void ChannelResetConnectionBackoff(Channel* channel) {
101 grpc_channel_reset_connect_backoff(channel->c_channel_);
104 } // namespace experimental
106 internal::Call Channel::CreateCallInternal(const internal::RpcMethod& method,
107 ClientContext* context,
109 size_t interceptor_pos) {
110 const bool kRegistered = method.channel_tag() && context->authority().empty();
111 grpc_call* c_call = nullptr;
113 c_call = grpc_channel_create_registered_call(
114 c_channel_, context->propagate_from_call_,
115 context->propagation_options_.c_bitmask(), cq->cq(),
116 method.channel_tag(), context->raw_deadline(), nullptr);
118 const string* host_str = nullptr;
119 if (!context->authority_.empty()) {
120 host_str = &context->authority_;
121 } else if (!host_.empty()) {
124 grpc_slice method_slice =
125 SliceFromArray(method.name(), strlen(method.name()));
126 grpc_slice host_slice;
127 if (host_str != nullptr) {
128 host_slice = SliceFromCopiedString(*host_str);
130 c_call = grpc_channel_create_call(
131 c_channel_, context->propagate_from_call_,
132 context->propagation_options_.c_bitmask(), cq->cq(), method_slice,
133 host_str == nullptr ? nullptr : &host_slice, context->raw_deadline(),
135 grpc_slice_unref(method_slice);
136 if (host_str != nullptr) {
137 grpc_slice_unref(host_slice);
140 grpc_census_call_set_context(c_call, context->census_context());
142 // ClientRpcInfo should be set before call because set_call also checks
143 // whether the call has been cancelled, and if the call was cancelled, we
144 // should notify the interceptors too/
146 context->set_client_rpc_info(method.name(), method.method_type(), this,
147 interceptor_creators_, interceptor_pos);
148 context->set_call(c_call, shared_from_this());
150 return internal::Call(c_call, this, cq, info);
153 internal::Call Channel::CreateCall(const internal::RpcMethod& method,
154 ClientContext* context,
155 CompletionQueue* cq) {
156 return CreateCallInternal(method, context, cq, 0);
159 void Channel::PerformOpsOnCall(internal::CallOpSetInterface* ops,
160 internal::Call* call) {
162 call); // Make a copy of call. It's fine since Call just has pointers
165 void* Channel::RegisterMethod(const char* method) {
166 return grpc_channel_register_call(
167 c_channel_, method, host_.empty() ? nullptr : host_.c_str(), nullptr);
170 grpc_connectivity_state Channel::GetState(bool try_to_connect) {
171 return grpc_channel_check_connectivity_state(c_channel_, try_to_connect);
176 class TagSaver final : public internal::CompletionQueueTag {
178 explicit TagSaver(void* tag) : tag_(tag) {}
179 ~TagSaver() override {}
180 bool FinalizeResult(void** tag, bool* status) override {
192 void Channel::NotifyOnStateChangeImpl(grpc_connectivity_state last_observed,
193 gpr_timespec deadline,
194 CompletionQueue* cq, void* tag) {
195 TagSaver* tag_saver = new TagSaver(tag);
196 grpc_channel_watch_connectivity_state(c_channel_, last_observed, deadline,
197 cq->cq(), tag_saver);
200 bool Channel::WaitForStateChangeImpl(grpc_connectivity_state last_observed,
201 gpr_timespec deadline) {
205 NotifyOnStateChangeImpl(last_observed, deadline, &cq, nullptr);
207 GPR_ASSERT(tag == nullptr);
212 class ShutdownCallback : public grpc_experimental_completion_queue_functor {
214 ShutdownCallback() { functor_run = &ShutdownCallback::Run; }
215 // TakeCQ takes ownership of the cq into the shutdown callback
216 // so that the shutdown callback will be responsible for destroying it
217 void TakeCQ(CompletionQueue* cq) { cq_ = cq; }
219 // The Run function will get invoked by the completion queue library
220 // when the shutdown is actually complete
221 static void Run(grpc_experimental_completion_queue_functor* cb, int) {
222 auto* callback = static_cast<ShutdownCallback*>(cb);
223 delete callback->cq_;
228 CompletionQueue* cq_ = nullptr;
232 CompletionQueue* Channel::CallbackCQ() {
233 // TODO(vjpai): Consider using a single global CQ for the default CQ
234 // if there is no explicit per-channel CQ registered
235 std::lock_guard<std::mutex> l(mu_);
236 if (callback_cq_ == nullptr) {
237 auto* shutdown_callback = new ShutdownCallback;
238 callback_cq_ = new CompletionQueue(grpc_completion_queue_attributes{
239 GRPC_CQ_CURRENT_VERSION, GRPC_CQ_CALLBACK, GRPC_CQ_DEFAULT_POLLING,
242 // Transfer ownership of the new cq to its own shutdown callback
243 shutdown_callback->TakeCQ(callback_cq_);