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 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_COMPLETION_QUEUE_H 33 #define GRPCPP_COMPLETION_QUEUE_H 34 35 #include <grpc/grpc.h> 36 #include <grpc/support/atm.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 46 #include <list> 47 48 #include "absl/log/absl_check.h" 49 50 struct grpc_completion_queue; 51 52 namespace grpc { 53 template <class R> 54 class ClientReader; 55 template <class W> 56 class ClientWriter; 57 template <class W, class R> 58 class ClientReaderWriter; 59 template <class R> 60 class ServerReader; 61 template <class W> 62 class ServerWriter; 63 namespace internal { 64 template <class W, class R> 65 class ServerReaderWriterBody; 66 67 template <class ResponseType> 68 void UnaryRunHandlerHelper( 69 const grpc::internal::MethodHandler::HandlerParameter&, ResponseType*, 70 grpc::Status&); 71 template <class ServiceType, class RequestType, class ResponseType, 72 class BaseRequestType, class BaseResponseType> 73 class RpcMethodHandler; 74 template <class ServiceType, class RequestType, class ResponseType> 75 class ClientStreamingHandler; 76 template <class ServiceType, class RequestType, class ResponseType> 77 class ServerStreamingHandler; 78 template <class Streamer, bool WriteNeeded> 79 class TemplatedBidiStreamingHandler; 80 template <grpc::StatusCode code> 81 class ErrorMethodHandler; 82 } // namespace internal 83 84 class Channel; 85 class ChannelInterface; 86 class Server; 87 class ServerBuilder; 88 class ServerContextBase; 89 class ServerInterface; 90 91 namespace internal { 92 class CompletionQueueTag; 93 class RpcMethod; 94 template <class InputMessage, class OutputMessage> 95 class BlockingUnaryCallImpl; 96 template <class Op1, class Op2, class Op3, class Op4, class Op5, class Op6> 97 class CallOpSet; 98 } // namespace internal 99 100 /// A thin wrapper around \ref grpc_completion_queue (see \ref 101 /// src/core/lib/surface/completion_queue.h). 102 /// See \ref doc/cpp/perf_notes.md for notes on best practices for high 103 /// performance servers. 104 class CompletionQueue : private grpc::internal::GrpcLibrary { 105 public: 106 /// Default constructor. Implicitly creates a \a grpc_completion_queue 107 /// instance. CompletionQueue()108 CompletionQueue() 109 : CompletionQueue(grpc_completion_queue_attributes{ 110 GRPC_CQ_CURRENT_VERSION, GRPC_CQ_NEXT, GRPC_CQ_DEFAULT_POLLING, 111 nullptr}) {} 112 113 /// Wrap \a take, taking ownership of the instance. 114 /// 115 /// \param take The completion queue instance to wrap. Ownership is taken. 116 explicit CompletionQueue(grpc_completion_queue* take); 117 118 /// Destructor. Destroys the owned wrapped completion queue / instance. ~CompletionQueue()119 ~CompletionQueue() override { grpc_completion_queue_destroy(cq_); } 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 // Check return type == GOT_EVENT... cases: 179 // SHUTDOWN - queue has been shutdown, return false. 180 // TIMEOUT - we passed infinity time => queue has been shutdown, return 181 // false. 182 // GOT_EVENT - we actually got an event, return true. 183 return (AsyncNextInternal(tag, ok, gpr_inf_future(GPR_CLOCK_REALTIME)) == 184 GOT_EVENT); 185 } 186 187 /// Read from the queue, blocking up to \a deadline (or the queue's shutdown). 188 /// Both \a tag and \a ok are updated upon success (if an event is available 189 /// within the \a deadline). A \a tag points to an arbitrary location usually 190 /// employed to uniquely identify an event. 191 /// 192 /// \param[out] tag Upon success, updated to point to the event's tag. 193 /// \param[out] ok Upon success, true if a successful event, false otherwise 194 /// See documentation for CompletionQueue::Next for explanation of ok 195 /// \param[in] deadline How long to block in wait for an event. 196 /// 197 /// \return The type of event read. 198 template <typename T> AsyncNext(void ** tag,bool * ok,const T & deadline)199 NextStatus AsyncNext(void** tag, bool* ok, const T& deadline) { 200 grpc::TimePoint<T> deadline_tp(deadline); 201 return AsyncNextInternal(tag, ok, deadline_tp.raw_time()); 202 } 203 204 /// EXPERIMENTAL 205 /// First executes \a F, then reads from the queue, blocking up to 206 /// \a deadline (or the queue's shutdown). 207 /// Both \a tag and \a ok are updated upon success (if an event is available 208 /// within the \a deadline). A \a tag points to an arbitrary location usually 209 /// employed to uniquely identify an event. 210 /// 211 /// \param[in] f Function to execute before calling AsyncNext on this queue. 212 /// \param[out] tag Upon success, updated to point to the event's tag. 213 /// \param[out] ok Upon success, true if read a regular event, false 214 /// otherwise. 215 /// \param[in] deadline How long to block in wait for an event. 216 /// 217 /// \return The type of event read. 218 template <typename T, typename F> DoThenAsyncNext(F && f,void ** tag,bool * ok,const T & deadline)219 NextStatus DoThenAsyncNext(F&& f, void** tag, bool* ok, const T& deadline) { 220 CompletionQueueTLSCache cache = CompletionQueueTLSCache(this); 221 f(); 222 if (cache.Flush(tag, ok)) { 223 return GOT_EVENT; 224 } else { 225 return AsyncNext(tag, ok, deadline); 226 } 227 } 228 229 /// Request the shutdown of the queue. 230 /// 231 /// \warning This method must be called at some point if this completion queue 232 /// is accessed with Next or AsyncNext. \a Next will not return false 233 /// until this method has been called and all pending tags have been drained. 234 /// (Likewise for \a AsyncNext returning \a NextStatus::SHUTDOWN .) 235 /// Only once either one of these methods does that (that is, once the queue 236 /// has been \em drained) can an instance of this class be destroyed. 237 /// Also note that applications must ensure that no work is enqueued on this 238 /// completion queue after this method is called. 239 void Shutdown(); 240 241 /// Returns a \em raw pointer to the underlying \a grpc_completion_queue 242 /// instance. 243 /// 244 /// \warning Remember that the returned instance is owned. No transfer of 245 /// ownership is performed. cq()246 grpc_completion_queue* cq() { return cq_; } 247 248 protected: 249 /// Private constructor of CompletionQueue only visible to friend classes CompletionQueue(const grpc_completion_queue_attributes & attributes)250 explicit CompletionQueue(const grpc_completion_queue_attributes& attributes) { 251 cq_ = grpc_completion_queue_create( 252 grpc_completion_queue_factory_lookup(&attributes), &attributes, 253 nullptr); 254 InitialAvalanching(); // reserve this for the future shutdown 255 } 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 263 // Friend synchronous wrappers so that they can access Pluck(), which is 264 // a semi-private API geared towards the synchronous implementation. 265 template <class R> 266 friend class grpc::ClientReader; 267 template <class W> 268 friend class grpc::ClientWriter; 269 template <class W, class R> 270 friend class grpc::ClientReaderWriter; 271 template <class R> 272 friend class grpc::ServerReader; 273 template <class W> 274 friend class grpc::ServerWriter; 275 template <class W, class R> 276 friend class grpc::internal::ServerReaderWriterBody; 277 template <class ResponseType> 278 friend void grpc::internal::UnaryRunHandlerHelper( 279 const grpc::internal::MethodHandler::HandlerParameter&, ResponseType*, 280 grpc::Status&); 281 template <class ServiceType, class RequestType, class ResponseType> 282 friend class grpc::internal::ClientStreamingHandler; 283 template <class ServiceType, class RequestType, class ResponseType> 284 friend class grpc::internal::ServerStreamingHandler; 285 template <class Streamer, bool WriteNeeded> 286 friend class grpc::internal::TemplatedBidiStreamingHandler; 287 template <grpc::StatusCode code> 288 friend class grpc::internal::ErrorMethodHandler; 289 friend class grpc::ServerContextBase; 290 friend class grpc::ServerInterface; 291 template <class InputMessage, class OutputMessage> 292 friend class grpc::internal::BlockingUnaryCallImpl; 293 294 // Friends that need access to constructor for callback CQ 295 friend class grpc::Channel; 296 297 // For access to Register/CompleteAvalanching 298 template <class Op1, class Op2, class Op3, class Op4, class Op5, class Op6> 299 friend class grpc::internal::CallOpSet; 300 301 /// EXPERIMENTAL 302 /// Creates a Thread Local cache to store the first event 303 /// On this completion queue queued from this thread. Once 304 /// initialized, it must be flushed on the same thread. 305 class CompletionQueueTLSCache { 306 public: 307 explicit CompletionQueueTLSCache(CompletionQueue* cq); 308 ~CompletionQueueTLSCache(); 309 bool Flush(void** tag, bool* ok); 310 311 private: 312 CompletionQueue* cq_; 313 bool flushed_; 314 }; 315 316 NextStatus AsyncNextInternal(void** tag, bool* ok, gpr_timespec deadline); 317 318 /// Wraps \a grpc_completion_queue_pluck. 319 /// \warning Must not be mixed with calls to \a Next. Pluck(grpc::internal::CompletionQueueTag * tag)320 bool Pluck(grpc::internal::CompletionQueueTag* tag) { 321 auto deadline = gpr_inf_future(GPR_CLOCK_REALTIME); 322 while (true) { 323 auto ev = grpc_completion_queue_pluck(cq_, tag, deadline, nullptr); 324 bool ok = ev.success != 0; 325 void* ignored = tag; 326 if (tag->FinalizeResult(&ignored, &ok)) { 327 ABSL_CHECK(ignored == tag); 328 return ok; 329 } 330 } 331 } 332 333 /// Performs a single polling pluck on \a tag. 334 /// \warning Must not be mixed with calls to \a Next. 335 /// 336 /// TODO: sreek - This calls tag->FinalizeResult() even if the cq_ is already 337 /// shutdown. This is most likely a bug and if it is a bug, then change this 338 /// implementation to simple call the other TryPluck function with a zero 339 /// timeout. i.e: 340 /// TryPluck(tag, gpr_time_0(GPR_CLOCK_REALTIME)) TryPluck(grpc::internal::CompletionQueueTag * tag)341 void TryPluck(grpc::internal::CompletionQueueTag* tag) { 342 auto deadline = gpr_time_0(GPR_CLOCK_REALTIME); 343 auto ev = grpc_completion_queue_pluck(cq_, tag, deadline, nullptr); 344 if (ev.type == GRPC_QUEUE_TIMEOUT) return; 345 bool ok = ev.success != 0; 346 void* ignored = tag; 347 // the tag must be swallowed if using TryPluck 348 ABSL_CHECK(!tag->FinalizeResult(&ignored, &ok)); 349 } 350 351 /// Performs a single polling pluck on \a tag. Calls tag->FinalizeResult if 352 /// the pluck() was successful and returned the tag. 353 /// 354 /// This exects tag->FinalizeResult (if called) to return 'false' i.e expects 355 /// that the tag is internal not something that is returned to the user. TryPluck(grpc::internal::CompletionQueueTag * tag,gpr_timespec deadline)356 void TryPluck(grpc::internal::CompletionQueueTag* tag, 357 gpr_timespec deadline) { 358 auto ev = grpc_completion_queue_pluck(cq_, tag, deadline, nullptr); 359 if (ev.type == GRPC_QUEUE_TIMEOUT || ev.type == GRPC_QUEUE_SHUTDOWN) { 360 return; 361 } 362 363 bool ok = ev.success != 0; 364 void* ignored = tag; 365 ABSL_CHECK(!tag->FinalizeResult(&ignored, &ok)); 366 } 367 368 /// Manage state of avalanching operations : completion queue tags that 369 /// trigger other completion queue operations. The underlying core completion 370 /// queue should not really shutdown until all avalanching operations have 371 /// been finalized. Note that we maintain the requirement that an avalanche 372 /// registration must take place before CQ shutdown (which must be maintained 373 /// elsewhere) InitialAvalanching()374 void InitialAvalanching() { 375 gpr_atm_rel_store(&avalanches_in_flight_, gpr_atm{1}); 376 } RegisterAvalanching()377 void RegisterAvalanching() { 378 gpr_atm_no_barrier_fetch_add(&avalanches_in_flight_, gpr_atm{1}); 379 } CompleteAvalanching()380 void CompleteAvalanching() { 381 if (gpr_atm_no_barrier_fetch_add(&avalanches_in_flight_, gpr_atm{-1}) == 382 1) { 383 grpc_completion_queue_shutdown(cq_); 384 } 385 } 386 RegisterServer(const grpc::Server * server)387 void RegisterServer(const grpc::Server* server) { 388 (void)server; 389 #ifndef NDEBUG 390 grpc::internal::MutexLock l(&server_list_mutex_); 391 server_list_.push_back(server); 392 #endif 393 } UnregisterServer(const grpc::Server * server)394 void UnregisterServer(const grpc::Server* server) { 395 (void)server; 396 #ifndef NDEBUG 397 grpc::internal::MutexLock l(&server_list_mutex_); 398 server_list_.remove(server); 399 #endif 400 } ServerListEmpty()401 bool ServerListEmpty() const { 402 #ifndef NDEBUG 403 grpc::internal::MutexLock l(&server_list_mutex_); 404 return server_list_.empty(); 405 #endif 406 return true; 407 } 408 409 static CompletionQueue* CallbackAlternativeCQ(); 410 static void ReleaseCallbackAlternativeCQ(CompletionQueue* cq); 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_completion_queue_functor * shutdown_cb)441 ServerCompletionQueue(grpc_cq_completion_type completion_type, 442 grpc_cq_polling_type polling_type, 443 grpc_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_COMPLETION_QUEUE_H 457