You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

completion_queue.h 21 kB

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