channel_cc.cc 8.3 KB

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