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 #include <cinttypes>
20 #include <deque>
21 #include <list>
22 #include <thread>
23 #include <unordered_map>
24 #include <vector>
25
26 #include <grpc/support/alloc.h>
27 #include <grpc/support/log.h>
28 #include <grpc/support/string_util.h>
29 #include <grpcpp/channel.h>
30 #include <grpcpp/client_context.h>
31 #include <grpcpp/create_channel.h>
32
33 #include "src/core/lib/gpr/env.h"
34 #include "src/core/lib/gpr/host_port.h"
35 #include "src/core/lib/profiling/timers.h"
36 #include "src/proto/grpc/testing/worker_service.grpc.pb.h"
37 #include "test/core/util/port.h"
38 #include "test/core/util/test_config.h"
39 #include "test/cpp/qps/client.h"
40 #include "test/cpp/qps/driver.h"
41 #include "test/cpp/qps/histogram.h"
42 #include "test/cpp/qps/qps_worker.h"
43 #include "test/cpp/qps/stats.h"
44 #include "test/cpp/util/test_credentials_provider.h"
45
46 using std::deque;
47 using std::list;
48 using std::thread;
49 using std::unique_ptr;
50 using std::vector;
51
52 namespace grpc {
53 namespace testing {
get_host(const std::string & worker)54 static std::string get_host(const std::string& worker) {
55 char* host;
56 char* port;
57
58 gpr_split_host_port(worker.c_str(), &host, &port);
59 const string s(host);
60
61 gpr_free(host);
62 gpr_free(port);
63 return s;
64 }
65
get_workers(const string & env_name)66 static deque<string> get_workers(const string& env_name) {
67 deque<string> out;
68 char* env = gpr_getenv(env_name.c_str());
69 if (!env) {
70 env = gpr_strdup("");
71 }
72 char* p = env;
73 if (strlen(env) != 0) {
74 for (;;) {
75 char* comma = strchr(p, ',');
76 if (comma) {
77 out.emplace_back(p, comma);
78 p = comma + 1;
79 } else {
80 out.emplace_back(p);
81 break;
82 }
83 }
84 }
85 if (out.size() == 0) {
86 gpr_log(GPR_ERROR,
87 "Environment variable \"%s\" does not contain a list of QPS "
88 "workers to use. Set it to a comma-separated list of "
89 "hostname:port pairs, starting with hosts that should act as "
90 "servers. E.g. export "
91 "%s=\"serverhost1:1234,clienthost1:1234,clienthost2:1234\"",
92 env_name.c_str(), env_name.c_str());
93 }
94 gpr_free(env);
95 return out;
96 }
97
98 // helpers for postprocess_scenario_result
WallTime(const ClientStats & s)99 static double WallTime(const ClientStats& s) { return s.time_elapsed(); }
SystemTime(const ClientStats & s)100 static double SystemTime(const ClientStats& s) { return s.time_system(); }
UserTime(const ClientStats & s)101 static double UserTime(const ClientStats& s) { return s.time_user(); }
CliPollCount(const ClientStats & s)102 static double CliPollCount(const ClientStats& s) { return s.cq_poll_count(); }
SvrPollCount(const ServerStats & s)103 static double SvrPollCount(const ServerStats& s) { return s.cq_poll_count(); }
ServerWallTime(const ServerStats & s)104 static double ServerWallTime(const ServerStats& s) { return s.time_elapsed(); }
ServerSystemTime(const ServerStats & s)105 static double ServerSystemTime(const ServerStats& s) { return s.time_system(); }
ServerUserTime(const ServerStats & s)106 static double ServerUserTime(const ServerStats& s) { return s.time_user(); }
ServerTotalCpuTime(const ServerStats & s)107 static double ServerTotalCpuTime(const ServerStats& s) {
108 return s.total_cpu_time();
109 }
ServerIdleCpuTime(const ServerStats & s)110 static double ServerIdleCpuTime(const ServerStats& s) {
111 return s.idle_cpu_time();
112 }
Cores(int n)113 static int Cores(int n) { return n; }
114
115 // Postprocess ScenarioResult and populate result summary.
postprocess_scenario_result(ScenarioResult * result)116 static void postprocess_scenario_result(ScenarioResult* result) {
117 Histogram histogram;
118 histogram.MergeProto(result->latencies());
119
120 auto time_estimate = average(result->client_stats(), WallTime);
121 auto qps = histogram.Count() / time_estimate;
122 auto qps_per_server_core = qps / sum(result->server_cores(), Cores);
123
124 result->mutable_summary()->set_qps(qps);
125 result->mutable_summary()->set_qps_per_server_core(qps_per_server_core);
126 result->mutable_summary()->set_latency_50(histogram.Percentile(50));
127 result->mutable_summary()->set_latency_90(histogram.Percentile(90));
128 result->mutable_summary()->set_latency_95(histogram.Percentile(95));
129 result->mutable_summary()->set_latency_99(histogram.Percentile(99));
130 result->mutable_summary()->set_latency_999(histogram.Percentile(99.9));
131
132 auto server_system_time = 100.0 *
133 sum(result->server_stats(), ServerSystemTime) /
134 sum(result->server_stats(), ServerWallTime);
135 auto server_user_time = 100.0 * sum(result->server_stats(), ServerUserTime) /
136 sum(result->server_stats(), ServerWallTime);
137
138 auto client_system_time = 100.0 * sum(result->client_stats(), SystemTime) /
139 sum(result->client_stats(), WallTime);
140 auto client_user_time = 100.0 * sum(result->client_stats(), UserTime) /
141 sum(result->client_stats(), WallTime);
142
143 result->mutable_summary()->set_server_system_time(server_system_time);
144 result->mutable_summary()->set_server_user_time(server_user_time);
145 result->mutable_summary()->set_client_system_time(client_system_time);
146 result->mutable_summary()->set_client_user_time(client_user_time);
147
148 // For Non-linux platform, get_cpu_usage() is not implemented. Thus,
149 // ServerTotalCpuTime and ServerIdleCpuTime are both 0.
150 if (average(result->server_stats(), ServerTotalCpuTime) == 0) {
151 result->mutable_summary()->set_server_cpu_usage(0);
152 } else {
153 auto server_cpu_usage =
154 100 - 100 * average(result->server_stats(), ServerIdleCpuTime) /
155 average(result->server_stats(), ServerTotalCpuTime);
156 result->mutable_summary()->set_server_cpu_usage(server_cpu_usage);
157 }
158
159 if (result->request_results_size() > 0) {
160 int64_t successes = 0;
161 int64_t failures = 0;
162 for (int i = 0; i < result->request_results_size(); i++) {
163 const RequestResultCount& rrc = result->request_results(i);
164 if (rrc.status_code() == 0) {
165 successes += rrc.count();
166 } else {
167 failures += rrc.count();
168 }
169 }
170 result->mutable_summary()->set_successful_requests_per_second(
171 successes / time_estimate);
172 result->mutable_summary()->set_failed_requests_per_second(failures /
173 time_estimate);
174 }
175
176 result->mutable_summary()->set_client_polls_per_request(
177 sum(result->client_stats(), CliPollCount) / histogram.Count());
178 result->mutable_summary()->set_server_polls_per_request(
179 sum(result->server_stats(), SvrPollCount) / histogram.Count());
180
181 auto server_queries_per_cpu_sec =
182 histogram.Count() / (sum(result->server_stats(), ServerSystemTime) +
183 sum(result->server_stats(), ServerUserTime));
184 auto client_queries_per_cpu_sec =
185 histogram.Count() / (sum(result->client_stats(), SystemTime) +
186 sum(result->client_stats(), UserTime));
187
188 result->mutable_summary()->set_server_queries_per_cpu_sec(
189 server_queries_per_cpu_sec);
190 result->mutable_summary()->set_client_queries_per_cpu_sec(
191 client_queries_per_cpu_sec);
192 }
193
194 std::vector<grpc::testing::Server*>* g_inproc_servers = nullptr;
195
RunScenario(const ClientConfig & initial_client_config,size_t num_clients,const ServerConfig & initial_server_config,size_t num_servers,int warmup_seconds,int benchmark_seconds,int spawn_local_worker_count,const grpc::string & qps_server_target_override,const grpc::string & credential_type,bool run_inproc,int32_t median_latency_collection_interval_millis)196 std::unique_ptr<ScenarioResult> RunScenario(
197 const ClientConfig& initial_client_config, size_t num_clients,
198 const ServerConfig& initial_server_config, size_t num_servers,
199 int warmup_seconds, int benchmark_seconds, int spawn_local_worker_count,
200 const grpc::string& qps_server_target_override,
201 const grpc::string& credential_type, bool run_inproc,
202 int32_t median_latency_collection_interval_millis) {
203 if (run_inproc) {
204 g_inproc_servers = new std::vector<grpc::testing::Server*>;
205 }
206 // Log everything from the driver
207 gpr_set_log_verbosity(GPR_LOG_SEVERITY_DEBUG);
208
209 // ClientContext allocations (all are destroyed at scope exit)
210 list<ClientContext> contexts;
211 auto alloc_context = [](list<ClientContext>* contexts) {
212 contexts->emplace_back();
213 auto context = &contexts->back();
214 context->set_wait_for_ready(true);
215 return context;
216 };
217
218 // To be added to the result, containing the final configuration used for
219 // client and config (including host, etc.)
220 ClientConfig result_client_config;
221
222 // Get client, server lists; ignore if inproc test
223 auto workers = (!run_inproc) ? get_workers("QPS_WORKERS") : deque<string>();
224 ClientConfig client_config = initial_client_config;
225
226 // Spawn some local workers if desired
227 vector<unique_ptr<QpsWorker>> local_workers;
228 for (int i = 0; i < abs(spawn_local_worker_count); i++) {
229 // act as if we're a new test -- gets a good rng seed
230 static bool called_init = false;
231 if (!called_init) {
232 char args_buf[100];
233 strcpy(args_buf, "some-benchmark");
234 char* args[] = {args_buf};
235 grpc_test_init(1, args);
236 called_init = true;
237 }
238
239 char addr[256];
240 // we use port # of -1 to indicate inproc
241 int driver_port = (!run_inproc) ? grpc_pick_unused_port_or_die() : -1;
242 local_workers.emplace_back(new QpsWorker(driver_port, 0, credential_type));
243 sprintf(addr, "localhost:%d", driver_port);
244 if (spawn_local_worker_count < 0) {
245 workers.push_front(addr);
246 } else {
247 workers.push_back(addr);
248 }
249 }
250 GPR_ASSERT(workers.size() != 0);
251
252 // if num_clients is set to <=0, do dynamic sizing: all workers
253 // except for servers are clients
254 if (num_clients <= 0) {
255 num_clients = workers.size() - num_servers;
256 }
257
258 // TODO(ctiller): support running multiple configurations, and binpack
259 // client/server pairs
260 // to available workers
261 GPR_ASSERT(workers.size() >= num_clients + num_servers);
262
263 // Trim to just what we need
264 workers.resize(num_clients + num_servers);
265
266 // Start servers
267 struct ServerData {
268 unique_ptr<WorkerService::Stub> stub;
269 unique_ptr<ClientReaderWriter<ServerArgs, ServerStatus>> stream;
270 };
271 std::vector<ServerData> servers(num_servers);
272 std::unordered_map<string, std::deque<int>> hosts_cores;
273 ChannelArguments channel_args;
274
275 for (size_t i = 0; i < num_servers; i++) {
276 gpr_log(GPR_INFO, "Starting server on %s (worker #%" PRIuPTR ")",
277 workers[i].c_str(), i);
278 if (!run_inproc) {
279 servers[i].stub = WorkerService::NewStub(CreateChannel(
280 workers[i], GetCredentialsProvider()->GetChannelCredentials(
281 credential_type, &channel_args)));
282 } else {
283 servers[i].stub = WorkerService::NewStub(
284 local_workers[i]->InProcessChannel(channel_args));
285 }
286
287 const ServerConfig& server_config = initial_server_config;
288 if (server_config.core_limit() != 0) {
289 gpr_log(GPR_ERROR,
290 "server config core limit is set but ignored by driver");
291 }
292
293 ServerArgs args;
294 *args.mutable_setup() = server_config;
295 servers[i].stream = servers[i].stub->RunServer(alloc_context(&contexts));
296 if (!servers[i].stream->Write(args)) {
297 gpr_log(GPR_ERROR, "Could not write args to server %zu", i);
298 }
299 ServerStatus init_status;
300 if (!servers[i].stream->Read(&init_status)) {
301 gpr_log(GPR_ERROR, "Server %zu did not yield initial status", i);
302 }
303 if (qps_server_target_override.length() > 0) {
304 // overriding the qps server target only works if there is 1 server
305 GPR_ASSERT(num_servers == 1);
306 client_config.add_server_targets(qps_server_target_override);
307 } else if (run_inproc) {
308 std::string cli_target(INPROC_NAME_PREFIX);
309 cli_target += std::to_string(i);
310 client_config.add_server_targets(cli_target);
311 } else {
312 std::string host;
313 char* cli_target;
314 host = get_host(workers[i]);
315 gpr_join_host_port(&cli_target, host.c_str(), init_status.port());
316 client_config.add_server_targets(cli_target);
317 gpr_free(cli_target);
318 }
319 }
320
321 client_config.set_median_latency_collection_interval_millis(
322 median_latency_collection_interval_millis);
323
324 // Targets are all set by now
325 result_client_config = client_config;
326 // Start clients
327 struct ClientData {
328 unique_ptr<WorkerService::Stub> stub;
329 unique_ptr<ClientReaderWriter<ClientArgs, ClientStatus>> stream;
330 };
331 std::vector<ClientData> clients(num_clients);
332 size_t channels_allocated = 0;
333 for (size_t i = 0; i < num_clients; i++) {
334 const auto& worker = workers[i + num_servers];
335 gpr_log(GPR_INFO, "Starting client on %s (worker #%" PRIuPTR ")",
336 worker.c_str(), i + num_servers);
337 if (!run_inproc) {
338 clients[i].stub = WorkerService::NewStub(
339 CreateChannel(worker, GetCredentialsProvider()->GetChannelCredentials(
340 credential_type, &channel_args)));
341 } else {
342 clients[i].stub = WorkerService::NewStub(
343 local_workers[i + num_servers]->InProcessChannel(channel_args));
344 }
345 ClientConfig per_client_config = client_config;
346
347 if (initial_client_config.core_limit() != 0) {
348 gpr_log(GPR_ERROR, "client config core limit set but ignored");
349 }
350
351 // Reduce channel count so that total channels specified is held regardless
352 // of the number of clients available
353 size_t num_channels =
354 (client_config.client_channels() - channels_allocated) /
355 (num_clients - i);
356 channels_allocated += num_channels;
357 gpr_log(GPR_DEBUG, "Client %" PRIdPTR " gets %" PRIdPTR " channels", i,
358 num_channels);
359 per_client_config.set_client_channels(num_channels);
360
361 ClientArgs args;
362 *args.mutable_setup() = per_client_config;
363 clients[i].stream = clients[i].stub->RunClient(alloc_context(&contexts));
364 if (!clients[i].stream->Write(args)) {
365 gpr_log(GPR_ERROR, "Could not write args to client %zu", i);
366 }
367 }
368
369 for (size_t i = 0; i < num_clients; i++) {
370 ClientStatus init_status;
371 if (!clients[i].stream->Read(&init_status)) {
372 gpr_log(GPR_ERROR, "Client %zu did not yield initial status", i);
373 }
374 }
375
376 // Send an initial mark: clients can use this to know that everything is ready
377 // to start
378 gpr_log(GPR_INFO, "Initiating");
379 ServerArgs server_mark;
380 server_mark.mutable_mark()->set_reset(true);
381 ClientArgs client_mark;
382 client_mark.mutable_mark()->set_reset(true);
383 ServerStatus server_status;
384 ClientStatus client_status;
385 for (size_t i = 0; i < num_clients; i++) {
386 auto client = &clients[i];
387 if (!client->stream->Write(client_mark)) {
388 gpr_log(GPR_ERROR, "Couldn't write mark to client %zu", i);
389 }
390 }
391 for (size_t i = 0; i < num_clients; i++) {
392 auto client = &clients[i];
393 if (!client->stream->Read(&client_status)) {
394 gpr_log(GPR_ERROR, "Couldn't get status from client %zu", i);
395 }
396 }
397
398 // Let everything warmup
399 gpr_log(GPR_INFO, "Warming up");
400 gpr_timespec start = gpr_now(GPR_CLOCK_REALTIME);
401 gpr_sleep_until(
402 gpr_time_add(start, gpr_time_from_seconds(warmup_seconds, GPR_TIMESPAN)));
403
404 // Start a run
405 gpr_log(GPR_INFO, "Starting");
406 for (size_t i = 0; i < num_servers; i++) {
407 auto server = &servers[i];
408 if (!server->stream->Write(server_mark)) {
409 gpr_log(GPR_ERROR, "Couldn't write mark to server %zu", i);
410 }
411 }
412 for (size_t i = 0; i < num_clients; i++) {
413 auto client = &clients[i];
414 if (!client->stream->Write(client_mark)) {
415 gpr_log(GPR_ERROR, "Couldn't write mark to client %zu", i);
416 }
417 }
418 for (size_t i = 0; i < num_servers; i++) {
419 auto server = &servers[i];
420 if (!server->stream->Read(&server_status)) {
421 gpr_log(GPR_ERROR, "Couldn't get status from server %zu", i);
422 }
423 }
424 for (size_t i = 0; i < num_clients; i++) {
425 auto client = &clients[i];
426 if (!client->stream->Read(&client_status)) {
427 gpr_log(GPR_ERROR, "Couldn't get status from client %zu", i);
428 }
429 }
430
431 // Wait some time
432 gpr_log(GPR_INFO, "Running");
433 // Use gpr_sleep_until rather than this_thread::sleep_until to support
434 // compilers that don't work with this_thread
435 gpr_sleep_until(gpr_time_add(
436 start,
437 gpr_time_from_seconds(warmup_seconds + benchmark_seconds, GPR_TIMESPAN)));
438
439 gpr_timer_set_enabled(0);
440
441 // Finish a run
442 std::unique_ptr<ScenarioResult> result(new ScenarioResult);
443 Histogram merged_latencies;
444 std::unordered_map<int, int64_t> merged_statuses;
445
446 gpr_log(GPR_INFO, "Finishing clients");
447 for (size_t i = 0; i < num_clients; i++) {
448 auto client = &clients[i];
449 if (!client->stream->Write(client_mark)) {
450 gpr_log(GPR_ERROR, "Couldn't write mark to client %zu", i);
451 }
452 if (!client->stream->WritesDone()) {
453 gpr_log(GPR_ERROR, "Failed WritesDone for client %zu", i);
454 }
455 }
456 for (size_t i = 0; i < num_clients; i++) {
457 auto client = &clients[i];
458 // Read the client final status
459 if (client->stream->Read(&client_status)) {
460 gpr_log(GPR_INFO, "Received final status from client %zu", i);
461 const auto& stats = client_status.stats();
462 merged_latencies.MergeProto(stats.latencies());
463 for (int i = 0; i < stats.request_results_size(); i++) {
464 merged_statuses[stats.request_results(i).status_code()] +=
465 stats.request_results(i).count();
466 }
467 result->add_client_stats()->CopyFrom(stats);
468 // That final status should be the last message on the client stream
469 GPR_ASSERT(!client->stream->Read(&client_status));
470 } else {
471 gpr_log(GPR_ERROR, "Couldn't get final status from client %zu", i);
472 }
473 }
474 for (size_t i = 0; i < num_clients; i++) {
475 auto client = &clients[i];
476 Status s = client->stream->Finish();
477 result->add_client_success(s.ok());
478 if (!s.ok()) {
479 gpr_log(GPR_ERROR, "Client %zu had an error %s", i,
480 s.error_message().c_str());
481 }
482 }
483
484 merged_latencies.FillProto(result->mutable_latencies());
485 for (std::unordered_map<int, int64_t>::iterator it = merged_statuses.begin();
486 it != merged_statuses.end(); ++it) {
487 RequestResultCount* rrc = result->add_request_results();
488 rrc->set_status_code(it->first);
489 rrc->set_count(it->second);
490 }
491
492 gpr_log(GPR_INFO, "Finishing servers");
493 for (size_t i = 0; i < num_servers; i++) {
494 auto server = &servers[i];
495 if (!server->stream->Write(server_mark)) {
496 gpr_log(GPR_ERROR, "Couldn't write mark to server %zu", i);
497 }
498 if (!server->stream->WritesDone()) {
499 gpr_log(GPR_ERROR, "Failed WritesDone for server %zu", i);
500 }
501 }
502 for (size_t i = 0; i < num_servers; i++) {
503 auto server = &servers[i];
504 // Read the server final status
505 if (server->stream->Read(&server_status)) {
506 gpr_log(GPR_INFO, "Received final status from server %zu", i);
507 result->add_server_stats()->CopyFrom(server_status.stats());
508 result->add_server_cores(server_status.cores());
509 // That final status should be the last message on the server stream
510 GPR_ASSERT(!server->stream->Read(&server_status));
511 } else {
512 gpr_log(GPR_ERROR, "Couldn't get final status from server %zu", i);
513 }
514 }
515 for (size_t i = 0; i < num_servers; i++) {
516 auto server = &servers[i];
517 Status s = server->stream->Finish();
518 result->add_server_success(s.ok());
519 if (!s.ok()) {
520 gpr_log(GPR_ERROR, "Server %zu had an error %s", i,
521 s.error_message().c_str());
522 }
523 }
524
525 if (g_inproc_servers != nullptr) {
526 delete g_inproc_servers;
527 }
528 postprocess_scenario_result(result.get());
529 return result;
530 }
531
RunQuit(const grpc::string & credential_type)532 bool RunQuit(const grpc::string& credential_type) {
533 // Get client, server lists
534 bool result = true;
535 auto workers = get_workers("QPS_WORKERS");
536 if (workers.size() == 0) {
537 return false;
538 }
539
540 ChannelArguments channel_args;
541 for (size_t i = 0; i < workers.size(); i++) {
542 auto stub = WorkerService::NewStub(CreateChannel(
543 workers[i], GetCredentialsProvider()->GetChannelCredentials(
544 credential_type, &channel_args)));
545 Void dummy;
546 grpc::ClientContext ctx;
547 ctx.set_wait_for_ready(true);
548 Status s = stub->QuitWorker(&ctx, dummy, &dummy);
549 if (!s.ok()) {
550 gpr_log(GPR_ERROR, "Worker %zu could not be properly quit because %s", i,
551 s.error_message().c_str());
552 result = false;
553 }
554 }
555 return result;
556 }
557
558 } // namespace testing
559 } // namespace grpc
560