server_cc.cc 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  1. /*
  2. * Copyright 2015 gRPC authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. */
  17. #include <grpcpp/server.h>
  18. #include <cstdlib>
  19. #include <sstream>
  20. #include <utility>
  21. #include <grpc/grpc.h>
  22. #include <grpc/support/alloc.h>
  23. #include <grpc/support/log.h>
  24. #include <grpcpp/completion_queue.h>
  25. #include <grpcpp/generic/async_generic_service.h>
  26. #include <grpcpp/impl/codegen/async_unary_call.h>
  27. #include <grpcpp/impl/codegen/call.h>
  28. #include <grpcpp/impl/codegen/completion_queue_tag.h>
  29. #include <grpcpp/impl/codegen/server_interceptor.h>
  30. #include <grpcpp/impl/grpc_library.h>
  31. #include <grpcpp/impl/method_handler_impl.h>
  32. #include <grpcpp/impl/rpc_service_method.h>
  33. #include <grpcpp/impl/server_initializer.h>
  34. #include <grpcpp/impl/service_type.h>
  35. #include <grpcpp/security/server_credentials.h>
  36. #include <grpcpp/server_context.h>
  37. #include <grpcpp/support/time.h>
  38. #include "src/core/ext/transport/inproc/inproc_transport.h"
  39. #include "src/core/lib/iomgr/exec_ctx.h"
  40. #include "src/core/lib/profiling/timers.h"
  41. #include "src/core/lib/surface/call.h"
  42. #include "src/core/lib/surface/completion_queue.h"
  43. #include "src/cpp/client/create_channel_internal.h"
  44. #include "src/cpp/server/health/default_health_check_service.h"
  45. #include "src/cpp/thread_manager/thread_manager.h"
  46. namespace grpc {
  47. namespace {
  48. // The default value for maximum number of threads that can be created in the
  49. // sync server. This value of INT_MAX is chosen to match the default behavior if
  50. // no ResourceQuota is set. To modify the max number of threads in a sync
  51. // server, pass a custom ResourceQuota object (with the desired number of
  52. // max-threads set) to the server builder.
  53. #define DEFAULT_MAX_SYNC_SERVER_THREADS INT_MAX
  54. // How many callback requests of each method should we pre-register at start
  55. #define DEFAULT_CALLBACK_REQS_PER_METHOD 512
  56. // What is the (soft) limit for outstanding requests in the server
  57. #define SOFT_MAXIMUM_CALLBACK_REQS_OUTSTANDING 30000
  58. // If the number of unmatched requests for a method drops below this amount, try
  59. // to allocate extra unless it pushes the total number of callbacks above the
  60. // soft maximum
  61. #define SOFT_MINIMUM_SPARE_CALLBACK_REQS_PER_METHOD 128
  62. class DefaultGlobalCallbacks final : public Server::GlobalCallbacks {
  63. public:
  64. ~DefaultGlobalCallbacks() override {}
  65. void PreSynchronousRequest(ServerContext* context) override {}
  66. void PostSynchronousRequest(ServerContext* context) override {}
  67. };
  68. std::shared_ptr<Server::GlobalCallbacks> g_callbacks = nullptr;
  69. gpr_once g_once_init_callbacks = GPR_ONCE_INIT;
  70. void InitGlobalCallbacks() {
  71. if (!g_callbacks) {
  72. g_callbacks.reset(new DefaultGlobalCallbacks());
  73. }
  74. }
  75. class ShutdownTag : public internal::CompletionQueueTag {
  76. public:
  77. bool FinalizeResult(void** tag, bool* status) { return false; }
  78. };
  79. class DummyTag : public internal::CompletionQueueTag {
  80. public:
  81. bool FinalizeResult(void** tag, bool* status) { return true; }
  82. };
  83. class UnimplementedAsyncRequestContext {
  84. protected:
  85. UnimplementedAsyncRequestContext() : generic_stream_(&server_context_) {}
  86. GenericServerContext server_context_;
  87. GenericServerAsyncReaderWriter generic_stream_;
  88. };
  89. } // namespace
  90. /// Use private inheritance rather than composition only to establish order
  91. /// of construction, since the public base class should be constructed after the
  92. /// elements belonging to the private base class are constructed. This is not
  93. /// possible using true composition.
  94. class Server::UnimplementedAsyncRequest final
  95. : private UnimplementedAsyncRequestContext,
  96. public GenericAsyncRequest {
  97. public:
  98. UnimplementedAsyncRequest(Server* server, ServerCompletionQueue* cq)
  99. : GenericAsyncRequest(server, &server_context_, &generic_stream_, cq, cq,
  100. nullptr, false),
  101. server_(server),
  102. cq_(cq) {}
  103. bool FinalizeResult(void** tag, bool* status) override;
  104. ServerContext* context() { return &server_context_; }
  105. GenericServerAsyncReaderWriter* stream() { return &generic_stream_; }
  106. private:
  107. Server* const server_;
  108. ServerCompletionQueue* const cq_;
  109. };
  110. /// UnimplementedAsyncResponse should not post user-visible completions to the
  111. /// C++ completion queue, but is generated as a CQ event by the core
  112. class Server::UnimplementedAsyncResponse final
  113. : public internal::CallOpSet<internal::CallOpSendInitialMetadata,
  114. internal::CallOpServerSendStatus> {
  115. public:
  116. UnimplementedAsyncResponse(UnimplementedAsyncRequest* request);
  117. ~UnimplementedAsyncResponse() { delete request_; }
  118. bool FinalizeResult(void** tag, bool* status) override {
  119. if (internal::CallOpSet<
  120. internal::CallOpSendInitialMetadata,
  121. internal::CallOpServerSendStatus>::FinalizeResult(tag, status)) {
  122. delete this;
  123. } else {
  124. // The tag was swallowed due to interception. We will see it again.
  125. }
  126. return false;
  127. }
  128. private:
  129. UnimplementedAsyncRequest* const request_;
  130. };
  131. class Server::SyncRequest final : public internal::CompletionQueueTag {
  132. public:
  133. SyncRequest(internal::RpcServiceMethod* method, void* method_tag)
  134. : method_(method),
  135. method_tag_(method_tag),
  136. in_flight_(false),
  137. has_request_payload_(
  138. method->method_type() == internal::RpcMethod::NORMAL_RPC ||
  139. method->method_type() == internal::RpcMethod::SERVER_STREAMING),
  140. call_details_(nullptr),
  141. cq_(nullptr) {
  142. grpc_metadata_array_init(&request_metadata_);
  143. }
  144. ~SyncRequest() {
  145. if (call_details_) {
  146. delete call_details_;
  147. }
  148. grpc_metadata_array_destroy(&request_metadata_);
  149. }
  150. void SetupRequest() { cq_ = grpc_completion_queue_create_for_pluck(nullptr); }
  151. void TeardownRequest() {
  152. grpc_completion_queue_destroy(cq_);
  153. cq_ = nullptr;
  154. }
  155. void Request(grpc_server* server, grpc_completion_queue* notify_cq) {
  156. GPR_ASSERT(cq_ && !in_flight_);
  157. in_flight_ = true;
  158. if (method_tag_) {
  159. if (grpc_server_request_registered_call(
  160. server, method_tag_, &call_, &deadline_, &request_metadata_,
  161. has_request_payload_ ? &request_payload_ : nullptr, cq_,
  162. notify_cq, this) != GRPC_CALL_OK) {
  163. TeardownRequest();
  164. return;
  165. }
  166. } else {
  167. if (!call_details_) {
  168. call_details_ = new grpc_call_details;
  169. grpc_call_details_init(call_details_);
  170. }
  171. if (grpc_server_request_call(server, &call_, call_details_,
  172. &request_metadata_, cq_, notify_cq,
  173. this) != GRPC_CALL_OK) {
  174. TeardownRequest();
  175. return;
  176. }
  177. }
  178. }
  179. void PostShutdownCleanup() {
  180. if (call_) {
  181. grpc_call_unref(call_);
  182. call_ = nullptr;
  183. }
  184. if (cq_) {
  185. grpc_completion_queue_destroy(cq_);
  186. cq_ = nullptr;
  187. }
  188. }
  189. bool FinalizeResult(void** tag, bool* status) override {
  190. if (!*status) {
  191. grpc_completion_queue_destroy(cq_);
  192. cq_ = nullptr;
  193. }
  194. if (call_details_) {
  195. deadline_ = call_details_->deadline;
  196. grpc_call_details_destroy(call_details_);
  197. grpc_call_details_init(call_details_);
  198. }
  199. return true;
  200. }
  201. // The CallData class represents a call that is "active" as opposed
  202. // to just being requested. It wraps and takes ownership of the cq from
  203. // the call request
  204. class CallData final {
  205. public:
  206. explicit CallData(Server* server, SyncRequest* mrd)
  207. : cq_(mrd->cq_),
  208. ctx_(mrd->deadline_, &mrd->request_metadata_),
  209. has_request_payload_(mrd->has_request_payload_),
  210. request_payload_(has_request_payload_ ? mrd->request_payload_
  211. : nullptr),
  212. request_(nullptr),
  213. method_(mrd->method_),
  214. call_(
  215. mrd->call_, server, &cq_, server->max_receive_message_size(),
  216. ctx_.set_server_rpc_info(method_->name(), method_->method_type(),
  217. server->interceptor_creators_)),
  218. server_(server),
  219. global_callbacks_(nullptr),
  220. resources_(false) {
  221. ctx_.set_call(mrd->call_);
  222. ctx_.cq_ = &cq_;
  223. GPR_ASSERT(mrd->in_flight_);
  224. mrd->in_flight_ = false;
  225. mrd->request_metadata_.count = 0;
  226. }
  227. ~CallData() {
  228. if (has_request_payload_ && request_payload_) {
  229. grpc_byte_buffer_destroy(request_payload_);
  230. }
  231. }
  232. void Run(const std::shared_ptr<GlobalCallbacks>& global_callbacks,
  233. bool resources) {
  234. global_callbacks_ = global_callbacks;
  235. resources_ = resources;
  236. interceptor_methods_.SetCall(&call_);
  237. interceptor_methods_.SetReverse();
  238. // Set interception point for RECV INITIAL METADATA
  239. interceptor_methods_.AddInterceptionHookPoint(
  240. experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA);
  241. interceptor_methods_.SetRecvInitialMetadata(&ctx_.client_metadata_);
  242. if (has_request_payload_) {
  243. // Set interception point for RECV MESSAGE
  244. auto* handler = resources_ ? method_->handler()
  245. : server_->resource_exhausted_handler_.get();
  246. request_ = handler->Deserialize(call_.call(), request_payload_,
  247. &request_status_);
  248. request_payload_ = nullptr;
  249. interceptor_methods_.AddInterceptionHookPoint(
  250. experimental::InterceptionHookPoints::POST_RECV_MESSAGE);
  251. interceptor_methods_.SetRecvMessage(request_, nullptr);
  252. }
  253. if (interceptor_methods_.RunInterceptors(
  254. [this]() { ContinueRunAfterInterception(); })) {
  255. ContinueRunAfterInterception();
  256. } else {
  257. // There were interceptors to be run, so ContinueRunAfterInterception
  258. // will be run when interceptors are done.
  259. }
  260. }
  261. void ContinueRunAfterInterception() {
  262. {
  263. ctx_.BeginCompletionOp(&call_, nullptr, nullptr);
  264. global_callbacks_->PreSynchronousRequest(&ctx_);
  265. auto* handler = resources_ ? method_->handler()
  266. : server_->resource_exhausted_handler_.get();
  267. handler->RunHandler(internal::MethodHandler::HandlerParameter(
  268. &call_, &ctx_, request_, request_status_, nullptr));
  269. request_ = nullptr;
  270. global_callbacks_->PostSynchronousRequest(&ctx_);
  271. cq_.Shutdown();
  272. internal::CompletionQueueTag* op_tag = ctx_.GetCompletionOpTag();
  273. cq_.TryPluck(op_tag, gpr_inf_future(GPR_CLOCK_REALTIME));
  274. /* Ensure the cq_ is shutdown */
  275. DummyTag ignored_tag;
  276. GPR_ASSERT(cq_.Pluck(&ignored_tag) == false);
  277. }
  278. delete this;
  279. }
  280. private:
  281. CompletionQueue cq_;
  282. ServerContext ctx_;
  283. const bool has_request_payload_;
  284. grpc_byte_buffer* request_payload_;
  285. void* request_;
  286. Status request_status_;
  287. internal::RpcServiceMethod* const method_;
  288. internal::Call call_;
  289. Server* server_;
  290. std::shared_ptr<GlobalCallbacks> global_callbacks_;
  291. bool resources_;
  292. internal::InterceptorBatchMethodsImpl interceptor_methods_;
  293. };
  294. private:
  295. internal::RpcServiceMethod* const method_;
  296. void* const method_tag_;
  297. bool in_flight_;
  298. const bool has_request_payload_;
  299. grpc_call* call_;
  300. grpc_call_details* call_details_;
  301. gpr_timespec deadline_;
  302. grpc_metadata_array request_metadata_;
  303. grpc_byte_buffer* request_payload_;
  304. grpc_completion_queue* cq_;
  305. };
  306. class Server::CallbackRequest final : public internal::CompletionQueueTag {
  307. public:
  308. CallbackRequest(Server* server, size_t method_idx,
  309. internal::RpcServiceMethod* method, void* method_tag)
  310. : server_(server),
  311. method_index_(method_idx),
  312. method_(method),
  313. method_tag_(method_tag),
  314. has_request_payload_(
  315. method->method_type() == internal::RpcMethod::NORMAL_RPC ||
  316. method->method_type() == internal::RpcMethod::SERVER_STREAMING),
  317. cq_(server->CallbackCQ()),
  318. tag_(this) {
  319. server_->callback_reqs_outstanding_++;
  320. Setup();
  321. }
  322. ~CallbackRequest() {
  323. Clear();
  324. // The counter of outstanding requests must be decremented
  325. // under a lock in case it causes the server shutdown.
  326. std::lock_guard<std::mutex> l(server_->callback_reqs_mu_);
  327. if (--server_->callback_reqs_outstanding_ == 0) {
  328. server_->callback_reqs_done_cv_.notify_one();
  329. }
  330. }
  331. bool Request() {
  332. if (method_tag_) {
  333. if (GRPC_CALL_OK !=
  334. grpc_server_request_registered_call(
  335. server_->c_server(), method_tag_, &call_, &deadline_,
  336. &request_metadata_,
  337. has_request_payload_ ? &request_payload_ : nullptr, cq_->cq(),
  338. cq_->cq(), static_cast<void*>(&tag_))) {
  339. return false;
  340. }
  341. } else {
  342. if (!call_details_) {
  343. call_details_ = new grpc_call_details;
  344. grpc_call_details_init(call_details_);
  345. }
  346. if (grpc_server_request_call(server_->c_server(), &call_, call_details_,
  347. &request_metadata_, cq_->cq(), cq_->cq(),
  348. static_cast<void*>(&tag_)) != GRPC_CALL_OK) {
  349. return false;
  350. }
  351. }
  352. return true;
  353. }
  354. bool FinalizeResult(void** tag, bool* status) override { return false; }
  355. private:
  356. class CallbackCallTag : public grpc_experimental_completion_queue_functor {
  357. public:
  358. CallbackCallTag(Server::CallbackRequest* req) : req_(req) {
  359. functor_run = &CallbackCallTag::StaticRun;
  360. }
  361. // force_run can not be performed on a tag if operations using this tag
  362. // have been sent to PerformOpsOnCall. It is intended for error conditions
  363. // that are detected before the operations are internally processed.
  364. void force_run(bool ok) { Run(ok); }
  365. private:
  366. Server::CallbackRequest* req_;
  367. internal::Call* call_;
  368. static void StaticRun(grpc_experimental_completion_queue_functor* cb,
  369. int ok) {
  370. static_cast<CallbackCallTag*>(cb)->Run(static_cast<bool>(ok));
  371. }
  372. void Run(bool ok) {
  373. void* ignored = req_;
  374. bool new_ok = ok;
  375. GPR_ASSERT(!req_->FinalizeResult(&ignored, &new_ok));
  376. GPR_ASSERT(ignored == req_);
  377. int count =
  378. static_cast<int>(gpr_atm_no_barrier_fetch_add(
  379. &req_->server_
  380. ->callback_unmatched_reqs_count_[req_->method_index_],
  381. -1)) -
  382. 1;
  383. if (!ok) {
  384. // The call has been shutdown.
  385. // Delete its contents to free up the request.
  386. delete req_;
  387. return;
  388. }
  389. // If this was the last request in the list or it is below the soft
  390. // minimum and there are spare requests available, set up a new one.
  391. if (count == 0 || (count < SOFT_MINIMUM_SPARE_CALLBACK_REQS_PER_METHOD &&
  392. req_->server_->callback_reqs_outstanding_ <
  393. SOFT_MAXIMUM_CALLBACK_REQS_OUTSTANDING)) {
  394. auto* new_req = new CallbackRequest(req_->server_, req_->method_index_,
  395. req_->method_, req_->method_tag_);
  396. if (!new_req->Request()) {
  397. // The server must have just decided to shutdown.
  398. gpr_atm_no_barrier_fetch_add(
  399. &new_req->server_
  400. ->callback_unmatched_reqs_count_[new_req->method_index_],
  401. -1);
  402. delete new_req;
  403. }
  404. }
  405. // Bind the call, deadline, and metadata from what we got
  406. req_->ctx_.set_call(req_->call_);
  407. req_->ctx_.cq_ = req_->cq_;
  408. req_->ctx_.BindDeadlineAndMetadata(req_->deadline_,
  409. &req_->request_metadata_);
  410. req_->request_metadata_.count = 0;
  411. // Create a C++ Call to control the underlying core call
  412. call_ = new (grpc_call_arena_alloc(req_->call_, sizeof(internal::Call)))
  413. internal::Call(
  414. req_->call_, req_->server_, req_->cq_,
  415. req_->server_->max_receive_message_size(),
  416. req_->ctx_.set_server_rpc_info(
  417. req_->method_->name(), req_->method_->method_type(),
  418. req_->server_->interceptor_creators_));
  419. req_->interceptor_methods_.SetCall(call_);
  420. req_->interceptor_methods_.SetReverse();
  421. // Set interception point for RECV INITIAL METADATA
  422. req_->interceptor_methods_.AddInterceptionHookPoint(
  423. experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA);
  424. req_->interceptor_methods_.SetRecvInitialMetadata(
  425. &req_->ctx_.client_metadata_);
  426. if (req_->has_request_payload_) {
  427. // Set interception point for RECV MESSAGE
  428. req_->request_ = req_->method_->handler()->Deserialize(
  429. req_->call_, req_->request_payload_, &req_->request_status_);
  430. req_->request_payload_ = nullptr;
  431. req_->interceptor_methods_.AddInterceptionHookPoint(
  432. experimental::InterceptionHookPoints::POST_RECV_MESSAGE);
  433. req_->interceptor_methods_.SetRecvMessage(req_->request_, nullptr);
  434. }
  435. if (req_->interceptor_methods_.RunInterceptors(
  436. [this] { ContinueRunAfterInterception(); })) {
  437. ContinueRunAfterInterception();
  438. } else {
  439. // There were interceptors to be run, so ContinueRunAfterInterception
  440. // will be run when interceptors are done.
  441. }
  442. }
  443. void ContinueRunAfterInterception() {
  444. req_->method_->handler()->RunHandler(
  445. internal::MethodHandler::HandlerParameter(
  446. call_, &req_->ctx_, req_->request_, req_->request_status_,
  447. [this] {
  448. // Recycle this request if there aren't too many outstanding.
  449. // Note that we don't have to worry about a case where there
  450. // are no requests waiting to match for this method since that
  451. // is already taken care of when binding a request to a call.
  452. // TODO(vjpai): Also don't recycle this request if the dynamic
  453. // load no longer justifies it. Consider measuring
  454. // dynamic load and setting a target accordingly.
  455. if (req_->server_->callback_reqs_outstanding_ <
  456. SOFT_MAXIMUM_CALLBACK_REQS_OUTSTANDING) {
  457. req_->Clear();
  458. req_->Setup();
  459. } else {
  460. // We can free up this request because there are too many
  461. delete req_;
  462. return;
  463. }
  464. if (!req_->Request()) {
  465. // The server must have just decided to shutdown.
  466. delete req_;
  467. }
  468. }));
  469. }
  470. };
  471. void Clear() {
  472. if (call_details_) {
  473. delete call_details_;
  474. call_details_ = nullptr;
  475. }
  476. grpc_metadata_array_destroy(&request_metadata_);
  477. if (has_request_payload_ && request_payload_) {
  478. grpc_byte_buffer_destroy(request_payload_);
  479. }
  480. ctx_.Clear();
  481. interceptor_methods_.ClearState();
  482. }
  483. void Setup() {
  484. gpr_atm_no_barrier_fetch_add(
  485. &server_->callback_unmatched_reqs_count_[method_index_], 1);
  486. grpc_metadata_array_init(&request_metadata_);
  487. ctx_.Setup(gpr_inf_future(GPR_CLOCK_REALTIME));
  488. request_payload_ = nullptr;
  489. request_ = nullptr;
  490. request_status_ = Status();
  491. }
  492. Server* const server_;
  493. size_t method_index_;
  494. internal::RpcServiceMethod* const method_;
  495. void* const method_tag_;
  496. const bool has_request_payload_;
  497. grpc_byte_buffer* request_payload_;
  498. void* request_;
  499. Status request_status_;
  500. grpc_call_details* call_details_ = nullptr;
  501. grpc_call* call_;
  502. gpr_timespec deadline_;
  503. grpc_metadata_array request_metadata_;
  504. CompletionQueue* cq_;
  505. CallbackCallTag tag_;
  506. ServerContext ctx_;
  507. internal::InterceptorBatchMethodsImpl interceptor_methods_;
  508. };
  509. // Implementation of ThreadManager. Each instance of SyncRequestThreadManager
  510. // manages a pool of threads that poll for incoming Sync RPCs and call the
  511. // appropriate RPC handlers
  512. class Server::SyncRequestThreadManager : public ThreadManager {
  513. public:
  514. SyncRequestThreadManager(Server* server, CompletionQueue* server_cq,
  515. std::shared_ptr<GlobalCallbacks> global_callbacks,
  516. grpc_resource_quota* rq, int min_pollers,
  517. int max_pollers, int cq_timeout_msec)
  518. : ThreadManager("SyncServer", rq, min_pollers, max_pollers),
  519. server_(server),
  520. server_cq_(server_cq),
  521. cq_timeout_msec_(cq_timeout_msec),
  522. global_callbacks_(std::move(global_callbacks)) {}
  523. WorkStatus PollForWork(void** tag, bool* ok) override {
  524. *tag = nullptr;
  525. // TODO(ctiller): workaround for GPR_TIMESPAN based deadlines not working
  526. // right now
  527. gpr_timespec deadline =
  528. gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
  529. gpr_time_from_millis(cq_timeout_msec_, GPR_TIMESPAN));
  530. switch (server_cq_->AsyncNext(tag, ok, deadline)) {
  531. case CompletionQueue::TIMEOUT:
  532. return TIMEOUT;
  533. case CompletionQueue::SHUTDOWN:
  534. return SHUTDOWN;
  535. case CompletionQueue::GOT_EVENT:
  536. return WORK_FOUND;
  537. }
  538. GPR_UNREACHABLE_CODE(return TIMEOUT);
  539. }
  540. void DoWork(void* tag, bool ok, bool resources) override {
  541. SyncRequest* sync_req = static_cast<SyncRequest*>(tag);
  542. if (!sync_req) {
  543. // No tag. Nothing to work on. This is an unlikley scenario and possibly a
  544. // bug in RPC Manager implementation.
  545. gpr_log(GPR_ERROR, "Sync server. DoWork() was called with NULL tag");
  546. return;
  547. }
  548. if (ok) {
  549. // Calldata takes ownership of the completion queue and interceptors
  550. // inside sync_req
  551. auto* cd = new SyncRequest::CallData(server_, sync_req);
  552. // Prepare for the next request
  553. if (!IsShutdown()) {
  554. sync_req->SetupRequest(); // Create new completion queue for sync_req
  555. sync_req->Request(server_->c_server(), server_cq_->cq());
  556. }
  557. GPR_TIMER_SCOPE("cd.Run()", 0);
  558. cd->Run(global_callbacks_, resources);
  559. }
  560. // TODO (sreek) If ok is false here (which it isn't in case of
  561. // grpc_request_registered_call), we should still re-queue the request
  562. // object
  563. }
  564. void AddSyncMethod(internal::RpcServiceMethod* method, void* tag) {
  565. sync_requests_.emplace_back(new SyncRequest(method, tag));
  566. }
  567. void AddUnknownSyncMethod() {
  568. if (!sync_requests_.empty()) {
  569. unknown_method_.reset(new internal::RpcServiceMethod(
  570. "unknown", internal::RpcMethod::BIDI_STREAMING,
  571. new internal::UnknownMethodHandler));
  572. sync_requests_.emplace_back(
  573. new SyncRequest(unknown_method_.get(), nullptr));
  574. }
  575. }
  576. void Shutdown() override {
  577. ThreadManager::Shutdown();
  578. server_cq_->Shutdown();
  579. }
  580. void Wait() override {
  581. ThreadManager::Wait();
  582. // Drain any pending items from the queue
  583. void* tag;
  584. bool ok;
  585. while (server_cq_->Next(&tag, &ok)) {
  586. if (ok) {
  587. // If a request was pulled off the queue, it means that the thread
  588. // handling the request added it to the completion queue after shutdown
  589. // was called - because the thread had already started and checked the
  590. // shutdown flag before shutdown was called. In this case, we simply
  591. // clean it up here, *after* calling wait on all the worker threads, at
  592. // which point we are certain no in-flight requests will add more to the
  593. // queue. This fixes an intermittent memory leak on shutdown.
  594. SyncRequest* sync_req = static_cast<SyncRequest*>(tag);
  595. sync_req->PostShutdownCleanup();
  596. }
  597. }
  598. }
  599. void Start() {
  600. if (!sync_requests_.empty()) {
  601. for (auto m = sync_requests_.begin(); m != sync_requests_.end(); m++) {
  602. (*m)->SetupRequest();
  603. (*m)->Request(server_->c_server(), server_cq_->cq());
  604. }
  605. Initialize(); // ThreadManager's Initialize()
  606. }
  607. }
  608. private:
  609. Server* server_;
  610. CompletionQueue* server_cq_;
  611. int cq_timeout_msec_;
  612. std::vector<std::unique_ptr<SyncRequest>> sync_requests_;
  613. std::unique_ptr<internal::RpcServiceMethod> unknown_method_;
  614. std::shared_ptr<Server::GlobalCallbacks> global_callbacks_;
  615. };
  616. static internal::GrpcLibraryInitializer g_gli_initializer;
  617. Server::Server(
  618. int max_receive_message_size, ChannelArguments* args,
  619. std::shared_ptr<std::vector<std::unique_ptr<ServerCompletionQueue>>>
  620. sync_server_cqs,
  621. int min_pollers, int max_pollers, int sync_cq_timeout_msec,
  622. grpc_resource_quota* server_rq,
  623. std::vector<
  624. std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
  625. interceptor_creators)
  626. : interceptor_creators_(std::move(interceptor_creators)),
  627. max_receive_message_size_(max_receive_message_size),
  628. sync_server_cqs_(std::move(sync_server_cqs)),
  629. started_(false),
  630. shutdown_(false),
  631. shutdown_notified_(false),
  632. has_generic_service_(false),
  633. server_(nullptr),
  634. server_initializer_(new ServerInitializer(this)),
  635. health_check_service_disabled_(false) {
  636. g_gli_initializer.summon();
  637. gpr_once_init(&g_once_init_callbacks, InitGlobalCallbacks);
  638. global_callbacks_ = g_callbacks;
  639. global_callbacks_->UpdateArguments(args);
  640. if (sync_server_cqs_ != nullptr) {
  641. bool default_rq_created = false;
  642. if (server_rq == nullptr) {
  643. server_rq = grpc_resource_quota_create("SyncServer-default-rq");
  644. grpc_resource_quota_set_max_threads(server_rq,
  645. DEFAULT_MAX_SYNC_SERVER_THREADS);
  646. default_rq_created = true;
  647. }
  648. for (const auto& it : *sync_server_cqs_) {
  649. sync_req_mgrs_.emplace_back(new SyncRequestThreadManager(
  650. this, it.get(), global_callbacks_, server_rq, min_pollers,
  651. max_pollers, sync_cq_timeout_msec));
  652. }
  653. if (default_rq_created) {
  654. grpc_resource_quota_unref(server_rq);
  655. }
  656. }
  657. grpc_channel_args channel_args;
  658. args->SetChannelArgs(&channel_args);
  659. for (size_t i = 0; i < channel_args.num_args; i++) {
  660. if (0 ==
  661. strcmp(channel_args.args[i].key, kHealthCheckServiceInterfaceArg)) {
  662. if (channel_args.args[i].value.pointer.p == nullptr) {
  663. health_check_service_disabled_ = true;
  664. } else {
  665. health_check_service_.reset(static_cast<HealthCheckServiceInterface*>(
  666. channel_args.args[i].value.pointer.p));
  667. }
  668. break;
  669. }
  670. }
  671. server_ = grpc_server_create(&channel_args, nullptr);
  672. }
  673. Server::~Server() {
  674. {
  675. std::unique_lock<std::mutex> lock(mu_);
  676. if (callback_cq_ != nullptr) {
  677. callback_cq_->Shutdown();
  678. }
  679. if (started_ && !shutdown_) {
  680. lock.unlock();
  681. Shutdown();
  682. } else if (!started_) {
  683. // Shutdown the completion queues
  684. for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) {
  685. (*it)->Shutdown();
  686. }
  687. }
  688. }
  689. grpc_server_destroy(server_);
  690. for (auto& per_method_count : callback_unmatched_reqs_count_) {
  691. // There should be no more unmatched callbacks for any method
  692. // as each request is failed by Shutdown. Check that this actually
  693. // happened
  694. GPR_ASSERT(static_cast<int>(gpr_atm_no_barrier_load(&per_method_count)) ==
  695. 0);
  696. }
  697. }
  698. void Server::SetGlobalCallbacks(GlobalCallbacks* callbacks) {
  699. GPR_ASSERT(!g_callbacks);
  700. GPR_ASSERT(callbacks);
  701. g_callbacks.reset(callbacks);
  702. }
  703. grpc_server* Server::c_server() { return server_; }
  704. std::shared_ptr<Channel> Server::InProcessChannel(
  705. const ChannelArguments& args) {
  706. grpc_channel_args channel_args = args.c_channel_args();
  707. return CreateChannelInternal(
  708. "inproc", grpc_inproc_channel_create(server_, &channel_args, nullptr),
  709. std::vector<
  710. std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>());
  711. }
  712. std::shared_ptr<Channel>
  713. Server::experimental_type::InProcessChannelWithInterceptors(
  714. const ChannelArguments& args,
  715. std::vector<
  716. std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
  717. interceptor_creators) {
  718. grpc_channel_args channel_args = args.c_channel_args();
  719. return CreateChannelInternal(
  720. "inproc",
  721. grpc_inproc_channel_create(server_->server_, &channel_args, nullptr),
  722. std::move(interceptor_creators));
  723. }
  724. static grpc_server_register_method_payload_handling PayloadHandlingForMethod(
  725. internal::RpcServiceMethod* method) {
  726. switch (method->method_type()) {
  727. case internal::RpcMethod::NORMAL_RPC:
  728. case internal::RpcMethod::SERVER_STREAMING:
  729. return GRPC_SRM_PAYLOAD_READ_INITIAL_BYTE_BUFFER;
  730. case internal::RpcMethod::CLIENT_STREAMING:
  731. case internal::RpcMethod::BIDI_STREAMING:
  732. return GRPC_SRM_PAYLOAD_NONE;
  733. }
  734. GPR_UNREACHABLE_CODE(return GRPC_SRM_PAYLOAD_NONE;);
  735. }
  736. bool Server::RegisterService(const grpc::string* host, Service* service) {
  737. bool has_async_methods = service->has_async_methods();
  738. if (has_async_methods) {
  739. GPR_ASSERT(service->server_ == nullptr &&
  740. "Can only register an asynchronous service against one server.");
  741. service->server_ = this;
  742. }
  743. const char* method_name = nullptr;
  744. for (auto it = service->methods_.begin(); it != service->methods_.end();
  745. ++it) {
  746. if (it->get() == nullptr) { // Handled by generic service if any.
  747. continue;
  748. }
  749. internal::RpcServiceMethod* method = it->get();
  750. void* method_registration_tag = grpc_server_register_method(
  751. server_, method->name(), host ? host->c_str() : nullptr,
  752. PayloadHandlingForMethod(method), 0);
  753. if (method_registration_tag == nullptr) {
  754. gpr_log(GPR_DEBUG, "Attempt to register %s multiple times",
  755. method->name());
  756. return false;
  757. }
  758. if (method->handler() == nullptr) { // Async method without handler
  759. method->set_server_tag(method_registration_tag);
  760. } else if (method->api_type() ==
  761. internal::RpcServiceMethod::ApiType::SYNC) {
  762. for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) {
  763. (*it)->AddSyncMethod(method, method_registration_tag);
  764. }
  765. } else {
  766. // a callback method. Register at least some callback requests
  767. callback_unmatched_reqs_count_.push_back(0);
  768. auto method_index = callback_unmatched_reqs_count_.size() - 1;
  769. // TODO(vjpai): Register these dynamically based on need
  770. for (int i = 0; i < DEFAULT_CALLBACK_REQS_PER_METHOD; i++) {
  771. callback_reqs_to_start_.push_back(new CallbackRequest(
  772. this, method_index, method, method_registration_tag));
  773. }
  774. // Enqueue it so that it will be Request'ed later after all request
  775. // matchers are created at core server startup
  776. }
  777. method_name = method->name();
  778. }
  779. // Parse service name.
  780. if (method_name != nullptr) {
  781. std::stringstream ss(method_name);
  782. grpc::string service_name;
  783. if (std::getline(ss, service_name, '/') &&
  784. std::getline(ss, service_name, '/')) {
  785. services_.push_back(service_name);
  786. }
  787. }
  788. return true;
  789. }
  790. void Server::RegisterAsyncGenericService(AsyncGenericService* service) {
  791. GPR_ASSERT(service->server_ == nullptr &&
  792. "Can only register an async generic service against one server.");
  793. service->server_ = this;
  794. has_generic_service_ = true;
  795. }
  796. int Server::AddListeningPort(const grpc::string& addr,
  797. ServerCredentials* creds) {
  798. GPR_ASSERT(!started_);
  799. int port = creds->AddPortToServer(addr, server_);
  800. global_callbacks_->AddPort(this, addr, creds, port);
  801. return port;
  802. }
  803. void Server::Start(ServerCompletionQueue** cqs, size_t num_cqs) {
  804. GPR_ASSERT(!started_);
  805. global_callbacks_->PreServerStart(this);
  806. started_ = true;
  807. // Only create default health check service when user did not provide an
  808. // explicit one.
  809. ServerCompletionQueue* health_check_cq = nullptr;
  810. DefaultHealthCheckService::HealthCheckServiceImpl*
  811. default_health_check_service_impl = nullptr;
  812. if (health_check_service_ == nullptr && !health_check_service_disabled_ &&
  813. DefaultHealthCheckServiceEnabled()) {
  814. auto* default_hc_service = new DefaultHealthCheckService;
  815. health_check_service_.reset(default_hc_service);
  816. // We create a non-polling CQ to avoid impacting application
  817. // performance. This ensures that we don't introduce thread hops
  818. // for application requests that wind up on this CQ, which is polled
  819. // in its own thread.
  820. health_check_cq =
  821. new ServerCompletionQueue(GRPC_CQ_NEXT, GRPC_CQ_NON_POLLING, nullptr);
  822. grpc_server_register_completion_queue(server_, health_check_cq->cq(),
  823. nullptr);
  824. default_health_check_service_impl =
  825. default_hc_service->GetHealthCheckService(
  826. std::unique_ptr<ServerCompletionQueue>(health_check_cq));
  827. RegisterService(nullptr, default_health_check_service_impl);
  828. }
  829. grpc_server_start(server_);
  830. if (!has_generic_service_) {
  831. for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) {
  832. (*it)->AddUnknownSyncMethod();
  833. }
  834. for (size_t i = 0; i < num_cqs; i++) {
  835. if (cqs[i]->IsFrequentlyPolled()) {
  836. new UnimplementedAsyncRequest(this, cqs[i]);
  837. }
  838. }
  839. if (health_check_cq != nullptr) {
  840. new UnimplementedAsyncRequest(this, health_check_cq);
  841. }
  842. }
  843. // If this server has any support for synchronous methods (has any sync
  844. // server CQs), make sure that we have a ResourceExhausted handler
  845. // to deal with the case of thread exhaustion
  846. if (sync_server_cqs_ != nullptr && !sync_server_cqs_->empty()) {
  847. resource_exhausted_handler_.reset(new internal::ResourceExhaustedHandler);
  848. }
  849. for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) {
  850. (*it)->Start();
  851. }
  852. for (auto* cbreq : callback_reqs_to_start_) {
  853. GPR_ASSERT(cbreq->Request());
  854. }
  855. callback_reqs_to_start_.clear();
  856. if (default_health_check_service_impl != nullptr) {
  857. default_health_check_service_impl->StartServingThread();
  858. }
  859. }
  860. void Server::ShutdownInternal(gpr_timespec deadline) {
  861. std::unique_lock<std::mutex> lock(mu_);
  862. if (shutdown_) {
  863. return;
  864. }
  865. shutdown_ = true;
  866. /// The completion queue to use for server shutdown completion notification
  867. CompletionQueue shutdown_cq;
  868. ShutdownTag shutdown_tag; // Dummy shutdown tag
  869. grpc_server_shutdown_and_notify(server_, shutdown_cq.cq(), &shutdown_tag);
  870. shutdown_cq.Shutdown();
  871. void* tag;
  872. bool ok;
  873. CompletionQueue::NextStatus status =
  874. shutdown_cq.AsyncNext(&tag, &ok, deadline);
  875. // If this timed out, it means we are done with the grace period for a clean
  876. // shutdown. We should force a shutdown now by cancelling all inflight calls
  877. if (status == CompletionQueue::NextStatus::TIMEOUT) {
  878. grpc_server_cancel_all_calls(server_);
  879. }
  880. // Else in case of SHUTDOWN or GOT_EVENT, it means that the server has
  881. // successfully shutdown
  882. // Shutdown all ThreadManagers. This will try to gracefully stop all the
  883. // threads in the ThreadManagers (once they process any inflight requests)
  884. for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) {
  885. (*it)->Shutdown(); // ThreadManager's Shutdown()
  886. }
  887. // Wait for threads in all ThreadManagers to terminate
  888. for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) {
  889. (*it)->Wait();
  890. }
  891. // Wait for all outstanding callback requests to complete
  892. // (whether waiting for a match or already active).
  893. // We know that no new requests will be created after this point
  894. // because they are only created at server startup time or when
  895. // we have a successful match on a request. During the shutdown phase,
  896. // requests that have not yet matched will be failed rather than
  897. // allowed to succeed, which will cause the server to delete the
  898. // request and decrement the count. Possibly a request will match before
  899. // the shutdown but then find that shutdown has already started by the
  900. // time it tries to register a new request. In that case, the registration
  901. // will report a failure, indicating a shutdown and again we won't end
  902. // up incrementing the counter.
  903. {
  904. std::unique_lock<std::mutex> cblock(callback_reqs_mu_);
  905. callback_reqs_done_cv_.wait(
  906. cblock, [this] { return callback_reqs_outstanding_ == 0; });
  907. }
  908. // Drain the shutdown queue (if the previous call to AsyncNext() timed out
  909. // and we didn't remove the tag from the queue yet)
  910. while (shutdown_cq.Next(&tag, &ok)) {
  911. // Nothing to be done here. Just ignore ok and tag values
  912. }
  913. shutdown_notified_ = true;
  914. shutdown_cv_.notify_all();
  915. }
  916. void Server::Wait() {
  917. std::unique_lock<std::mutex> lock(mu_);
  918. while (started_ && !shutdown_notified_) {
  919. shutdown_cv_.wait(lock);
  920. }
  921. }
  922. void Server::PerformOpsOnCall(internal::CallOpSetInterface* ops,
  923. internal::Call* call) {
  924. ops->FillOps(call);
  925. }
  926. ServerInterface::BaseAsyncRequest::BaseAsyncRequest(
  927. ServerInterface* server, ServerContext* context,
  928. internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
  929. ServerCompletionQueue* notification_cq, void* tag, bool delete_on_finalize)
  930. : server_(server),
  931. context_(context),
  932. stream_(stream),
  933. call_cq_(call_cq),
  934. notification_cq_(notification_cq),
  935. tag_(tag),
  936. delete_on_finalize_(delete_on_finalize),
  937. call_(nullptr),
  938. done_intercepting_(false) {
  939. /* Set up interception state partially for the receive ops. call_wrapper_ is
  940. * not filled at this point, but it will be filled before the interceptors are
  941. * run. */
  942. interceptor_methods_.SetCall(&call_wrapper_);
  943. interceptor_methods_.SetReverse();
  944. call_cq_->RegisterAvalanching(); // This op will trigger more ops
  945. }
  946. ServerInterface::BaseAsyncRequest::~BaseAsyncRequest() {
  947. call_cq_->CompleteAvalanching();
  948. }
  949. bool ServerInterface::BaseAsyncRequest::FinalizeResult(void** tag,
  950. bool* status) {
  951. if (done_intercepting_) {
  952. *tag = tag_;
  953. if (delete_on_finalize_) {
  954. delete this;
  955. }
  956. return true;
  957. }
  958. context_->set_call(call_);
  959. context_->cq_ = call_cq_;
  960. if (call_wrapper_.call() == nullptr) {
  961. // Fill it since it is empty.
  962. call_wrapper_ = internal::Call(
  963. call_, server_, call_cq_, server_->max_receive_message_size(), nullptr);
  964. }
  965. // just the pointers inside call are copied here
  966. stream_->BindCall(&call_wrapper_);
  967. if (*status && call_ && call_wrapper_.server_rpc_info()) {
  968. done_intercepting_ = true;
  969. // Set interception point for RECV INITIAL METADATA
  970. interceptor_methods_.AddInterceptionHookPoint(
  971. experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA);
  972. interceptor_methods_.SetRecvInitialMetadata(&context_->client_metadata_);
  973. if (interceptor_methods_.RunInterceptors(
  974. [this]() { ContinueFinalizeResultAfterInterception(); })) {
  975. // There are no interceptors to run. Continue
  976. } else {
  977. // There were interceptors to be run, so
  978. // ContinueFinalizeResultAfterInterception will be run when interceptors
  979. // are done.
  980. return false;
  981. }
  982. }
  983. if (*status && call_) {
  984. context_->BeginCompletionOp(&call_wrapper_, nullptr, nullptr);
  985. }
  986. *tag = tag_;
  987. if (delete_on_finalize_) {
  988. delete this;
  989. }
  990. return true;
  991. }
  992. void ServerInterface::BaseAsyncRequest::
  993. ContinueFinalizeResultAfterInterception() {
  994. context_->BeginCompletionOp(&call_wrapper_, nullptr, nullptr);
  995. // Queue a tag which will be returned immediately
  996. grpc_core::ExecCtx exec_ctx;
  997. grpc_cq_begin_op(notification_cq_->cq(), this);
  998. grpc_cq_end_op(
  999. notification_cq_->cq(), this, GRPC_ERROR_NONE,
  1000. [](void* arg, grpc_cq_completion* completion) { delete completion; },
  1001. nullptr, new grpc_cq_completion());
  1002. }
  1003. ServerInterface::RegisteredAsyncRequest::RegisteredAsyncRequest(
  1004. ServerInterface* server, ServerContext* context,
  1005. internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
  1006. ServerCompletionQueue* notification_cq, void* tag, const char* name,
  1007. internal::RpcMethod::RpcType type)
  1008. : BaseAsyncRequest(server, context, stream, call_cq, notification_cq, tag,
  1009. true),
  1010. name_(name),
  1011. type_(type) {}
  1012. void ServerInterface::RegisteredAsyncRequest::IssueRequest(
  1013. void* registered_method, grpc_byte_buffer** payload,
  1014. ServerCompletionQueue* notification_cq) {
  1015. GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_registered_call(
  1016. server_->server(), registered_method, &call_,
  1017. &context_->deadline_,
  1018. context_->client_metadata_.arr(), payload,
  1019. call_cq_->cq(), notification_cq->cq(), this));
  1020. }
  1021. ServerInterface::GenericAsyncRequest::GenericAsyncRequest(
  1022. ServerInterface* server, GenericServerContext* context,
  1023. internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
  1024. ServerCompletionQueue* notification_cq, void* tag, bool delete_on_finalize)
  1025. : BaseAsyncRequest(server, context, stream, call_cq, notification_cq, tag,
  1026. delete_on_finalize) {
  1027. grpc_call_details_init(&call_details_);
  1028. GPR_ASSERT(notification_cq);
  1029. GPR_ASSERT(call_cq);
  1030. GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_call(
  1031. server->server(), &call_, &call_details_,
  1032. context->client_metadata_.arr(), call_cq->cq(),
  1033. notification_cq->cq(), this));
  1034. }
  1035. bool ServerInterface::GenericAsyncRequest::FinalizeResult(void** tag,
  1036. bool* status) {
  1037. // If we are done intercepting, there is nothing more for us to do
  1038. if (done_intercepting_) {
  1039. return BaseAsyncRequest::FinalizeResult(tag, status);
  1040. }
  1041. // TODO(yangg) remove the copy here.
  1042. if (*status) {
  1043. static_cast<GenericServerContext*>(context_)->method_ =
  1044. StringFromCopiedSlice(call_details_.method);
  1045. static_cast<GenericServerContext*>(context_)->host_ =
  1046. StringFromCopiedSlice(call_details_.host);
  1047. context_->deadline_ = call_details_.deadline;
  1048. }
  1049. grpc_slice_unref(call_details_.method);
  1050. grpc_slice_unref(call_details_.host);
  1051. call_wrapper_ = internal::Call(
  1052. call_, server_, call_cq_, server_->max_receive_message_size(),
  1053. context_->set_server_rpc_info(
  1054. static_cast<GenericServerContext*>(context_)->method_.c_str(),
  1055. internal::RpcMethod::BIDI_STREAMING,
  1056. *server_->interceptor_creators()));
  1057. return BaseAsyncRequest::FinalizeResult(tag, status);
  1058. }
  1059. bool Server::UnimplementedAsyncRequest::FinalizeResult(void** tag,
  1060. bool* status) {
  1061. if (GenericAsyncRequest::FinalizeResult(tag, status)) {
  1062. // We either had no interceptors run or we are done intercepting
  1063. if (*status) {
  1064. new UnimplementedAsyncRequest(server_, cq_);
  1065. new UnimplementedAsyncResponse(this);
  1066. } else {
  1067. delete this;
  1068. }
  1069. } else {
  1070. // The tag was swallowed due to interception. We will see it again.
  1071. }
  1072. return false;
  1073. }
  1074. Server::UnimplementedAsyncResponse::UnimplementedAsyncResponse(
  1075. UnimplementedAsyncRequest* request)
  1076. : request_(request) {
  1077. Status status(StatusCode::UNIMPLEMENTED, "");
  1078. internal::UnknownMethodHandler::FillOps(request_->context(), this);
  1079. request_->stream()->call_.PerformOps(this);
  1080. }
  1081. ServerInitializer* Server::initializer() { return server_initializer_.get(); }
  1082. namespace {
  1083. class ShutdownCallback : public grpc_experimental_completion_queue_functor {
  1084. public:
  1085. ShutdownCallback() { functor_run = &ShutdownCallback::Run; }
  1086. // TakeCQ takes ownership of the cq into the shutdown callback
  1087. // so that the shutdown callback will be responsible for destroying it
  1088. void TakeCQ(CompletionQueue* cq) { cq_ = cq; }
  1089. // The Run function will get invoked by the completion queue library
  1090. // when the shutdown is actually complete
  1091. static void Run(grpc_experimental_completion_queue_functor* cb, int) {
  1092. auto* callback = static_cast<ShutdownCallback*>(cb);
  1093. delete callback->cq_;
  1094. delete callback;
  1095. }
  1096. private:
  1097. CompletionQueue* cq_ = nullptr;
  1098. };
  1099. } // namespace
  1100. CompletionQueue* Server::CallbackCQ() {
  1101. // TODO(vjpai): Consider using a single global CQ for the default CQ
  1102. // if there is no explicit per-server CQ registered
  1103. std::lock_guard<std::mutex> l(mu_);
  1104. if (callback_cq_ == nullptr) {
  1105. auto* shutdown_callback = new ShutdownCallback;
  1106. callback_cq_ = new CompletionQueue(grpc_completion_queue_attributes{
  1107. GRPC_CQ_CURRENT_VERSION, GRPC_CQ_CALLBACK, GRPC_CQ_DEFAULT_POLLING,
  1108. shutdown_callback});
  1109. // Transfer ownership of the new cq to its own shutdown callback
  1110. shutdown_callback->TakeCQ(callback_cq_);
  1111. }
  1112. return callback_cq_;
  1113. }
  1114. } // namespace grpc