db59d4d84169407fc0b030a6c4943f6264554ec1
[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 namespace grpc {
46
47 static internal::GrpcLibraryInitializer g_gli_initializer;
48 Channel::Channel(
49     const grpc::string& host, grpc_channel* channel,
50     std::vector<
51         std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
52         interceptor_creators)
53     : host_(host), c_channel_(channel) {
54   interceptor_creators_ = std::move(interceptor_creators);
55   g_gli_initializer.summon();
56 }
57
58 Channel::~Channel() {
59   grpc_channel_destroy(c_channel_);
60   if (callback_cq_ != nullptr) {
61     callback_cq_->Shutdown();
62   }
63 }
64
65 namespace {
66
67 inline grpc_slice SliceFromArray(const char* arr, size_t len) {
68   return g_core_codegen_interface->grpc_slice_from_copied_buffer(arr, len);
69 }
70
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;
80   gpr_free(value);
81   return result;
82 }
83
84 }  // namespace
85
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);
90 }
91
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);
96 }
97
98 namespace experimental {
99
100 void ChannelResetConnectionBackoff(Channel* channel) {
101   grpc_channel_reset_connect_backoff(channel->c_channel_);
102 }
103
104 }  // namespace experimental
105
106 internal::Call Channel::CreateCallInternal(const internal::RpcMethod& method,
107                                            ClientContext* context,
108                                            CompletionQueue* cq,
109                                            size_t interceptor_pos) {
110   const bool kRegistered = method.channel_tag() && context->authority().empty();
111   grpc_call* c_call = nullptr;
112   if (kRegistered) {
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);
117   } else {
118     const string* host_str = nullptr;
119     if (!context->authority_.empty()) {
120       host_str = &context->authority_;
121     } else if (!host_.empty()) {
122       host_str = &host_;
123     }
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);
129     }
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(),
134         nullptr);
135     grpc_slice_unref(method_slice);
136     if (host_str != nullptr) {
137       grpc_slice_unref(host_slice);
138     }
139   }
140   grpc_census_call_set_context(c_call, context->census_context());
141
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/
145   auto* info =
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());
149
150   return internal::Call(c_call, this, cq, info);
151 }
152
153 internal::Call Channel::CreateCall(const internal::RpcMethod& method,
154                                    ClientContext* context,
155                                    CompletionQueue* cq) {
156   return CreateCallInternal(method, context, cq, 0);
157 }
158
159 void Channel::PerformOpsOnCall(internal::CallOpSetInterface* ops,
160                                internal::Call* call) {
161   ops->FillOps(
162       call);  // Make a copy of call. It's fine since Call just has pointers
163 }
164
165 void* Channel::RegisterMethod(const char* method) {
166   return grpc_channel_register_call(
167       c_channel_, method, host_.empty() ? nullptr : host_.c_str(), nullptr);
168 }
169
170 grpc_connectivity_state Channel::GetState(bool try_to_connect) {
171   return grpc_channel_check_connectivity_state(c_channel_, try_to_connect);
172 }
173
174 namespace {
175
176 class TagSaver final : public internal::CompletionQueueTag {
177  public:
178   explicit TagSaver(void* tag) : tag_(tag) {}
179   ~TagSaver() override {}
180   bool FinalizeResult(void** tag, bool* status) override {
181     *tag = tag_;
182     delete this;
183     return true;
184   }
185
186  private:
187   void* tag_;
188 };
189
190 }  // namespace
191
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);
198 }
199
200 bool Channel::WaitForStateChangeImpl(grpc_connectivity_state last_observed,
201                                      gpr_timespec deadline) {
202   CompletionQueue cq;
203   bool ok = false;
204   void* tag = nullptr;
205   NotifyOnStateChangeImpl(last_observed, deadline, &cq, nullptr);
206   cq.Next(&tag, &ok);
207   GPR_ASSERT(tag == nullptr);
208   return ok;
209 }
210
211 namespace {
212 class ShutdownCallback : public grpc_experimental_completion_queue_functor {
213  public:
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; }
218
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_;
224     delete callback;
225   }
226
227  private:
228   CompletionQueue* cq_ = nullptr;
229 };
230 }  // namespace
231
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,
240         shutdown_callback});
241
242     // Transfer ownership of the new cq to its own shutdown callback
243     shutdown_callback->TakeCQ(callback_cq_);
244   }
245   return callback_cq_;
246 }
247
248 }  // namespace grpc