completion_queue.h 18 KB

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