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