driver.cc 19 KB

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