driver.cc 25 KB

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