channel_cc.cc 9.2 KB

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