cfstream_test.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. /*
  2. *
  3. * Copyright 2019 The 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 <algorithm>
  19. #include <memory>
  20. #include <mutex>
  21. #include <random>
  22. #include <thread>
  23. #include <gtest/gtest.h>
  24. #include <grpc/grpc.h>
  25. #include <grpc/support/alloc.h>
  26. #include <grpc/support/atm.h>
  27. #include <grpc/support/log.h>
  28. #include <grpc/support/string_util.h>
  29. #include <grpc/support/time.h>
  30. #include <grpcpp/channel.h>
  31. #include <grpcpp/client_context.h>
  32. #include <grpcpp/create_channel.h>
  33. #include <grpcpp/health_check_service_interface.h>
  34. #include <grpcpp/server.h>
  35. #include <grpcpp/server_builder.h>
  36. #include "src/core/lib/backoff/backoff.h"
  37. #include "src/core/lib/gpr/env.h"
  38. #include "src/core/lib/iomgr/port.h"
  39. #include "src/proto/grpc/testing/echo.grpc.pb.h"
  40. #include "test/core/util/port.h"
  41. #include "test/core/util/test_config.h"
  42. #include "test/cpp/end2end/test_service_impl.h"
  43. #include "test/cpp/util/test_credentials_provider.h"
  44. #ifdef GRPC_CFSTREAM
  45. using grpc::ClientAsyncResponseReader;
  46. using grpc::testing::EchoRequest;
  47. using grpc::testing::EchoResponse;
  48. using grpc::testing::RequestParams;
  49. using std::chrono::system_clock;
  50. namespace grpc {
  51. namespace testing {
  52. namespace {
  53. struct TestScenario {
  54. TestScenario(const std::string& creds_type, const std::string& content)
  55. : credentials_type(creds_type), message_content(content) {}
  56. const std::string credentials_type;
  57. const std::string message_content;
  58. };
  59. class CFStreamTest : public ::testing::TestWithParam<TestScenario> {
  60. protected:
  61. CFStreamTest()
  62. : server_host_("grpctest"),
  63. interface_("lo0"),
  64. ipv4_address_("10.0.0.1") {}
  65. void DNSUp() {
  66. std::ostringstream cmd;
  67. // Add DNS entry for server_host_ in /etc/hosts
  68. cmd << "echo '" << ipv4_address_ << " " << server_host_
  69. << " ' | sudo tee -a /etc/hosts";
  70. std::system(cmd.str().c_str());
  71. }
  72. void DNSDown() {
  73. std::ostringstream cmd;
  74. // Remove DNS entry for server_host_ in /etc/hosts
  75. cmd << "sudo sed -i '.bak' '/" << server_host_ << "/d' /etc/hosts";
  76. std::system(cmd.str().c_str());
  77. }
  78. void InterfaceUp() {
  79. std::ostringstream cmd;
  80. cmd << "sudo /sbin/ifconfig " << interface_ << " alias " << ipv4_address_;
  81. std::system(cmd.str().c_str());
  82. }
  83. void InterfaceDown() {
  84. std::ostringstream cmd;
  85. cmd << "sudo /sbin/ifconfig " << interface_ << " -alias " << ipv4_address_;
  86. std::system(cmd.str().c_str());
  87. }
  88. void NetworkUp() {
  89. gpr_log(GPR_DEBUG, "Bringing network up");
  90. InterfaceUp();
  91. DNSUp();
  92. }
  93. void NetworkDown() {
  94. gpr_log(GPR_DEBUG, "Bringing network down");
  95. InterfaceDown();
  96. DNSDown();
  97. }
  98. void SetUp() override {
  99. NetworkUp();
  100. grpc_init();
  101. StartServer();
  102. }
  103. void TearDown() override {
  104. NetworkDown();
  105. StopServer();
  106. grpc_shutdown();
  107. }
  108. void StartServer() {
  109. port_ = grpc_pick_unused_port_or_die();
  110. server_.reset(new ServerData(port_, GetParam().credentials_type));
  111. server_->Start(server_host_);
  112. }
  113. void StopServer() { server_->Shutdown(); }
  114. std::unique_ptr<grpc::testing::EchoTestService::Stub> BuildStub(
  115. const std::shared_ptr<Channel>& channel) {
  116. return grpc::testing::EchoTestService::NewStub(channel);
  117. }
  118. std::shared_ptr<Channel> BuildChannel() {
  119. std::ostringstream server_address;
  120. server_address << server_host_ << ":" << port_;
  121. ChannelArguments args;
  122. auto channel_creds = GetCredentialsProvider()->GetChannelCredentials(
  123. GetParam().credentials_type, &args);
  124. return CreateCustomChannel(server_address.str(), channel_creds, args);
  125. }
  126. void SendRpc(
  127. const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
  128. bool expect_success = false) {
  129. auto response = std::unique_ptr<EchoResponse>(new EchoResponse());
  130. EchoRequest request;
  131. auto& msg = GetParam().message_content;
  132. request.set_message(msg);
  133. ClientContext context;
  134. Status status = stub->Echo(&context, request, response.get());
  135. if (status.ok()) {
  136. gpr_log(GPR_DEBUG, "RPC with succeeded");
  137. EXPECT_EQ(msg, response->message());
  138. } else {
  139. gpr_log(GPR_DEBUG, "RPC failed: %s", status.error_message().c_str());
  140. }
  141. if (expect_success) {
  142. EXPECT_TRUE(status.ok());
  143. }
  144. }
  145. void SendAsyncRpc(
  146. const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
  147. RequestParams param = RequestParams()) {
  148. EchoRequest request;
  149. request.set_message(GetParam().message_content);
  150. *request.mutable_param() = std::move(param);
  151. AsyncClientCall* call = new AsyncClientCall;
  152. call->response_reader =
  153. stub->PrepareAsyncEcho(&call->context, request, &cq_);
  154. call->response_reader->StartCall();
  155. call->response_reader->Finish(&call->reply, &call->status, (void*)call);
  156. }
  157. void ShutdownCQ() { cq_.Shutdown(); }
  158. bool CQNext(void** tag, bool* ok) {
  159. auto deadline = std::chrono::system_clock::now() + std::chrono::seconds(10);
  160. auto ret = cq_.AsyncNext(tag, ok, deadline);
  161. if (ret == grpc::CompletionQueue::GOT_EVENT) {
  162. return true;
  163. } else if (ret == grpc::CompletionQueue::SHUTDOWN) {
  164. return false;
  165. } else {
  166. GPR_ASSERT(ret == grpc::CompletionQueue::TIMEOUT);
  167. // This can happen if we hit the Apple CFStream bug which results in the
  168. // read stream freezing. We are ignoring hangs and timeouts, but these
  169. // tests are still useful as they can catch memory memory corruptions,
  170. // crashes and other bugs that don't result in test freeze/timeout.
  171. return false;
  172. }
  173. }
  174. bool WaitForChannelNotReady(Channel* channel, int timeout_seconds = 5) {
  175. const gpr_timespec deadline =
  176. grpc_timeout_seconds_to_deadline(timeout_seconds);
  177. grpc_connectivity_state state;
  178. while ((state = channel->GetState(false /* try_to_connect */)) ==
  179. GRPC_CHANNEL_READY) {
  180. if (!channel->WaitForStateChange(state, deadline)) return false;
  181. }
  182. return true;
  183. }
  184. bool WaitForChannelReady(Channel* channel, int timeout_seconds = 10) {
  185. const gpr_timespec deadline =
  186. grpc_timeout_seconds_to_deadline(timeout_seconds);
  187. grpc_connectivity_state state;
  188. while ((state = channel->GetState(true /* try_to_connect */)) !=
  189. GRPC_CHANNEL_READY) {
  190. if (!channel->WaitForStateChange(state, deadline)) return false;
  191. }
  192. return true;
  193. }
  194. struct AsyncClientCall {
  195. EchoResponse reply;
  196. ClientContext context;
  197. Status status;
  198. std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader;
  199. };
  200. private:
  201. struct ServerData {
  202. int port_;
  203. const std::string creds_;
  204. std::unique_ptr<Server> server_;
  205. TestServiceImpl service_;
  206. std::unique_ptr<std::thread> thread_;
  207. bool server_ready_ = false;
  208. ServerData(int port, const std::string& creds)
  209. : port_(port), creds_(creds) {}
  210. void Start(const std::string& server_host) {
  211. gpr_log(GPR_INFO, "starting server on port %d", port_);
  212. std::mutex mu;
  213. std::unique_lock<std::mutex> lock(mu);
  214. std::condition_variable cond;
  215. thread_.reset(new std::thread(
  216. std::bind(&ServerData::Serve, this, server_host, &mu, &cond)));
  217. cond.wait(lock, [this] { return server_ready_; });
  218. server_ready_ = false;
  219. gpr_log(GPR_INFO, "server startup complete");
  220. }
  221. void Serve(const std::string& server_host, std::mutex* mu,
  222. std::condition_variable* cond) {
  223. std::ostringstream server_address;
  224. server_address << server_host << ":" << port_;
  225. ServerBuilder builder;
  226. auto server_creds =
  227. GetCredentialsProvider()->GetServerCredentials(creds_);
  228. builder.AddListeningPort(server_address.str(), server_creds);
  229. builder.RegisterService(&service_);
  230. server_ = builder.BuildAndStart();
  231. std::lock_guard<std::mutex> lock(*mu);
  232. server_ready_ = true;
  233. cond->notify_one();
  234. }
  235. void Shutdown(bool join = true) {
  236. server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
  237. if (join) thread_->join();
  238. }
  239. };
  240. CompletionQueue cq_;
  241. const std::string server_host_;
  242. const std::string interface_;
  243. const std::string ipv4_address_;
  244. std::unique_ptr<ServerData> server_;
  245. int port_;
  246. };
  247. std::vector<TestScenario> CreateTestScenarios() {
  248. std::vector<TestScenario> scenarios;
  249. std::vector<std::string> credentials_types;
  250. std::vector<std::string> messages;
  251. credentials_types.push_back(kInsecureCredentialsType);
  252. auto sec_list = GetCredentialsProvider()->GetSecureCredentialsTypeList();
  253. for (auto sec = sec_list.begin(); sec != sec_list.end(); sec++) {
  254. credentials_types.push_back(*sec);
  255. }
  256. messages.push_back("🖖");
  257. for (size_t k = 1; k < GRPC_DEFAULT_MAX_RECV_MESSAGE_LENGTH / 1024; k *= 32) {
  258. std::string big_msg;
  259. for (size_t i = 0; i < k * 1024; ++i) {
  260. char c = 'a' + (i % 26);
  261. big_msg += c;
  262. }
  263. messages.push_back(big_msg);
  264. }
  265. for (auto cred = credentials_types.begin(); cred != credentials_types.end();
  266. ++cred) {
  267. for (auto msg = messages.begin(); msg != messages.end(); msg++) {
  268. scenarios.emplace_back(*cred, *msg);
  269. }
  270. }
  271. return scenarios;
  272. }
  273. INSTANTIATE_TEST_SUITE_P(CFStreamTest, CFStreamTest,
  274. ::testing::ValuesIn(CreateTestScenarios()));
  275. // gRPC should automatically detech network flaps (without enabling keepalives)
  276. // when CFStream is enabled
  277. TEST_P(CFStreamTest, NetworkTransition) {
  278. auto channel = BuildChannel();
  279. auto stub = BuildStub(channel);
  280. // Channel should be in READY state after we send an RPC
  281. SendRpc(stub, /*expect_success=*/true);
  282. EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
  283. std::atomic_bool shutdown{false};
  284. std::thread sender = std::thread([this, &stub, &shutdown]() {
  285. while (true) {
  286. if (shutdown.load()) {
  287. return;
  288. }
  289. SendRpc(stub);
  290. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  291. }
  292. });
  293. // bring down network
  294. NetworkDown();
  295. // network going down should be detected by cfstream
  296. EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
  297. // bring network interface back up
  298. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  299. NetworkUp();
  300. // channel should reconnect
  301. EXPECT_TRUE(WaitForChannelReady(channel.get()));
  302. EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
  303. shutdown.store(true);
  304. sender.join();
  305. }
  306. // Network flaps while RPCs are in flight
  307. TEST_P(CFStreamTest, NetworkFlapRpcsInFlight) {
  308. auto channel = BuildChannel();
  309. auto stub = BuildStub(channel);
  310. std::atomic_int rpcs_sent{0};
  311. // Channel should be in READY state after we send some RPCs
  312. for (int i = 0; i < 10; ++i) {
  313. RequestParams param;
  314. param.set_skip_cancelled_check(true);
  315. SendAsyncRpc(stub, param);
  316. ++rpcs_sent;
  317. }
  318. EXPECT_TRUE(WaitForChannelReady(channel.get()));
  319. // Bring down the network
  320. NetworkDown();
  321. std::thread thd = std::thread([this, &rpcs_sent]() {
  322. void* got_tag;
  323. bool ok = false;
  324. bool network_down = true;
  325. int total_completions = 0;
  326. while (CQNext(&got_tag, &ok)) {
  327. ++total_completions;
  328. GPR_ASSERT(ok);
  329. AsyncClientCall* call = static_cast<AsyncClientCall*>(got_tag);
  330. if (!call->status.ok()) {
  331. gpr_log(GPR_DEBUG, "RPC failed with error: %s",
  332. call->status.error_message().c_str());
  333. // Bring network up when RPCs start failing
  334. if (network_down) {
  335. NetworkUp();
  336. network_down = false;
  337. }
  338. } else {
  339. gpr_log(GPR_DEBUG, "RPC succeeded");
  340. }
  341. delete call;
  342. }
  343. // Remove line below and uncomment the following line after Apple CFStream
  344. // bug has been fixed.
  345. (void)rpcs_sent;
  346. // EXPECT_EQ(total_completions, rpcs_sent);
  347. });
  348. for (int i = 0; i < 100; ++i) {
  349. RequestParams param;
  350. param.set_skip_cancelled_check(true);
  351. SendAsyncRpc(stub, param);
  352. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  353. ++rpcs_sent;
  354. }
  355. ShutdownCQ();
  356. thd.join();
  357. }
  358. // Send a bunch of RPCs, some of which are expected to fail.
  359. // We should get back a response for all RPCs
  360. TEST_P(CFStreamTest, ConcurrentRpc) {
  361. auto channel = BuildChannel();
  362. auto stub = BuildStub(channel);
  363. std::atomic_int rpcs_sent{0};
  364. std::thread thd = std::thread([this, &rpcs_sent]() {
  365. void* got_tag;
  366. bool ok = false;
  367. int total_completions = 0;
  368. while (CQNext(&got_tag, &ok)) {
  369. ++total_completions;
  370. GPR_ASSERT(ok);
  371. AsyncClientCall* call = static_cast<AsyncClientCall*>(got_tag);
  372. if (!call->status.ok()) {
  373. gpr_log(GPR_DEBUG, "RPC failed with error: %s",
  374. call->status.error_message().c_str());
  375. // Bring network up when RPCs start failing
  376. } else {
  377. gpr_log(GPR_DEBUG, "RPC succeeded");
  378. }
  379. delete call;
  380. }
  381. // Remove line below and uncomment the following line after Apple CFStream
  382. // bug has been fixed.
  383. (void)rpcs_sent;
  384. // EXPECT_EQ(total_completions, rpcs_sent);
  385. });
  386. for (int i = 0; i < 10; ++i) {
  387. if (i % 3 == 0) {
  388. RequestParams param;
  389. ErrorStatus* error = param.mutable_expected_error();
  390. error->set_code(StatusCode::INTERNAL);
  391. error->set_error_message("internal error");
  392. SendAsyncRpc(stub, param);
  393. } else if (i % 5 == 0) {
  394. RequestParams param;
  395. param.set_echo_metadata(true);
  396. DebugInfo* info = param.mutable_debug_info();
  397. info->add_stack_entries("stack_entry1");
  398. info->add_stack_entries("stack_entry2");
  399. info->set_detail("detailed debug info");
  400. SendAsyncRpc(stub, param);
  401. } else {
  402. SendAsyncRpc(stub);
  403. }
  404. ++rpcs_sent;
  405. }
  406. ShutdownCQ();
  407. thd.join();
  408. }
  409. } // namespace
  410. } // namespace testing
  411. } // namespace grpc
  412. #endif // GRPC_CFSTREAM
  413. int main(int argc, char** argv) {
  414. ::testing::InitGoogleTest(&argc, argv);
  415. grpc::testing::TestEnvironment env(argc, argv);
  416. gpr_setenv("grpc_cfstream", "1");
  417. const auto result = RUN_ALL_TESTS();
  418. return result;
  419. }