Imported Upstream version 1.22.0
[platform/upstream/grpc.git] / src / cpp / client / channel_cc.cc
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 #include <mutex>
24
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"
44
45 void ::grpc::experimental::ChannelResetConnectionBackoff(Channel* channel) {
46   grpc_impl::experimental::ChannelResetConnectionBackoff(channel);
47 }
48
49 namespace grpc_impl {
50
51 static ::grpc::internal::GrpcLibraryInitializer g_gli_initializer;
52 Channel::Channel(const grpc::string& host, grpc_channel* channel,
53                  std::vector<std::unique_ptr<
54                      ::grpc::experimental::ClientInterceptorFactoryInterface>>
55                      interceptor_creators)
56     : host_(host), c_channel_(channel) {
57   interceptor_creators_ = std::move(interceptor_creators);
58   g_gli_initializer.summon();
59 }
60
61 Channel::~Channel() {
62   grpc_channel_destroy(c_channel_);
63   if (callback_cq_ != nullptr) {
64     callback_cq_->Shutdown();
65   }
66 }
67
68 namespace {
69
70 inline grpc_slice SliceFromArray(const char* arr, size_t len) {
71   return ::grpc::g_core_codegen_interface->grpc_slice_from_copied_buffer(arr,
72                                                                          len);
73 }
74
75 grpc::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   grpc::string result = value;
84   gpr_free(value);
85   return result;
86 }
87
88 }  // namespace
89
90 grpc::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
96 grpc::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
104 void ChannelResetConnectionBackoff(Channel* channel) {
105   grpc_channel_reset_connect_backoff(channel->c_channel_);
106 }
107
108 }  // namespace experimental
109
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 ::grpc::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 =
149       context->set_client_rpc_info(method.name(), 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
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
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
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
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:
181   explicit TagSaver(void* tag) : tag_(tag) {}
182   ~TagSaver() override {}
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
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
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_experimental_completion_queue_functor {
216  public:
217   ShutdownCallback() { functor_run = &ShutdownCallback::Run; }
218   // TakeCQ takes ownership of the cq into the shutdown callback
219   // so that the shutdown callback will be responsible for destroying it
220   void TakeCQ(::grpc::CompletionQueue* cq) { cq_ = cq; }
221
222   // The Run function will get invoked by the completion queue library
223   // when the shutdown is actually complete
224   static void Run(grpc_experimental_completion_queue_functor* cb, int) {
225     auto* callback = static_cast<ShutdownCallback*>(cb);
226     delete callback->cq_;
227     delete callback;
228   }
229
230  private:
231   ::grpc::CompletionQueue* cq_ = nullptr;
232 };
233 }  // namespace
234
235 ::grpc::CompletionQueue* Channel::CallbackCQ() {
236   // TODO(vjpai): Consider using a single global CQ for the default CQ
237   // if there is no explicit per-channel CQ registered
238   grpc::internal::MutexLock l(&mu_);
239   if (callback_cq_ == nullptr) {
240     auto* shutdown_callback = new ShutdownCallback;
241     callback_cq_ = new ::grpc::CompletionQueue(grpc_completion_queue_attributes{
242         GRPC_CQ_CURRENT_VERSION, GRPC_CQ_CALLBACK, GRPC_CQ_DEFAULT_POLLING,
243         shutdown_callback});
244
245     // Transfer ownership of the new cq to its own shutdown callback
246     shutdown_callback->TakeCQ(callback_cq_);
247   }
248   return callback_cq_;
249 }
250
251 }  // namespace grpc_impl