server.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. /*
  2. *
  3. * Copyright 2015, Google Inc.
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are
  8. * met:
  9. *
  10. * * Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above
  13. * copyright notice, this list of conditions and the following disclaimer
  14. * in the documentation and/or other materials provided with the
  15. * distribution.
  16. * * Neither the name of Google Inc. nor the names of its
  17. * contributors may be used to endorse or promote products derived from
  18. * this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. *
  32. */
  33. #include <grpc++/server.h>
  34. #include <utility>
  35. #include <grpc/grpc.h>
  36. #include <grpc/grpc_security.h>
  37. #include <grpc/support/alloc.h>
  38. #include <grpc/support/log.h>
  39. #include <grpc++/completion_queue.h>
  40. #include <grpc++/async_generic_service.h>
  41. #include <grpc++/impl/rpc_service_method.h>
  42. #include <grpc++/impl/service_type.h>
  43. #include <grpc++/server_context.h>
  44. #include <grpc++/server_credentials.h>
  45. #include <grpc++/thread_pool_interface.h>
  46. #include <grpc++/time.h>
  47. #include "src/core/profiling/timers.h"
  48. #include "src/cpp/proto/proto_utils.h"
  49. namespace grpc {
  50. class Server::SyncRequest GRPC_FINAL : public CompletionQueueTag {
  51. public:
  52. SyncRequest(RpcServiceMethod* method, void* tag)
  53. : method_(method),
  54. tag_(tag),
  55. in_flight_(false),
  56. has_request_payload_(method->method_type() == RpcMethod::NORMAL_RPC ||
  57. method->method_type() ==
  58. RpcMethod::SERVER_STREAMING),
  59. has_response_payload_(method->method_type() == RpcMethod::NORMAL_RPC ||
  60. method->method_type() ==
  61. RpcMethod::CLIENT_STREAMING) {
  62. grpc_metadata_array_init(&request_metadata_);
  63. }
  64. static SyncRequest* Wait(CompletionQueue* cq, bool* ok) {
  65. void* tag = nullptr;
  66. *ok = false;
  67. if (!cq->Next(&tag, ok)) {
  68. return nullptr;
  69. }
  70. auto* mrd = static_cast<SyncRequest*>(tag);
  71. GPR_ASSERT(mrd->in_flight_);
  72. return mrd;
  73. }
  74. void Request(grpc_server* server) {
  75. GPR_ASSERT(!in_flight_);
  76. in_flight_ = true;
  77. cq_ = grpc_completion_queue_create();
  78. GPR_ASSERT(GRPC_CALL_OK ==
  79. grpc_server_request_registered_call(
  80. server, tag_, &call_, &deadline_, &request_metadata_,
  81. has_request_payload_ ? &request_payload_ : nullptr, cq_,
  82. this));
  83. }
  84. bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE {
  85. if (!*status) {
  86. grpc_completion_queue_destroy(cq_);
  87. }
  88. return true;
  89. }
  90. class CallData GRPC_FINAL {
  91. public:
  92. explicit CallData(Server* server, SyncRequest* mrd)
  93. : cq_(mrd->cq_),
  94. call_(mrd->call_, server, &cq_, server->max_message_size_),
  95. ctx_(mrd->deadline_, mrd->request_metadata_.metadata,
  96. mrd->request_metadata_.count),
  97. has_request_payload_(mrd->has_request_payload_),
  98. has_response_payload_(mrd->has_response_payload_),
  99. request_payload_(mrd->request_payload_),
  100. method_(mrd->method_) {
  101. ctx_.call_ = mrd->call_;
  102. ctx_.cq_ = &cq_;
  103. GPR_ASSERT(mrd->in_flight_);
  104. mrd->in_flight_ = false;
  105. mrd->request_metadata_.count = 0;
  106. }
  107. ~CallData() {
  108. if (has_request_payload_ && request_payload_) {
  109. grpc_byte_buffer_destroy(request_payload_);
  110. }
  111. }
  112. void Run() {
  113. std::unique_ptr<grpc::protobuf::Message> req;
  114. std::unique_ptr<grpc::protobuf::Message> res;
  115. if (has_request_payload_) {
  116. GRPC_TIMER_BEGIN(GRPC_PTAG_PROTO_DESERIALIZE, call_.call());
  117. req.reset(method_->AllocateRequestProto());
  118. if (!DeserializeProto(request_payload_, req.get(), call_.max_message_size())) {
  119. abort(); // for now
  120. }
  121. GRPC_TIMER_END(GRPC_PTAG_PROTO_DESERIALIZE, call_.call());
  122. }
  123. if (has_response_payload_) {
  124. res.reset(method_->AllocateResponseProto());
  125. }
  126. ctx_.BeginCompletionOp(&call_);
  127. auto status = method_->handler()->RunHandler(
  128. MethodHandler::HandlerParameter(&call_, &ctx_, req.get(), res.get()));
  129. CallOpBuffer buf;
  130. if (!ctx_.sent_initial_metadata_) {
  131. buf.AddSendInitialMetadata(&ctx_.initial_metadata_);
  132. }
  133. if (has_response_payload_) {
  134. buf.AddSendMessage(*res);
  135. }
  136. buf.AddServerSendStatus(&ctx_.trailing_metadata_, status);
  137. call_.PerformOps(&buf);
  138. GPR_ASSERT(cq_.Pluck(&buf));
  139. void* ignored_tag;
  140. bool ignored_ok;
  141. cq_.Shutdown();
  142. GPR_ASSERT(cq_.Next(&ignored_tag, &ignored_ok) == false);
  143. }
  144. private:
  145. CompletionQueue cq_;
  146. Call call_;
  147. ServerContext ctx_;
  148. const bool has_request_payload_;
  149. const bool has_response_payload_;
  150. grpc_byte_buffer* request_payload_;
  151. RpcServiceMethod* const method_;
  152. };
  153. private:
  154. RpcServiceMethod* const method_;
  155. void* const tag_;
  156. bool in_flight_;
  157. const bool has_request_payload_;
  158. const bool has_response_payload_;
  159. grpc_call* call_;
  160. gpr_timespec deadline_;
  161. grpc_metadata_array request_metadata_;
  162. grpc_byte_buffer* request_payload_;
  163. grpc_completion_queue* cq_;
  164. };
  165. grpc_server* CreateServer(grpc_completion_queue* cq, int max_message_size) {
  166. if (max_message_size > 0) {
  167. grpc_arg arg;
  168. arg.type = GRPC_ARG_INTEGER;
  169. arg.key = const_cast<char*>(GRPC_ARG_MAX_MESSAGE_LENGTH);
  170. arg.value.integer = max_message_size;
  171. grpc_channel_args args = {1, &arg};
  172. return grpc_server_create(cq, &args);
  173. } else {
  174. return grpc_server_create(cq, nullptr);
  175. }
  176. }
  177. Server::Server(ThreadPoolInterface* thread_pool, bool thread_pool_owned,
  178. int max_message_size)
  179. : max_message_size_(max_message_size),
  180. started_(false),
  181. shutdown_(false),
  182. num_running_cb_(0),
  183. sync_methods_(new std::list<SyncRequest>),
  184. server_(CreateServer(cq_.cq(), max_message_size)),
  185. thread_pool_(thread_pool),
  186. thread_pool_owned_(thread_pool_owned) {}
  187. Server::~Server() {
  188. {
  189. grpc::unique_lock<grpc::mutex> lock(mu_);
  190. if (started_ && !shutdown_) {
  191. lock.unlock();
  192. Shutdown();
  193. }
  194. }
  195. grpc_server_destroy(server_);
  196. if (thread_pool_owned_) {
  197. delete thread_pool_;
  198. }
  199. delete sync_methods_;
  200. }
  201. bool Server::RegisterService(RpcService* service) {
  202. for (int i = 0; i < service->GetMethodCount(); ++i) {
  203. RpcServiceMethod* method = service->GetMethod(i);
  204. void* tag =
  205. grpc_server_register_method(server_, method->name(), nullptr, cq_.cq());
  206. if (!tag) {
  207. gpr_log(GPR_DEBUG, "Attempt to register %s multiple times",
  208. method->name());
  209. return false;
  210. }
  211. SyncRequest request(method, tag);
  212. sync_methods_->emplace_back(request);
  213. }
  214. return true;
  215. }
  216. bool Server::RegisterAsyncService(AsynchronousService* service) {
  217. GPR_ASSERT(service->dispatch_impl_ == nullptr &&
  218. "Can only register an asynchronous service against one server.");
  219. service->dispatch_impl_ = this;
  220. service->request_args_ = new void* [service->method_count_];
  221. for (size_t i = 0; i < service->method_count_; ++i) {
  222. void* tag =
  223. grpc_server_register_method(server_, service->method_names_[i], nullptr,
  224. service->completion_queue()->cq());
  225. if (!tag) {
  226. gpr_log(GPR_DEBUG, "Attempt to register %s multiple times",
  227. service->method_names_[i]);
  228. return false;
  229. }
  230. service->request_args_[i] = tag;
  231. }
  232. return true;
  233. }
  234. void Server::RegisterAsyncGenericService(AsyncGenericService* service) {
  235. GPR_ASSERT(service->server_ == nullptr &&
  236. "Can only register an async generic service against one server.");
  237. service->server_ = this;
  238. }
  239. int Server::AddListeningPort(const grpc::string& addr,
  240. ServerCredentials* creds) {
  241. GPR_ASSERT(!started_);
  242. return creds->AddPortToServer(addr, server_);
  243. }
  244. bool Server::Start() {
  245. GPR_ASSERT(!started_);
  246. started_ = true;
  247. grpc_server_start(server_);
  248. // Start processing rpcs.
  249. if (!sync_methods_->empty()) {
  250. for (auto m = sync_methods_->begin(); m != sync_methods_->end(); m++) {
  251. m->Request(server_);
  252. }
  253. ScheduleCallback();
  254. }
  255. return true;
  256. }
  257. void Server::Shutdown() {
  258. grpc::unique_lock<grpc::mutex> lock(mu_);
  259. if (started_ && !shutdown_) {
  260. shutdown_ = true;
  261. grpc_server_shutdown(server_);
  262. cq_.Shutdown();
  263. // Wait for running callbacks to finish.
  264. while (num_running_cb_ != 0) {
  265. callback_cv_.wait(lock);
  266. }
  267. }
  268. }
  269. void Server::Wait() {
  270. grpc::unique_lock<grpc::mutex> lock(mu_);
  271. while (num_running_cb_ != 0) {
  272. callback_cv_.wait(lock);
  273. }
  274. }
  275. void Server::PerformOpsOnCall(CallOpBuffer* buf, Call* call) {
  276. static const size_t MAX_OPS = 8;
  277. size_t nops = MAX_OPS;
  278. grpc_op ops[MAX_OPS];
  279. buf->FillOps(ops, &nops);
  280. GPR_ASSERT(GRPC_CALL_OK ==
  281. grpc_call_start_batch(call->call(), ops, nops, buf));
  282. }
  283. class Server::AsyncRequest GRPC_FINAL : public CompletionQueueTag {
  284. public:
  285. AsyncRequest(Server* server, void* registered_method, ServerContext* ctx,
  286. grpc::protobuf::Message* request,
  287. ServerAsyncStreamingInterface* stream, CompletionQueue* cq,
  288. void* tag)
  289. : tag_(tag),
  290. request_(request),
  291. stream_(stream),
  292. cq_(cq),
  293. ctx_(ctx),
  294. generic_ctx_(nullptr),
  295. server_(server),
  296. call_(nullptr),
  297. payload_(nullptr) {
  298. memset(&array_, 0, sizeof(array_));
  299. grpc_call_details_init(&call_details_);
  300. grpc_server_request_registered_call(
  301. server->server_, registered_method, &call_, &call_details_.deadline,
  302. &array_, request ? &payload_ : nullptr, cq->cq(), this);
  303. }
  304. AsyncRequest(Server* server, GenericServerContext* ctx,
  305. ServerAsyncStreamingInterface* stream, CompletionQueue* cq,
  306. void* tag)
  307. : tag_(tag),
  308. request_(nullptr),
  309. stream_(stream),
  310. cq_(cq),
  311. ctx_(nullptr),
  312. generic_ctx_(ctx),
  313. server_(server),
  314. call_(nullptr),
  315. payload_(nullptr) {
  316. memset(&array_, 0, sizeof(array_));
  317. grpc_call_details_init(&call_details_);
  318. grpc_server_request_call(server->server_, &call_, &call_details_, &array_,
  319. cq->cq(), this);
  320. }
  321. ~AsyncRequest() {
  322. if (payload_) {
  323. grpc_byte_buffer_destroy(payload_);
  324. }
  325. grpc_metadata_array_destroy(&array_);
  326. }
  327. bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE {
  328. *tag = tag_;
  329. bool orig_status = *status;
  330. if (*status && request_) {
  331. if (payload_) {
  332. GRPC_TIMER_BEGIN(GRPC_PTAG_PROTO_DESERIALIZE, call_);
  333. *status = DeserializeProto(payload_, request_,
  334. server_->max_message_size_);
  335. GRPC_TIMER_END(GRPC_PTAG_PROTO_DESERIALIZE, call_);
  336. } else {
  337. *status = false;
  338. }
  339. }
  340. ServerContext* ctx = ctx_ ? ctx_ : generic_ctx_;
  341. GPR_ASSERT(ctx);
  342. if (*status) {
  343. ctx->deadline_ = call_details_.deadline;
  344. for (size_t i = 0; i < array_.count; i++) {
  345. ctx->client_metadata_.insert(std::make_pair(
  346. grpc::string(array_.metadata[i].key),
  347. grpc::string(
  348. array_.metadata[i].value,
  349. array_.metadata[i].value + array_.metadata[i].value_length)));
  350. }
  351. if (generic_ctx_) {
  352. // TODO(yangg) remove the copy here.
  353. generic_ctx_->method_ = call_details_.method;
  354. generic_ctx_->host_ = call_details_.host;
  355. gpr_free(call_details_.method);
  356. gpr_free(call_details_.host);
  357. }
  358. }
  359. ctx->call_ = call_;
  360. ctx->cq_ = cq_;
  361. Call call(call_, server_, cq_, server_->max_message_size_);
  362. if (orig_status && call_) {
  363. ctx->BeginCompletionOp(&call);
  364. }
  365. // just the pointers inside call are copied here
  366. stream_->BindCall(&call);
  367. delete this;
  368. return true;
  369. }
  370. private:
  371. void* const tag_;
  372. grpc::protobuf::Message* const request_;
  373. ServerAsyncStreamingInterface* const stream_;
  374. CompletionQueue* const cq_;
  375. ServerContext* const ctx_;
  376. GenericServerContext* const generic_ctx_;
  377. Server* const server_;
  378. grpc_call* call_;
  379. grpc_call_details call_details_;
  380. grpc_metadata_array array_;
  381. grpc_byte_buffer* payload_;
  382. };
  383. void Server::RequestAsyncCall(void* registered_method, ServerContext* context,
  384. grpc::protobuf::Message* request,
  385. ServerAsyncStreamingInterface* stream,
  386. CompletionQueue* cq, void* tag) {
  387. new AsyncRequest(this, registered_method, context, request, stream, cq, tag);
  388. }
  389. void Server::RequestAsyncGenericCall(GenericServerContext* context,
  390. ServerAsyncStreamingInterface* stream,
  391. CompletionQueue* cq, void* tag) {
  392. new AsyncRequest(this, context, stream, cq, tag);
  393. }
  394. void Server::ScheduleCallback() {
  395. {
  396. grpc::unique_lock<grpc::mutex> lock(mu_);
  397. num_running_cb_++;
  398. }
  399. thread_pool_->ScheduleCallback(std::bind(&Server::RunRpc, this));
  400. }
  401. void Server::RunRpc() {
  402. // Wait for one more incoming rpc.
  403. bool ok;
  404. auto* mrd = SyncRequest::Wait(&cq_, &ok);
  405. if (mrd) {
  406. ScheduleCallback();
  407. if (ok) {
  408. SyncRequest::CallData cd(this, mrd);
  409. mrd->Request(server_);
  410. cd.Run();
  411. }
  412. }
  413. {
  414. grpc::unique_lock<grpc::mutex> lock(mu_);
  415. num_running_cb_--;
  416. if (shutdown_) {
  417. callback_cv_.notify_all();
  418. }
  419. }
  420. }
  421. } // namespace grpc