server.cc 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. /*
  2. *
  3. * Copyright 2014, 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/log.h>
  38. #include <grpc++/completion_queue.h>
  39. #include <grpc++/impl/rpc_service_method.h>
  40. #include <grpc++/server_context.h>
  41. #include <grpc++/server_credentials.h>
  42. #include <grpc++/thread_pool_interface.h>
  43. #include "src/cpp/proto/proto_utils.h"
  44. namespace grpc {
  45. Server::Server(ThreadPoolInterface *thread_pool, bool thread_pool_owned,
  46. ServerCredentials *creds)
  47. : started_(false),
  48. shutdown_(false),
  49. num_running_cb_(0),
  50. thread_pool_(thread_pool),
  51. thread_pool_owned_(thread_pool_owned),
  52. secure_(creds != nullptr) {
  53. if (creds) {
  54. server_ = grpc_secure_server_create(creds->GetRawCreds(), cq_.cq(), nullptr);
  55. } else {
  56. server_ = grpc_server_create(cq_.cq(), nullptr);
  57. }
  58. }
  59. Server::Server() {
  60. // Should not be called.
  61. GPR_ASSERT(false);
  62. }
  63. Server::~Server() {
  64. std::unique_lock<std::mutex> lock(mu_);
  65. if (started_ && !shutdown_) {
  66. lock.unlock();
  67. Shutdown();
  68. } else {
  69. lock.unlock();
  70. }
  71. grpc_server_destroy(server_);
  72. if (thread_pool_owned_) {
  73. delete thread_pool_;
  74. }
  75. }
  76. bool Server::RegisterService(RpcService *service) {
  77. for (int i = 0; i < service->GetMethodCount(); ++i) {
  78. RpcServiceMethod *method = service->GetMethod(i);
  79. void *tag = grpc_server_register_method(server_, method->name(), nullptr);
  80. if (!tag) {
  81. gpr_log(GPR_DEBUG, "Attempt to register %s multiple times",
  82. method->name());
  83. return false;
  84. }
  85. methods_.emplace_back(method, tag);
  86. }
  87. return true;
  88. }
  89. int Server::AddPort(const grpc::string &addr) {
  90. GPR_ASSERT(!started_);
  91. if (secure_) {
  92. return grpc_server_add_secure_http2_port(server_, addr.c_str());
  93. } else {
  94. return grpc_server_add_http2_port(server_, addr.c_str());
  95. }
  96. }
  97. class Server::MethodRequestData final : public CompletionQueueTag {
  98. public:
  99. MethodRequestData(RpcServiceMethod *method, void *tag)
  100. : method_(method),
  101. tag_(tag),
  102. has_request_payload_(method->method_type() == RpcMethod::NORMAL_RPC ||
  103. method->method_type() ==
  104. RpcMethod::SERVER_STREAMING),
  105. has_response_payload_(method->method_type() == RpcMethod::NORMAL_RPC ||
  106. method->method_type() ==
  107. RpcMethod::CLIENT_STREAMING) {
  108. grpc_metadata_array_init(&request_metadata_);
  109. }
  110. static MethodRequestData *Wait(CompletionQueue *cq, bool *ok) {
  111. void *tag;
  112. if (!cq->Next(&tag, ok)) {
  113. return nullptr;
  114. }
  115. auto *mrd = static_cast<MethodRequestData *>(tag);
  116. GPR_ASSERT(mrd->in_flight_);
  117. return mrd;
  118. }
  119. void Request(grpc_server *server) {
  120. GPR_ASSERT(!in_flight_);
  121. in_flight_ = true;
  122. cq_ = grpc_completion_queue_create();
  123. GPR_ASSERT(GRPC_CALL_OK ==
  124. grpc_server_request_registered_call(
  125. server, tag_, &call_, &deadline_, &request_metadata_,
  126. has_request_payload_ ? &request_payload_ : nullptr,
  127. cq_, this));
  128. }
  129. void FinalizeResult(void **tag, bool *status) override {}
  130. class CallData {
  131. public:
  132. explicit CallData(Server *server, MethodRequestData *mrd)
  133. : cq_(mrd->cq_),
  134. call_(mrd->call_, server, &cq_),
  135. ctx_(mrd->deadline_, mrd->request_metadata_.metadata,
  136. mrd->request_metadata_.count),
  137. has_request_payload_(mrd->has_request_payload_),
  138. has_response_payload_(mrd->has_response_payload_),
  139. request_payload_(mrd->request_payload_),
  140. method_(mrd->method_) {
  141. GPR_ASSERT(mrd->in_flight_);
  142. mrd->in_flight_ = false;
  143. mrd->request_metadata_.count = 0;
  144. }
  145. void Run() {
  146. std::unique_ptr<google::protobuf::Message> req;
  147. std::unique_ptr<google::protobuf::Message> res;
  148. if (has_request_payload_) {
  149. req.reset(method_->AllocateRequestProto());
  150. if (!DeserializeProto(request_payload_, req.get())) {
  151. abort(); // for now
  152. }
  153. }
  154. if (has_response_payload_) {
  155. res.reset(method_->AllocateResponseProto());
  156. }
  157. auto status = method_->handler()->RunHandler(
  158. MethodHandler::HandlerParameter(&call_, &ctx_, req.get(), res.get()));
  159. CallOpBuffer buf;
  160. buf.AddServerSendStatus(nullptr, status);
  161. if (has_response_payload_) {
  162. buf.AddSendMessage(*res);
  163. }
  164. call_.PerformOps(&buf);
  165. GPR_ASSERT(cq_.Pluck(&buf));
  166. }
  167. private:
  168. CompletionQueue cq_;
  169. Call call_;
  170. ServerContext ctx_;
  171. const bool has_request_payload_;
  172. const bool has_response_payload_;
  173. grpc_byte_buffer *request_payload_;
  174. RpcServiceMethod *const method_;
  175. };
  176. private:
  177. RpcServiceMethod *const method_;
  178. void *const tag_;
  179. bool in_flight_ = false;
  180. const bool has_request_payload_;
  181. const bool has_response_payload_;
  182. grpc_call *call_;
  183. gpr_timespec deadline_;
  184. grpc_metadata_array request_metadata_;
  185. grpc_byte_buffer *request_payload_;
  186. grpc_completion_queue *cq_;
  187. };
  188. bool Server::Start() {
  189. GPR_ASSERT(!started_);
  190. started_ = true;
  191. grpc_server_start(server_);
  192. // Start processing rpcs.
  193. if (!methods_.empty()) {
  194. for (auto &m : methods_) {
  195. m.Request(server_);
  196. }
  197. ScheduleCallback();
  198. }
  199. return true;
  200. }
  201. void Server::Shutdown() {
  202. {
  203. std::unique_lock<std::mutex> lock(mu_);
  204. if (started_ && !shutdown_) {
  205. shutdown_ = true;
  206. grpc_server_shutdown(server_);
  207. // Wait for running callbacks to finish.
  208. while (num_running_cb_ != 0) {
  209. callback_cv_.wait(lock);
  210. }
  211. }
  212. }
  213. }
  214. void Server::PerformOpsOnCall(CallOpBuffer *buf, Call *call) {
  215. static const size_t MAX_OPS = 8;
  216. size_t nops = MAX_OPS;
  217. grpc_op ops[MAX_OPS];
  218. buf->FillOps(ops, &nops);
  219. GPR_ASSERT(GRPC_CALL_OK ==
  220. grpc_call_start_batch(call->call(), ops, nops,
  221. buf));
  222. }
  223. void Server::ScheduleCallback() {
  224. {
  225. std::unique_lock<std::mutex> lock(mu_);
  226. num_running_cb_++;
  227. }
  228. thread_pool_->ScheduleCallback(std::bind(&Server::RunRpc, this));
  229. }
  230. void Server::RunRpc() {
  231. // Wait for one more incoming rpc.
  232. bool ok;
  233. auto *mrd = MethodRequestData::Wait(&cq_, &ok);
  234. if (mrd) {
  235. MethodRequestData::CallData cd(this, mrd);
  236. if (ok) {
  237. mrd->Request(server_);
  238. ScheduleCallback();
  239. cd.Run();
  240. }
  241. }
  242. {
  243. std::unique_lock<std::mutex> lock(mu_);
  244. num_running_cb_--;
  245. if (shutdown_) {
  246. callback_cv_.notify_all();
  247. }
  248. }
  249. }
  250. } // namespace grpc