client_sync.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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 <chrono>
  19. #include <memory>
  20. #include <mutex>
  21. #include <sstream>
  22. #include <string>
  23. #include <thread>
  24. #include <vector>
  25. #include <grpc/grpc.h>
  26. #include <grpc/support/alloc.h>
  27. #include <grpc/support/log.h>
  28. #include <grpc/support/time.h>
  29. #include <grpcpp/channel.h>
  30. #include <grpcpp/client_context.h>
  31. #include <grpcpp/server.h>
  32. #include <grpcpp/server_builder.h>
  33. #include "src/core/lib/profiling/timers.h"
  34. #include "src/proto/grpc/testing/benchmark_service.grpc.pb.h"
  35. #include "test/cpp/qps/client.h"
  36. #include "test/cpp/qps/interarrival.h"
  37. #include "test/cpp/qps/usage_timer.h"
  38. namespace grpc {
  39. namespace testing {
  40. static std::unique_ptr<BenchmarkService::Stub> BenchmarkStubCreator(
  41. const std::shared_ptr<Channel>& ch) {
  42. return BenchmarkService::NewStub(ch);
  43. }
  44. class SynchronousClient
  45. : public ClientImpl<BenchmarkService::Stub, SimpleRequest> {
  46. public:
  47. explicit SynchronousClient(const ClientConfig& config)
  48. : ClientImpl<BenchmarkService::Stub, SimpleRequest>(
  49. config, BenchmarkStubCreator) {
  50. num_threads_ =
  51. config.outstanding_rpcs_per_channel() * config.client_channels();
  52. responses_.resize(num_threads_);
  53. SetupLoadTest(config, num_threads_);
  54. }
  55. ~SynchronousClient() override {}
  56. virtual bool InitThreadFuncImpl(size_t thread_idx) = 0;
  57. virtual bool ThreadFuncImpl(HistogramEntry* entry, size_t thread_idx) = 0;
  58. void ThreadFunc(size_t thread_idx, Thread* t) override {
  59. if (!InitThreadFuncImpl(thread_idx)) {
  60. return;
  61. }
  62. for (;;) {
  63. // run the loop body
  64. HistogramEntry entry;
  65. const bool thread_still_ok = ThreadFuncImpl(&entry, thread_idx);
  66. t->UpdateHistogram(&entry);
  67. if (!thread_still_ok || ThreadCompleted()) {
  68. return;
  69. }
  70. }
  71. }
  72. protected:
  73. // WaitToIssue returns false if we realize that we need to break out
  74. bool WaitToIssue(int thread_idx) {
  75. if (!closed_loop_) {
  76. const gpr_timespec next_issue_time = NextIssueTime(thread_idx);
  77. // Avoid sleeping for too long continuously because we might
  78. // need to terminate before then. This is an issue since
  79. // exponential distribution can occasionally produce bad outliers
  80. while (true) {
  81. const gpr_timespec one_sec_delay =
  82. gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
  83. gpr_time_from_seconds(1, GPR_TIMESPAN));
  84. if (gpr_time_cmp(next_issue_time, one_sec_delay) <= 0) {
  85. gpr_sleep_until(next_issue_time);
  86. return true;
  87. } else {
  88. gpr_sleep_until(one_sec_delay);
  89. if (gpr_atm_acq_load(&thread_pool_done_) != static_cast<gpr_atm>(0)) {
  90. return false;
  91. }
  92. }
  93. }
  94. }
  95. return true;
  96. }
  97. size_t num_threads_;
  98. std::vector<SimpleResponse> responses_;
  99. };
  100. class SynchronousUnaryClient final : public SynchronousClient {
  101. public:
  102. explicit SynchronousUnaryClient(const ClientConfig& config)
  103. : SynchronousClient(config) {
  104. StartThreads(num_threads_);
  105. }
  106. ~SynchronousUnaryClient() override {}
  107. bool InitThreadFuncImpl(size_t /*thread_idx*/) override { return true; }
  108. bool ThreadFuncImpl(HistogramEntry* entry, size_t thread_idx) override {
  109. if (!WaitToIssue(thread_idx)) {
  110. return true;
  111. }
  112. auto* stub = channels_[thread_idx % channels_.size()].get_stub();
  113. double start = UsageTimer::Now();
  114. GPR_TIMER_SCOPE("SynchronousUnaryClient::ThreadFunc", 0);
  115. grpc::ClientContext context;
  116. grpc::Status s =
  117. stub->UnaryCall(&context, request_, &responses_[thread_idx]);
  118. if (s.ok()) {
  119. entry->set_value((UsageTimer::Now() - start) * 1e9);
  120. }
  121. entry->set_status(s.error_code());
  122. return true;
  123. }
  124. private:
  125. void DestroyMultithreading() final { EndThreads(); }
  126. };
  127. template <class StreamType>
  128. class SynchronousStreamingClient : public SynchronousClient {
  129. public:
  130. explicit SynchronousStreamingClient(const ClientConfig& config)
  131. : SynchronousClient(config),
  132. context_(num_threads_),
  133. stream_(num_threads_),
  134. stream_mu_(num_threads_),
  135. shutdown_(num_threads_),
  136. messages_per_stream_(config.messages_per_stream()),
  137. messages_issued_(num_threads_) {
  138. StartThreads(num_threads_);
  139. }
  140. ~SynchronousStreamingClient() override {
  141. CleanupAllStreams([this](size_t thread_idx) {
  142. // Don't log any kind of error since we may have canceled this
  143. stream_[thread_idx]->Finish().IgnoreError();
  144. });
  145. }
  146. protected:
  147. std::vector<grpc::ClientContext> context_;
  148. std::vector<std::unique_ptr<StreamType>> stream_;
  149. // stream_mu_ is only needed when changing an element of stream_ or context_
  150. std::vector<std::mutex> stream_mu_;
  151. // use struct Bool rather than bool because vector<bool> is not concurrent
  152. struct Bool {
  153. bool val;
  154. Bool() : val(false) {}
  155. };
  156. std::vector<Bool> shutdown_;
  157. const int messages_per_stream_;
  158. std::vector<int> messages_issued_;
  159. void FinishStream(HistogramEntry* entry, size_t thread_idx) {
  160. Status s = stream_[thread_idx]->Finish();
  161. // don't set the value since the stream is failed and shouldn't be timed
  162. entry->set_status(s.error_code());
  163. if (!s.ok()) {
  164. std::lock_guard<std::mutex> l(stream_mu_[thread_idx]);
  165. if (!shutdown_[thread_idx].val) {
  166. gpr_log(GPR_ERROR, "Stream %" PRIuPTR " received an error %s",
  167. thread_idx, s.error_message().c_str());
  168. }
  169. }
  170. // Lock the stream_mu_ now because the client context could change
  171. std::lock_guard<std::mutex> l(stream_mu_[thread_idx]);
  172. context_[thread_idx].~ClientContext();
  173. new (&context_[thread_idx]) ClientContext();
  174. }
  175. void CleanupAllStreams(const std::function<void(size_t)>& cleaner) {
  176. std::vector<std::thread> cleanup_threads;
  177. for (size_t i = 0; i < num_threads_; i++) {
  178. cleanup_threads.emplace_back([this, i, cleaner] {
  179. std::lock_guard<std::mutex> l(stream_mu_[i]);
  180. shutdown_[i].val = true;
  181. if (stream_[i]) {
  182. cleaner(i);
  183. }
  184. });
  185. }
  186. for (auto& th : cleanup_threads) {
  187. th.join();
  188. }
  189. }
  190. private:
  191. void DestroyMultithreading() final {
  192. CleanupAllStreams(
  193. [this](size_t thread_idx) { context_[thread_idx].TryCancel(); });
  194. EndThreads();
  195. }
  196. };
  197. class SynchronousStreamingPingPongClient final
  198. : public SynchronousStreamingClient<
  199. grpc::ClientReaderWriter<SimpleRequest, SimpleResponse>> {
  200. public:
  201. explicit SynchronousStreamingPingPongClient(const ClientConfig& config)
  202. : SynchronousStreamingClient(config) {}
  203. ~SynchronousStreamingPingPongClient() override {
  204. CleanupAllStreams(
  205. [this](size_t thread_idx) { stream_[thread_idx]->WritesDone(); });
  206. }
  207. private:
  208. bool InitThreadFuncImpl(size_t thread_idx) override {
  209. auto* stub = channels_[thread_idx % channels_.size()].get_stub();
  210. std::lock_guard<std::mutex> l(stream_mu_[thread_idx]);
  211. if (!shutdown_[thread_idx].val) {
  212. stream_[thread_idx] = stub->StreamingCall(&context_[thread_idx]);
  213. } else {
  214. return false;
  215. }
  216. messages_issued_[thread_idx] = 0;
  217. return true;
  218. }
  219. bool ThreadFuncImpl(HistogramEntry* entry, size_t thread_idx) override {
  220. if (!WaitToIssue(thread_idx)) {
  221. return true;
  222. }
  223. GPR_TIMER_SCOPE("SynchronousStreamingPingPongClient::ThreadFunc", 0);
  224. double start = UsageTimer::Now();
  225. if (stream_[thread_idx]->Write(request_) &&
  226. stream_[thread_idx]->Read(&responses_[thread_idx])) {
  227. entry->set_value((UsageTimer::Now() - start) * 1e9);
  228. // don't set the status since there isn't one yet
  229. if ((messages_per_stream_ != 0) &&
  230. (++messages_issued_[thread_idx] < messages_per_stream_)) {
  231. return true;
  232. } else if (messages_per_stream_ == 0) {
  233. return true;
  234. } else {
  235. // Fall through to the below resetting code after finish
  236. }
  237. }
  238. stream_[thread_idx]->WritesDone();
  239. FinishStream(entry, thread_idx);
  240. auto* stub = channels_[thread_idx % channels_.size()].get_stub();
  241. std::lock_guard<std::mutex> l(stream_mu_[thread_idx]);
  242. if (!shutdown_[thread_idx].val) {
  243. stream_[thread_idx] = stub->StreamingCall(&context_[thread_idx]);
  244. } else {
  245. stream_[thread_idx].reset();
  246. return false;
  247. }
  248. messages_issued_[thread_idx] = 0;
  249. return true;
  250. }
  251. };
  252. class SynchronousStreamingFromClientClient final
  253. : public SynchronousStreamingClient<grpc::ClientWriter<SimpleRequest>> {
  254. public:
  255. explicit SynchronousStreamingFromClientClient(const ClientConfig& config)
  256. : SynchronousStreamingClient(config), last_issue_(num_threads_) {}
  257. ~SynchronousStreamingFromClientClient() override {
  258. CleanupAllStreams(
  259. [this](size_t thread_idx) { stream_[thread_idx]->WritesDone(); });
  260. }
  261. private:
  262. std::vector<double> last_issue_;
  263. bool InitThreadFuncImpl(size_t thread_idx) override {
  264. auto* stub = channels_[thread_idx % channels_.size()].get_stub();
  265. std::lock_guard<std::mutex> l(stream_mu_[thread_idx]);
  266. if (!shutdown_[thread_idx].val) {
  267. stream_[thread_idx] = stub->StreamingFromClient(&context_[thread_idx],
  268. &responses_[thread_idx]);
  269. } else {
  270. return false;
  271. }
  272. last_issue_[thread_idx] = UsageTimer::Now();
  273. return true;
  274. }
  275. bool ThreadFuncImpl(HistogramEntry* entry, size_t thread_idx) override {
  276. // Figure out how to make histogram sensible if this is rate-paced
  277. if (!WaitToIssue(thread_idx)) {
  278. return true;
  279. }
  280. GPR_TIMER_SCOPE("SynchronousStreamingFromClientClient::ThreadFunc", 0);
  281. if (stream_[thread_idx]->Write(request_)) {
  282. double now = UsageTimer::Now();
  283. entry->set_value((now - last_issue_[thread_idx]) * 1e9);
  284. last_issue_[thread_idx] = now;
  285. return true;
  286. }
  287. stream_[thread_idx]->WritesDone();
  288. FinishStream(entry, thread_idx);
  289. auto* stub = channels_[thread_idx % channels_.size()].get_stub();
  290. std::lock_guard<std::mutex> l(stream_mu_[thread_idx]);
  291. if (!shutdown_[thread_idx].val) {
  292. stream_[thread_idx] = stub->StreamingFromClient(&context_[thread_idx],
  293. &responses_[thread_idx]);
  294. } else {
  295. stream_[thread_idx].reset();
  296. return false;
  297. }
  298. return true;
  299. }
  300. };
  301. class SynchronousStreamingFromServerClient final
  302. : public SynchronousStreamingClient<grpc::ClientReader<SimpleResponse>> {
  303. public:
  304. explicit SynchronousStreamingFromServerClient(const ClientConfig& config)
  305. : SynchronousStreamingClient(config), last_recv_(num_threads_) {}
  306. ~SynchronousStreamingFromServerClient() override {}
  307. private:
  308. std::vector<double> last_recv_;
  309. bool InitThreadFuncImpl(size_t thread_idx) override {
  310. auto* stub = channels_[thread_idx % channels_.size()].get_stub();
  311. std::lock_guard<std::mutex> l(stream_mu_[thread_idx]);
  312. if (!shutdown_[thread_idx].val) {
  313. stream_[thread_idx] =
  314. stub->StreamingFromServer(&context_[thread_idx], request_);
  315. } else {
  316. return false;
  317. }
  318. last_recv_[thread_idx] = UsageTimer::Now();
  319. return true;
  320. }
  321. bool ThreadFuncImpl(HistogramEntry* entry, size_t thread_idx) override {
  322. GPR_TIMER_SCOPE("SynchronousStreamingFromServerClient::ThreadFunc", 0);
  323. if (stream_[thread_idx]->Read(&responses_[thread_idx])) {
  324. double now = UsageTimer::Now();
  325. entry->set_value((now - last_recv_[thread_idx]) * 1e9);
  326. last_recv_[thread_idx] = now;
  327. return true;
  328. }
  329. FinishStream(entry, thread_idx);
  330. auto* stub = channels_[thread_idx % channels_.size()].get_stub();
  331. std::lock_guard<std::mutex> l(stream_mu_[thread_idx]);
  332. if (!shutdown_[thread_idx].val) {
  333. stream_[thread_idx] =
  334. stub->StreamingFromServer(&context_[thread_idx], request_);
  335. } else {
  336. stream_[thread_idx].reset();
  337. return false;
  338. }
  339. return true;
  340. }
  341. };
  342. class SynchronousStreamingBothWaysClient final
  343. : public SynchronousStreamingClient<
  344. grpc::ClientReaderWriter<SimpleRequest, SimpleResponse>> {
  345. public:
  346. explicit SynchronousStreamingBothWaysClient(const ClientConfig& config)
  347. : SynchronousStreamingClient(config) {}
  348. ~SynchronousStreamingBothWaysClient() override {
  349. CleanupAllStreams(
  350. [this](size_t thread_idx) { stream_[thread_idx]->WritesDone(); });
  351. }
  352. private:
  353. bool InitThreadFuncImpl(size_t thread_idx) override {
  354. auto* stub = channels_[thread_idx % channels_.size()].get_stub();
  355. std::lock_guard<std::mutex> l(stream_mu_[thread_idx]);
  356. if (!shutdown_[thread_idx].val) {
  357. stream_[thread_idx] = stub->StreamingBothWays(&context_[thread_idx]);
  358. } else {
  359. return false;
  360. }
  361. return true;
  362. }
  363. bool ThreadFuncImpl(HistogramEntry* /*entry*/,
  364. size_t /*thread_idx*/) override {
  365. // TODO (vjpai): Do this
  366. return true;
  367. }
  368. };
  369. std::unique_ptr<Client> CreateSynchronousClient(const ClientConfig& config) {
  370. GPR_ASSERT(!config.use_coalesce_api()); // not supported yet.
  371. switch (config.rpc_type()) {
  372. case UNARY:
  373. return std::unique_ptr<Client>(new SynchronousUnaryClient(config));
  374. case STREAMING:
  375. return std::unique_ptr<Client>(
  376. new SynchronousStreamingPingPongClient(config));
  377. case STREAMING_FROM_CLIENT:
  378. return std::unique_ptr<Client>(
  379. new SynchronousStreamingFromClientClient(config));
  380. case STREAMING_FROM_SERVER:
  381. return std::unique_ptr<Client>(
  382. new SynchronousStreamingFromServerClient(config));
  383. case STREAMING_BOTH_WAYS:
  384. return std::unique_ptr<Client>(
  385. new SynchronousStreamingBothWaysClient(config));
  386. default:
  387. assert(false);
  388. return nullptr;
  389. }
  390. }
  391. } // namespace testing
  392. } // namespace grpc