completion_queue.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. /*
  2. *
  3. * Copyright 2015-2016 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. /// A completion queue implements a concurrent producer-consumer queue, with
  19. /// two main API-exposed methods: \a Next and \a AsyncNext. These
  20. /// methods are the essential component of the gRPC C++ asynchronous API.
  21. /// There is also a \a Shutdown method to indicate that a given completion queue
  22. /// will no longer have regular events. This must be called before the
  23. /// completion queue is destroyed.
  24. /// All completion queue APIs are thread-safe and may be used concurrently with
  25. /// any other completion queue API invocation; it is acceptable to have
  26. /// multiple threads calling \a Next or \a AsyncNext on the same or different
  27. /// completion queues, or to call these methods concurrently with a \a Shutdown
  28. /// elsewhere.
  29. /// \remark{All other API calls on completion queue should be completed before
  30. /// a completion queue destructor is called.}
  31. #ifndef GRPCPP_IMPL_CODEGEN_COMPLETION_QUEUE_H
  32. #define GRPCPP_IMPL_CODEGEN_COMPLETION_QUEUE_H
  33. // IWYU pragma: private, include <grpcpp/completion_queue.h>
  34. #include <list>
  35. #include <grpc/impl/codegen/atm.h>
  36. #include <grpcpp/impl/codegen/completion_queue_tag.h>
  37. #include <grpcpp/impl/codegen/core_codegen_interface.h>
  38. #include <grpcpp/impl/codegen/grpc_library.h>
  39. #include <grpcpp/impl/codegen/rpc_service_method.h>
  40. #include <grpcpp/impl/codegen/status.h>
  41. #include <grpcpp/impl/codegen/sync.h>
  42. #include <grpcpp/impl/codegen/time.h>
  43. struct grpc_completion_queue;
  44. namespace grpc {
  45. template <class R>
  46. class ClientReader;
  47. template <class W>
  48. class ClientWriter;
  49. template <class W, class R>
  50. class ClientReaderWriter;
  51. template <class R>
  52. class ServerReader;
  53. template <class W>
  54. class ServerWriter;
  55. namespace internal {
  56. template <class W, class R>
  57. class ServerReaderWriterBody;
  58. template <class ResponseType>
  59. void UnaryRunHandlerHelper(
  60. const grpc::internal::MethodHandler::HandlerParameter&, ResponseType*,
  61. grpc::Status&);
  62. template <class ServiceType, class RequestType, class ResponseType,
  63. class BaseRequestType, class BaseResponseType>
  64. class RpcMethodHandler;
  65. template <class ServiceType, class RequestType, class ResponseType>
  66. class ClientStreamingHandler;
  67. template <class ServiceType, class RequestType, class ResponseType>
  68. class ServerStreamingHandler;
  69. template <class Streamer, bool WriteNeeded>
  70. class TemplatedBidiStreamingHandler;
  71. template <grpc::StatusCode code>
  72. class ErrorMethodHandler;
  73. } // namespace internal
  74. class Channel;
  75. class ChannelInterface;
  76. class Server;
  77. class ServerBuilder;
  78. class ServerContextBase;
  79. class ServerInterface;
  80. namespace internal {
  81. class CompletionQueueTag;
  82. class RpcMethod;
  83. template <class InputMessage, class OutputMessage>
  84. class BlockingUnaryCallImpl;
  85. template <class Op1, class Op2, class Op3, class Op4, class Op5, class Op6>
  86. class CallOpSet;
  87. } // namespace internal
  88. extern CoreCodegenInterface* g_core_codegen_interface;
  89. /// A thin wrapper around \ref grpc_completion_queue (see \ref
  90. /// src/core/lib/surface/completion_queue.h).
  91. /// See \ref doc/cpp/perf_notes.md for notes on best practices for high
  92. /// performance servers.
  93. class CompletionQueue : private grpc::GrpcLibraryCodegen {
  94. public:
  95. /// Default constructor. Implicitly creates a \a grpc_completion_queue
  96. /// instance.
  97. CompletionQueue()
  98. : CompletionQueue(grpc_completion_queue_attributes{
  99. GRPC_CQ_CURRENT_VERSION, GRPC_CQ_NEXT, GRPC_CQ_DEFAULT_POLLING,
  100. nullptr}) {}
  101. /// Wrap \a take, taking ownership of the instance.
  102. ///
  103. /// \param take The completion queue instance to wrap. Ownership is taken.
  104. explicit CompletionQueue(grpc_completion_queue* take);
  105. /// Destructor. Destroys the owned wrapped completion queue / instance.
  106. ~CompletionQueue() override {
  107. grpc::g_core_codegen_interface->grpc_completion_queue_destroy(cq_);
  108. }
  109. /// Tri-state return for AsyncNext: SHUTDOWN, GOT_EVENT, TIMEOUT.
  110. enum NextStatus {
  111. SHUTDOWN, ///< The completion queue has been shutdown and fully-drained
  112. GOT_EVENT, ///< Got a new event; \a tag will be filled in with its
  113. ///< associated value; \a ok indicating its success.
  114. TIMEOUT ///< deadline was reached.
  115. };
  116. /// Read from the queue, blocking until an event is available or the queue is
  117. /// shutting down.
  118. ///
  119. /// \param[out] tag Updated to point to the read event's tag.
  120. /// \param[out] ok true if read a successful event, false otherwise.
  121. ///
  122. /// Note that each tag sent to the completion queue (through RPC operations
  123. /// or alarms) will be delivered out of the completion queue by a call to
  124. /// Next (or a related method), regardless of whether the operation succeeded
  125. /// or not. Success here means that this operation completed in the normal
  126. /// valid manner.
  127. ///
  128. /// Server-side RPC request: \a ok indicates that the RPC has indeed
  129. /// been started. If it is false, the server has been Shutdown
  130. /// before this particular call got matched to an incoming RPC.
  131. ///
  132. /// Client-side StartCall/RPC invocation: \a ok indicates that the RPC is
  133. /// going to go to the wire. If it is false, it not going to the wire. This
  134. /// would happen if the channel is either permanently broken or
  135. /// transiently broken but with the fail-fast option. (Note that async unary
  136. /// RPCs don't post a CQ tag at this point, nor do client-streaming
  137. /// or bidi-streaming RPCs that have the initial metadata corked option set.)
  138. ///
  139. /// Client-side Write, Client-side WritesDone, Server-side Write,
  140. /// Server-side Finish, Server-side SendInitialMetadata (which is
  141. /// typically included in Write or Finish when not done explicitly):
  142. /// \a ok means that the data/metadata/status/etc is going to go to the
  143. /// wire. If it is false, it not going to the wire because the call
  144. /// is already dead (i.e., canceled, deadline expired, other side
  145. /// dropped the channel, etc).
  146. ///
  147. /// Client-side Read, Server-side Read, Client-side
  148. /// RecvInitialMetadata (which is typically included in Read if not
  149. /// done explicitly): \a ok indicates whether there is a valid message
  150. /// that got read. If not, you know that there are certainly no more
  151. /// messages that can ever be read from this stream. For the client-side
  152. /// operations, this only happens because the call is dead. For the
  153. /// server-sider operation, though, this could happen because the client
  154. /// has done a WritesDone already.
  155. ///
  156. /// Client-side Finish: \a ok should always be true
  157. ///
  158. /// Server-side AsyncNotifyWhenDone: \a ok should always be true
  159. ///
  160. /// Alarm: \a ok is true if it expired, false if it was canceled
  161. ///
  162. /// \return true if got an event, false if the queue is fully drained and
  163. /// shut down.
  164. bool Next(void** tag, bool* ok) {
  165. // Check return type == GOT_EVENT... cases:
  166. // SHUTDOWN - queue has been shutdown, return false.
  167. // TIMEOUT - we passed infinity time => queue has been shutdown, return
  168. // false.
  169. // GOT_EVENT - we actually got an event, return true.
  170. return (AsyncNextInternal(tag, ok,
  171. grpc::g_core_codegen_interface->gpr_inf_future(
  172. GPR_CLOCK_REALTIME)) == GOT_EVENT);
  173. }
  174. /// Read from the queue, blocking up to \a deadline (or the queue's shutdown).
  175. /// Both \a tag and \a ok are updated upon success (if an event is available
  176. /// within the \a deadline). A \a tag points to an arbitrary location usually
  177. /// employed to uniquely identify an event.
  178. ///
  179. /// \param[out] tag Upon success, updated to point to the event's tag.
  180. /// \param[out] ok Upon success, true if a successful event, false otherwise
  181. /// See documentation for CompletionQueue::Next for explanation of ok
  182. /// \param[in] deadline How long to block in wait for an event.
  183. ///
  184. /// \return The type of event read.
  185. template <typename T>
  186. NextStatus AsyncNext(void** tag, bool* ok, const T& deadline) {
  187. grpc::TimePoint<T> deadline_tp(deadline);
  188. return AsyncNextInternal(tag, ok, deadline_tp.raw_time());
  189. }
  190. /// EXPERIMENTAL
  191. /// First executes \a F, then reads from the queue, blocking up to
  192. /// \a deadline (or the queue's shutdown).
  193. /// Both \a tag and \a ok are updated upon success (if an event is available
  194. /// within the \a deadline). A \a tag points to an arbitrary location usually
  195. /// employed to uniquely identify an event.
  196. ///
  197. /// \param[in] f Function to execute before calling AsyncNext on this queue.
  198. /// \param[out] tag Upon success, updated to point to the event's tag.
  199. /// \param[out] ok Upon success, true if read a regular event, false
  200. /// otherwise.
  201. /// \param[in] deadline How long to block in wait for an event.
  202. ///
  203. /// \return The type of event read.
  204. template <typename T, typename F>
  205. NextStatus DoThenAsyncNext(F&& f, void** tag, bool* ok, const T& deadline) {
  206. CompletionQueueTLSCache cache = CompletionQueueTLSCache(this);
  207. f();
  208. if (cache.Flush(tag, ok)) {
  209. return GOT_EVENT;
  210. } else {
  211. return AsyncNext(tag, ok, deadline);
  212. }
  213. }
  214. /// Request the shutdown of the queue.
  215. ///
  216. /// \warning This method must be called at some point if this completion queue
  217. /// is accessed with Next or AsyncNext. \a Next will not return false
  218. /// until this method has been called and all pending tags have been drained.
  219. /// (Likewise for \a AsyncNext returning \a NextStatus::SHUTDOWN .)
  220. /// Only once either one of these methods does that (that is, once the queue
  221. /// has been \em drained) can an instance of this class be destroyed.
  222. /// Also note that applications must ensure that no work is enqueued on this
  223. /// completion queue after this method is called.
  224. void Shutdown();
  225. /// Returns a \em raw pointer to the underlying \a grpc_completion_queue
  226. /// instance.
  227. ///
  228. /// \warning Remember that the returned instance is owned. No transfer of
  229. /// owership is performed.
  230. grpc_completion_queue* cq() { return cq_; }
  231. protected:
  232. /// Private constructor of CompletionQueue only visible to friend classes
  233. explicit CompletionQueue(const grpc_completion_queue_attributes& attributes) {
  234. cq_ = grpc::g_core_codegen_interface->grpc_completion_queue_create(
  235. grpc::g_core_codegen_interface->grpc_completion_queue_factory_lookup(
  236. &attributes),
  237. &attributes, nullptr);
  238. InitialAvalanching(); // reserve this for the future shutdown
  239. }
  240. private:
  241. // Friends for access to server registration lists that enable checking and
  242. // logging on shutdown
  243. friend class grpc::ServerBuilder;
  244. friend class grpc::Server;
  245. // Friend synchronous wrappers so that they can access Pluck(), which is
  246. // a semi-private API geared towards the synchronous implementation.
  247. template <class R>
  248. friend class grpc::ClientReader;
  249. template <class W>
  250. friend class grpc::ClientWriter;
  251. template <class W, class R>
  252. friend class grpc::ClientReaderWriter;
  253. template <class R>
  254. friend class grpc::ServerReader;
  255. template <class W>
  256. friend class grpc::ServerWriter;
  257. template <class W, class R>
  258. friend class grpc::internal::ServerReaderWriterBody;
  259. template <class ResponseType>
  260. friend void grpc::internal::UnaryRunHandlerHelper(
  261. const grpc::internal::MethodHandler::HandlerParameter&, ResponseType*,
  262. grpc::Status&);
  263. template <class ServiceType, class RequestType, class ResponseType>
  264. friend class grpc::internal::ClientStreamingHandler;
  265. template <class ServiceType, class RequestType, class ResponseType>
  266. friend class grpc::internal::ServerStreamingHandler;
  267. template <class Streamer, bool WriteNeeded>
  268. friend class grpc::internal::TemplatedBidiStreamingHandler;
  269. template <grpc::StatusCode code>
  270. friend class grpc::internal::ErrorMethodHandler;
  271. friend class grpc::ServerContextBase;
  272. friend class grpc::ServerInterface;
  273. template <class InputMessage, class OutputMessage>
  274. friend class grpc::internal::BlockingUnaryCallImpl;
  275. // Friends that need access to constructor for callback CQ
  276. friend class grpc::Channel;
  277. // For access to Register/CompleteAvalanching
  278. template <class Op1, class Op2, class Op3, class Op4, class Op5, class Op6>
  279. friend class grpc::internal::CallOpSet;
  280. /// EXPERIMENTAL
  281. /// Creates a Thread Local cache to store the first event
  282. /// On this completion queue queued from this thread. Once
  283. /// initialized, it must be flushed on the same thread.
  284. class CompletionQueueTLSCache {
  285. public:
  286. explicit CompletionQueueTLSCache(CompletionQueue* cq);
  287. ~CompletionQueueTLSCache();
  288. bool Flush(void** tag, bool* ok);
  289. private:
  290. CompletionQueue* cq_;
  291. bool flushed_;
  292. };
  293. NextStatus AsyncNextInternal(void** tag, bool* ok, gpr_timespec deadline);
  294. /// Wraps \a grpc_completion_queue_pluck.
  295. /// \warning Must not be mixed with calls to \a Next.
  296. bool Pluck(grpc::internal::CompletionQueueTag* tag) {
  297. auto deadline =
  298. grpc::g_core_codegen_interface->gpr_inf_future(GPR_CLOCK_REALTIME);
  299. while (true) {
  300. auto ev = grpc::g_core_codegen_interface->grpc_completion_queue_pluck(
  301. cq_, tag, deadline, nullptr);
  302. bool ok = ev.success != 0;
  303. void* ignored = tag;
  304. if (tag->FinalizeResult(&ignored, &ok)) {
  305. GPR_CODEGEN_ASSERT(ignored == tag);
  306. return ok;
  307. }
  308. }
  309. }
  310. /// Performs a single polling pluck on \a tag.
  311. /// \warning Must not be mixed with calls to \a Next.
  312. ///
  313. /// TODO: sreek - This calls tag->FinalizeResult() even if the cq_ is already
  314. /// shutdown. This is most likely a bug and if it is a bug, then change this
  315. /// implementation to simple call the other TryPluck function with a zero
  316. /// timeout. i.e:
  317. /// TryPluck(tag, gpr_time_0(GPR_CLOCK_REALTIME))
  318. void TryPluck(grpc::internal::CompletionQueueTag* tag) {
  319. auto deadline =
  320. grpc::g_core_codegen_interface->gpr_time_0(GPR_CLOCK_REALTIME);
  321. auto ev = grpc::g_core_codegen_interface->grpc_completion_queue_pluck(
  322. cq_, tag, deadline, nullptr);
  323. if (ev.type == GRPC_QUEUE_TIMEOUT) return;
  324. bool ok = ev.success != 0;
  325. void* ignored = tag;
  326. // the tag must be swallowed if using TryPluck
  327. GPR_CODEGEN_ASSERT(!tag->FinalizeResult(&ignored, &ok));
  328. }
  329. /// Performs a single polling pluck on \a tag. Calls tag->FinalizeResult if
  330. /// the pluck() was successful and returned the tag.
  331. ///
  332. /// This exects tag->FinalizeResult (if called) to return 'false' i.e expects
  333. /// that the tag is internal not something that is returned to the user.
  334. void TryPluck(grpc::internal::CompletionQueueTag* tag,
  335. gpr_timespec deadline) {
  336. auto ev = grpc::g_core_codegen_interface->grpc_completion_queue_pluck(
  337. cq_, tag, deadline, nullptr);
  338. if (ev.type == GRPC_QUEUE_TIMEOUT || ev.type == GRPC_QUEUE_SHUTDOWN) {
  339. return;
  340. }
  341. bool ok = ev.success != 0;
  342. void* ignored = tag;
  343. GPR_CODEGEN_ASSERT(!tag->FinalizeResult(&ignored, &ok));
  344. }
  345. /// Manage state of avalanching operations : completion queue tags that
  346. /// trigger other completion queue operations. The underlying core completion
  347. /// queue should not really shutdown until all avalanching operations have
  348. /// been finalized. Note that we maintain the requirement that an avalanche
  349. /// registration must take place before CQ shutdown (which must be maintained
  350. /// elsehwere)
  351. void InitialAvalanching() {
  352. gpr_atm_rel_store(&avalanches_in_flight_, static_cast<gpr_atm>(1));
  353. }
  354. void RegisterAvalanching() {
  355. gpr_atm_no_barrier_fetch_add(&avalanches_in_flight_,
  356. static_cast<gpr_atm>(1));
  357. }
  358. void CompleteAvalanching() {
  359. if (gpr_atm_no_barrier_fetch_add(&avalanches_in_flight_,
  360. static_cast<gpr_atm>(-1)) == 1) {
  361. grpc::g_core_codegen_interface->grpc_completion_queue_shutdown(cq_);
  362. }
  363. }
  364. void RegisterServer(const grpc::Server* server) {
  365. (void)server;
  366. #ifndef NDEBUG
  367. grpc::internal::MutexLock l(&server_list_mutex_);
  368. server_list_.push_back(server);
  369. #endif
  370. }
  371. void UnregisterServer(const grpc::Server* server) {
  372. (void)server;
  373. #ifndef NDEBUG
  374. grpc::internal::MutexLock l(&server_list_mutex_);
  375. server_list_.remove(server);
  376. #endif
  377. }
  378. bool ServerListEmpty() const {
  379. #ifndef NDEBUG
  380. grpc::internal::MutexLock l(&server_list_mutex_);
  381. return server_list_.empty();
  382. #endif
  383. return true;
  384. }
  385. static CompletionQueue* CallbackAlternativeCQ();
  386. static void ReleaseCallbackAlternativeCQ(CompletionQueue* cq);
  387. grpc_completion_queue* cq_; // owned
  388. gpr_atm avalanches_in_flight_;
  389. // List of servers associated with this CQ. Even though this is only used with
  390. // NDEBUG, instantiate it in all cases since otherwise the size will be
  391. // inconsistent.
  392. mutable grpc::internal::Mutex server_list_mutex_;
  393. std::list<const grpc::Server*>
  394. server_list_ /* GUARDED_BY(server_list_mutex_) */;
  395. };
  396. /// A specific type of completion queue used by the processing of notifications
  397. /// by servers. Instantiated by \a ServerBuilder or Server (for health checker).
  398. class ServerCompletionQueue : public CompletionQueue {
  399. public:
  400. bool IsFrequentlyPolled() { return polling_type_ != GRPC_CQ_NON_LISTENING; }
  401. protected:
  402. /// Default constructor
  403. ServerCompletionQueue() : polling_type_(GRPC_CQ_DEFAULT_POLLING) {}
  404. private:
  405. /// \param completion_type indicates whether this is a NEXT or CALLBACK
  406. /// completion queue.
  407. /// \param polling_type Informs the GRPC library about the type of polling
  408. /// allowed on this completion queue. See grpc_cq_polling_type's description
  409. /// in grpc_types.h for more details.
  410. /// \param shutdown_cb is the shutdown callback used for CALLBACK api queues
  411. ServerCompletionQueue(grpc_cq_completion_type completion_type,
  412. grpc_cq_polling_type polling_type,
  413. grpc_completion_queue_functor* shutdown_cb)
  414. : CompletionQueue(grpc_completion_queue_attributes{
  415. GRPC_CQ_CURRENT_VERSION, completion_type, polling_type,
  416. shutdown_cb}),
  417. polling_type_(polling_type) {}
  418. grpc_cq_polling_type polling_type_;
  419. friend class grpc::ServerBuilder;
  420. friend class grpc::Server;
  421. };
  422. } // namespace grpc
  423. #endif // GRPCPP_IMPL_CODEGEN_COMPLETION_QUEUE_H