blob: 67452294f98455b9e8a525671cb1d66356f495cf [file] [log] [blame]
vjpaidea740f2015-02-26 16:35:35 -08001/*
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
34#include <forward_list>
35#include <functional>
36#include <sys/time.h>
37#include <sys/resource.h>
38#include <sys/signal.h>
39#include <thread>
40
41#include <gflags/gflags.h>
42#include <grpc/support/alloc.h>
43#include <grpc/support/host_port.h>
44#include <grpc++/async_unary_call.h>
45#include <grpc++/config.h>
46#include <grpc++/server.h>
47#include <grpc++/server_builder.h>
48#include <grpc++/server_context.h>
49#include <grpc++/status.h>
50#include <gtest/gtest.h>
51#include "src/cpp/server/thread_pool.h"
52#include "test/core/util/grpc_profiler.h"
53#include "test/cpp/qps/qpstest.pb.h"
54
55#include <grpc/grpc.h>
56#include <grpc/support/log.h>
57
58DEFINE_bool(enable_ssl, false, "Whether to use ssl/tls.");
59DEFINE_int32(port, 0, "Server port.");
60DEFINE_int32(server_threads, 4, "Number of server threads.");
61
62using grpc::CompletionQueue;
63using grpc::Server;
64using grpc::ServerBuilder;
65using grpc::ServerContext;
66using grpc::ThreadPool;
67using grpc::testing::Payload;
68using grpc::testing::PayloadType;
69using grpc::testing::ServerStats;
70using grpc::testing::SimpleRequest;
71using grpc::testing::SimpleResponse;
72using grpc::testing::StatsRequest;
73using grpc::testing::TestService;
74using grpc::Status;
75
76// In some distros, gflags is in the namespace google, and in some others,
77// in gflags. This hack is enabling us to find both.
78namespace google {}
79namespace gflags {}
80using namespace google;
81using namespace gflags;
82
83static bool got_sigint = false;
84
85static void sigint_handler(int x) { got_sigint = 1; }
86
87static double time_double(struct timeval *tv) {
88 return tv->tv_sec + 1e-6 * tv->tv_usec;
89}
90
91static bool SetPayload(PayloadType type, int size, Payload *payload) {
92 PayloadType response_type = type;
93 // TODO(yangg): Support UNCOMPRESSABLE payload.
94 if (type != PayloadType::COMPRESSABLE) {
95 return false;
96 }
97 payload->set_type(response_type);
98 std::unique_ptr<char[]> body(new char[size]());
99 payload->set_body(body.get(), size);
100 return true;
101}
102
103namespace {
104
105class AsyncQpsServerTest {
106 public:
107 AsyncQpsServerTest() : srv_cq_(), async_service_(&srv_cq_), server_(nullptr) {
108 char *server_address = NULL;
109 gpr_join_host_port(&server_address, "::", FLAGS_port);
110
111 ServerBuilder builder;
112 builder.AddPort(server_address);
113
114 builder.RegisterAsyncService(&async_service_);
115
116 server_ = builder.BuildAndStart();
117 gpr_log(GPR_INFO, "Server listening on %s\n", server_address);
118 gpr_free(server_address);
119
120 using namespace std::placeholders;
121 request_unary_ = std::bind(&TestService::AsyncService::RequestUnaryCall,
122 &async_service_, _1, _2, _3, &srv_cq_, _4);
123 request_stats_ =
124 std::bind(&TestService::AsyncService::RequestCollectServerStats,
125 &async_service_, _1, _2, _3, &srv_cq_, _4);
126 for (int i = 0; i < 100; i++) {
Vijay Pai64ac47f2015-02-26 17:59:51 -0800127 contexts_.push_front(
128 new ServerRpcContextUnaryImpl<SimpleRequest, SimpleResponse>(
129 request_unary_, UnaryCall));
130 contexts_.push_front(
131 new ServerRpcContextUnaryImpl<StatsRequest, ServerStats>(
132 request_stats_, CollectServerStats));
vjpaidea740f2015-02-26 16:35:35 -0800133 }
134 }
135 ~AsyncQpsServerTest() {
136 server_->Shutdown();
137 void *ignored_tag;
138 bool ignored_ok;
139 srv_cq_.Shutdown();
140 while (srv_cq_.Next(&ignored_tag, &ignored_ok)) {
141 }
142 while (!contexts_.empty()) {
143 delete contexts_.front();
144 contexts_.pop_front();
145 }
146 }
147 void ServeRpcs(int num_threads) {
148 std::vector<std::thread> threads;
149 for (int i = 0; i < num_threads; i++) {
150 threads.push_back(std::thread([=]() {
151 // Wait until work is available or we are shutting down
152 bool ok;
153 void *got_tag;
154 while (srv_cq_.Next(&got_tag, &ok)) {
155 EXPECT_EQ(ok, true);
Vijay Pai64ac47f2015-02-26 17:59:51 -0800156 ServerRpcContext *ctx = detag(got_tag);
vjpaidea740f2015-02-26 16:35:35 -0800157 // The tag is a pointer to an RPC context to invoke
158 if ((*ctx)() == false) {
Vijay Pai64ac47f2015-02-26 17:59:51 -0800159 // this RPC context is done, so refresh it
160 ctx->refresh();
161 }
vjpaidea740f2015-02-26 16:35:35 -0800162 }
163 return;
164 }));
165 }
166 while (!got_sigint) {
167 std::this_thread::sleep_for(std::chrono::seconds(5));
168 }
169 }
Vijay Pai64ac47f2015-02-26 17:59:51 -0800170
vjpaidea740f2015-02-26 16:35:35 -0800171 private:
172 class ServerRpcContext {
Vijay Pai64ac47f2015-02-26 17:59:51 -0800173 public:
vjpaidea740f2015-02-26 16:35:35 -0800174 ServerRpcContext() {}
Vijay Pai64ac47f2015-02-26 17:59:51 -0800175 virtual ~ServerRpcContext(){};
176 virtual bool operator()() = 0; // do next state, return false if all done
177 virtual void refresh() = 0; // start this back at a clean state
vjpaidea740f2015-02-26 16:35:35 -0800178 };
179 static void *tag(ServerRpcContext *func) {
180 return reinterpret_cast<void *>(func);
181 }
182 static ServerRpcContext *detag(void *tag) {
183 return reinterpret_cast<ServerRpcContext *>(tag);
184 }
185
186 template <class RequestType, class ResponseType>
187 class ServerRpcContextUnaryImpl : public ServerRpcContext {
188 public:
189 ServerRpcContextUnaryImpl(
190 std::function<void(ServerContext *, RequestType *,
191 grpc::ServerAsyncResponseWriter<ResponseType> *,
192 void *)> request_method,
193 std::function<grpc::Status(const RequestType *, ResponseType *)>
194 invoke_method)
195 : next_state_(&ServerRpcContextUnaryImpl::invoker),
196 request_method_(request_method),
197 invoke_method_(invoke_method),
Vijay Pai64ac47f2015-02-26 17:59:51 -0800198 response_writer_(&srv_ctx_) {
vjpaidea740f2015-02-26 16:35:35 -0800199 request_method_(&srv_ctx_, &req_, &response_writer_,
Vijay Pai64ac47f2015-02-26 17:59:51 -0800200 AsyncQpsServerTest::tag(this));
vjpaidea740f2015-02-26 16:35:35 -0800201 }
vjpai3c110662015-02-27 07:17:16 -0800202 ~ServerRpcContextUnaryImpl() GRPC_OVERRIDE {}
203 bool operator()() GRPC_OVERRIDE { return (this->*next_state_)(); }
204 void refresh() GRPC_OVERRIDE {
vjpaidea740f2015-02-26 16:35:35 -0800205 srv_ctx_ = ServerContext();
206 req_ = RequestType();
207 response_writer_ =
Vijay Pai64ac47f2015-02-26 17:59:51 -0800208 grpc::ServerAsyncResponseWriter<ResponseType>(&srv_ctx_);
vjpaidea740f2015-02-26 16:35:35 -0800209
210 // Then request the method
211 next_state_ = &ServerRpcContextUnaryImpl::invoker;
212 request_method_(&srv_ctx_, &req_, &response_writer_,
Vijay Pai64ac47f2015-02-26 17:59:51 -0800213 AsyncQpsServerTest::tag(this));
vjpaidea740f2015-02-26 16:35:35 -0800214 }
Vijay Pai64ac47f2015-02-26 17:59:51 -0800215
vjpaidea740f2015-02-26 16:35:35 -0800216 private:
Vijay Pai64ac47f2015-02-26 17:59:51 -0800217 bool finisher() { return false; }
vjpaidea740f2015-02-26 16:35:35 -0800218 bool invoker() {
219 ResponseType response;
220
221 // Call the RPC processing function
222 grpc::Status status = invoke_method_(&req_, &response);
223
224 // Have the response writer work and invoke on_finish when done
225 next_state_ = &ServerRpcContextUnaryImpl::finisher;
Vijay Pai64ac47f2015-02-26 17:59:51 -0800226 response_writer_.Finish(response, status, AsyncQpsServerTest::tag(this));
vjpaidea740f2015-02-26 16:35:35 -0800227 return true;
228 }
229 ServerContext srv_ctx_;
230 RequestType req_;
231 bool (ServerRpcContextUnaryImpl::*next_state_)();
232 std::function<void(ServerContext *, RequestType *,
233 grpc::ServerAsyncResponseWriter<ResponseType> *, void *)>
234 request_method_;
235 std::function<grpc::Status(const RequestType *, ResponseType *)>
236 invoke_method_;
237 grpc::ServerAsyncResponseWriter<ResponseType> response_writer_;
238 };
239
240 static Status CollectServerStats(const StatsRequest *,
241 ServerStats *response) {
242 struct rusage usage;
243 struct timeval tv;
244 gettimeofday(&tv, NULL);
245 getrusage(RUSAGE_SELF, &usage);
246 response->set_time_now(time_double(&tv));
247 response->set_time_user(time_double(&usage.ru_utime));
248 response->set_time_system(time_double(&usage.ru_stime));
249 return Status::OK;
250 }
251 static Status UnaryCall(const SimpleRequest *request,
252 SimpleResponse *response) {
253 if (request->has_response_size() && request->response_size() > 0) {
254 if (!SetPayload(request->response_type(), request->response_size(),
255 response->mutable_payload())) {
256 return Status(grpc::StatusCode::INTERNAL, "Error creating payload.");
257 }
258 }
259 return Status::OK;
260 }
261 CompletionQueue srv_cq_;
262 TestService::AsyncService async_service_;
263 std::unique_ptr<Server> server_;
264 std::function<void(ServerContext *, SimpleRequest *,
265 grpc::ServerAsyncResponseWriter<SimpleResponse> *, void *)>
266 request_unary_;
267 std::function<void(ServerContext *, StatsRequest *,
268 grpc::ServerAsyncResponseWriter<ServerStats> *, void *)>
269 request_stats_;
270 std::forward_list<ServerRpcContext *> contexts_;
271};
272
273} // namespace
274
275static void RunServer() {
276 AsyncQpsServerTest server;
277
278 grpc_profiler_start("qps_server_async.prof");
279
280 server.ServeRpcs(FLAGS_server_threads);
281
282 grpc_profiler_stop();
283}
284
285int main(int argc, char **argv) {
286 grpc_init();
287 ParseCommandLineFlags(&argc, &argv, true);
288 GPR_ASSERT(FLAGS_port != 0);
289 GPR_ASSERT(!FLAGS_enable_ssl);
290
291 signal(SIGINT, sigint_handler);
292
293 RunServer();
294
295 grpc_shutdown();
296 google::protobuf::ShutdownProtobufLibrary();
297
298 return 0;
299}