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