port_sharing_end2end_test.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. /*
  2. *
  3. * Copyright 2019 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 <mutex>
  19. #include <thread>
  20. #include <gtest/gtest.h>
  21. #include <grpc/grpc.h>
  22. #include <grpc/support/alloc.h>
  23. #include <grpc/support/log.h>
  24. #include <grpc/support/time.h>
  25. #include <grpcpp/channel.h>
  26. #include <grpcpp/client_context.h>
  27. #include <grpcpp/create_channel.h>
  28. #include <grpcpp/security/credentials.h>
  29. #include <grpcpp/security/server_credentials.h>
  30. #include <grpcpp/server.h>
  31. #include <grpcpp/server_builder.h>
  32. #include <grpcpp/server_context.h>
  33. #include "src/core/lib/gpr/env.h"
  34. #include "src/core/lib/iomgr/endpoint.h"
  35. #include "src/core/lib/iomgr/exec_ctx.h"
  36. #include "src/core/lib/iomgr/pollset.h"
  37. #include "src/core/lib/iomgr/port.h"
  38. #include "src/core/lib/iomgr/tcp_server.h"
  39. #include "src/core/lib/security/credentials/credentials.h"
  40. #include "src/proto/grpc/testing/echo.grpc.pb.h"
  41. #include "test/core/util/port.h"
  42. #include "test/core/util/test_config.h"
  43. #include "test/core/util/test_tcp_server.h"
  44. #include "test/cpp/end2end/test_service_impl.h"
  45. #include "test/cpp/util/test_credentials_provider.h"
  46. #ifdef GRPC_POSIX_SOCKET_TCP_SERVER
  47. #include "src/core/lib/iomgr/tcp_posix.h"
  48. namespace grpc {
  49. namespace testing {
  50. namespace {
  51. class TestScenario {
  52. public:
  53. TestScenario(bool server_port, bool pending_data,
  54. const std::string& creds_type)
  55. : server_has_port(server_port),
  56. queue_pending_data(pending_data),
  57. credentials_type(creds_type) {}
  58. void Log() const;
  59. // server has its own port or not
  60. bool server_has_port;
  61. // whether tcp server should read some data before handoff
  62. bool queue_pending_data;
  63. const std::string credentials_type;
  64. };
  65. std::ostream& operator<<(std::ostream& out, const TestScenario& scenario) {
  66. return out << "TestScenario{server_has_port="
  67. << (scenario.server_has_port ? "true" : "false")
  68. << ", queue_pending_data="
  69. << (scenario.queue_pending_data ? "true" : "false")
  70. << ", credentials='" << scenario.credentials_type << "'}";
  71. }
  72. void TestScenario::Log() const {
  73. std::ostringstream out;
  74. out << *this;
  75. gpr_log(GPR_ERROR, "%s", out.str().c_str());
  76. }
  77. // Set up a test tcp server which is in charge of accepting connections and
  78. // handing off the connections as fds.
  79. class TestTcpServer {
  80. public:
  81. TestTcpServer()
  82. : shutdown_(false),
  83. queue_data_(false),
  84. port_(grpc_pick_unused_port_or_die()) {
  85. std::ostringstream server_address;
  86. server_address << "localhost:" << port_;
  87. address_ = server_address.str();
  88. test_tcp_server_init(&tcp_server_, &TestTcpServer::OnConnect, this);
  89. GRPC_CLOSURE_INIT(&on_fd_released_, &TestTcpServer::OnFdReleased, this,
  90. grpc_schedule_on_exec_ctx);
  91. }
  92. ~TestTcpServer() {
  93. running_thread_.join();
  94. test_tcp_server_destroy(&tcp_server_);
  95. grpc_recycle_unused_port(port_);
  96. }
  97. // Read some data before handing off the connection.
  98. void SetQueueData() { queue_data_ = true; }
  99. void Start() {
  100. test_tcp_server_start(&tcp_server_, port_);
  101. gpr_log(GPR_INFO, "Test TCP server started at %s", address_.c_str());
  102. }
  103. const std::string& address() { return address_; }
  104. void SetAcceptor(
  105. std::unique_ptr<experimental::ExternalConnectionAcceptor> acceptor) {
  106. connection_acceptor_ = std::move(acceptor);
  107. }
  108. void Run() {
  109. running_thread_ = std::thread([this]() {
  110. while (true) {
  111. {
  112. std::lock_guard<std::mutex> lock(mu_);
  113. if (shutdown_) {
  114. return;
  115. }
  116. }
  117. test_tcp_server_poll(&tcp_server_, 1);
  118. }
  119. });
  120. }
  121. void Shutdown() {
  122. std::lock_guard<std::mutex> lock(mu_);
  123. shutdown_ = true;
  124. }
  125. static void OnConnect(void* arg, grpc_endpoint* tcp,
  126. grpc_pollset* accepting_pollset,
  127. grpc_tcp_server_acceptor* acceptor) {
  128. auto* self = static_cast<TestTcpServer*>(arg);
  129. self->OnConnect(tcp, accepting_pollset, acceptor);
  130. }
  131. static void OnFdReleased(void* arg, grpc_error_handle err) {
  132. auto* self = static_cast<TestTcpServer*>(arg);
  133. self->OnFdReleased(err);
  134. }
  135. private:
  136. void OnConnect(grpc_endpoint* tcp, grpc_pollset* /*accepting_pollset*/,
  137. grpc_tcp_server_acceptor* acceptor) {
  138. std::string peer(grpc_endpoint_get_peer(tcp));
  139. gpr_log(GPR_INFO, "Got incoming connection! from %s", peer.c_str());
  140. EXPECT_FALSE(acceptor->external_connection);
  141. listener_fd_ = grpc_tcp_server_port_fd(
  142. acceptor->from_server, acceptor->port_index, acceptor->fd_index);
  143. gpr_free(acceptor);
  144. grpc_tcp_destroy_and_release_fd(tcp, &fd_, &on_fd_released_);
  145. }
  146. void OnFdReleased(grpc_error_handle err) {
  147. EXPECT_EQ(GRPC_ERROR_NONE, err);
  148. experimental::ExternalConnectionAcceptor::NewConnectionParameters p;
  149. p.listener_fd = listener_fd_;
  150. p.fd = fd_;
  151. if (queue_data_) {
  152. char buf[1024];
  153. ssize_t read_bytes = 0;
  154. while (read_bytes <= 0) {
  155. read_bytes = read(fd_, buf, 1024);
  156. }
  157. Slice data(buf, read_bytes);
  158. p.read_buffer = ByteBuffer(&data, 1);
  159. }
  160. gpr_log(GPR_INFO, "Handing off fd %d with data size %d from listener fd %d",
  161. fd_, static_cast<int>(p.read_buffer.Length()), listener_fd_);
  162. connection_acceptor_->HandleNewConnection(&p);
  163. }
  164. std::mutex mu_;
  165. bool shutdown_;
  166. int listener_fd_ = -1;
  167. int fd_ = -1;
  168. bool queue_data_ = false;
  169. grpc_closure on_fd_released_;
  170. std::thread running_thread_;
  171. int port_ = -1;
  172. std::string address_;
  173. std::unique_ptr<experimental::ExternalConnectionAcceptor>
  174. connection_acceptor_;
  175. test_tcp_server tcp_server_;
  176. };
  177. class PortSharingEnd2endTest : public ::testing::TestWithParam<TestScenario> {
  178. protected:
  179. PortSharingEnd2endTest() : is_server_started_(false), first_picked_port_(0) {
  180. GetParam().Log();
  181. }
  182. void SetUp() override {
  183. if (GetParam().queue_pending_data) {
  184. tcp_server1_.SetQueueData();
  185. tcp_server2_.SetQueueData();
  186. }
  187. tcp_server1_.Start();
  188. tcp_server2_.Start();
  189. ServerBuilder builder;
  190. if (GetParam().server_has_port) {
  191. int port = grpc_pick_unused_port_or_die();
  192. first_picked_port_ = port;
  193. server_address_ << "localhost:" << port;
  194. auto creds = GetCredentialsProvider()->GetServerCredentials(
  195. GetParam().credentials_type);
  196. builder.AddListeningPort(server_address_.str(), creds);
  197. gpr_log(GPR_INFO, "gRPC server listening on %s",
  198. server_address_.str().c_str());
  199. }
  200. auto server_creds = GetCredentialsProvider()->GetServerCredentials(
  201. GetParam().credentials_type);
  202. auto acceptor1 = builder.experimental().AddExternalConnectionAcceptor(
  203. ServerBuilder::experimental_type::ExternalConnectionType::FROM_FD,
  204. server_creds);
  205. tcp_server1_.SetAcceptor(std::move(acceptor1));
  206. auto acceptor2 = builder.experimental().AddExternalConnectionAcceptor(
  207. ServerBuilder::experimental_type::ExternalConnectionType::FROM_FD,
  208. server_creds);
  209. tcp_server2_.SetAcceptor(std::move(acceptor2));
  210. builder.RegisterService(&service_);
  211. server_ = builder.BuildAndStart();
  212. is_server_started_ = true;
  213. tcp_server1_.Run();
  214. tcp_server2_.Run();
  215. }
  216. void TearDown() override {
  217. tcp_server1_.Shutdown();
  218. tcp_server2_.Shutdown();
  219. if (is_server_started_) {
  220. server_->Shutdown();
  221. }
  222. if (first_picked_port_ > 0) {
  223. grpc_recycle_unused_port(first_picked_port_);
  224. }
  225. }
  226. void ResetStubs() {
  227. EXPECT_TRUE(is_server_started_);
  228. ChannelArguments args;
  229. args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, 1);
  230. auto channel_creds = GetCredentialsProvider()->GetChannelCredentials(
  231. GetParam().credentials_type, &args);
  232. channel_handoff1_ =
  233. CreateCustomChannel(tcp_server1_.address(), channel_creds, args);
  234. stub_handoff1_ = EchoTestService::NewStub(channel_handoff1_);
  235. channel_handoff2_ =
  236. CreateCustomChannel(tcp_server2_.address(), channel_creds, args);
  237. stub_handoff2_ = EchoTestService::NewStub(channel_handoff2_);
  238. if (GetParam().server_has_port) {
  239. ChannelArguments direct_args;
  240. direct_args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, 1);
  241. auto direct_creds = GetCredentialsProvider()->GetChannelCredentials(
  242. GetParam().credentials_type, &direct_args);
  243. channel_direct_ =
  244. CreateCustomChannel(server_address_.str(), direct_creds, direct_args);
  245. stub_direct_ = EchoTestService::NewStub(channel_direct_);
  246. }
  247. }
  248. bool is_server_started_;
  249. // channel/stub to the test tcp server, the connection will be handed to the
  250. // grpc server.
  251. std::shared_ptr<Channel> channel_handoff1_;
  252. std::unique_ptr<EchoTestService::Stub> stub_handoff1_;
  253. std::shared_ptr<Channel> channel_handoff2_;
  254. std::unique_ptr<EchoTestService::Stub> stub_handoff2_;
  255. // channel/stub to talk to the grpc server directly, if applicable.
  256. std::shared_ptr<Channel> channel_direct_;
  257. std::unique_ptr<EchoTestService::Stub> stub_direct_;
  258. std::unique_ptr<Server> server_;
  259. std::ostringstream server_address_;
  260. TestServiceImpl service_;
  261. TestTcpServer tcp_server1_;
  262. TestTcpServer tcp_server2_;
  263. int first_picked_port_;
  264. };
  265. void SendRpc(EchoTestService::Stub* stub, int num_rpcs) {
  266. EchoRequest request;
  267. EchoResponse response;
  268. request.set_message("Hello hello hello hello");
  269. for (int i = 0; i < num_rpcs; ++i) {
  270. ClientContext context;
  271. Status s = stub->Echo(&context, request, &response);
  272. EXPECT_EQ(response.message(), request.message());
  273. EXPECT_TRUE(s.ok());
  274. }
  275. }
  276. std::vector<TestScenario> CreateTestScenarios() {
  277. std::vector<TestScenario> scenarios;
  278. std::vector<std::string> credentials_types;
  279. #if TARGET_OS_IPHONE
  280. // Workaround Apple CFStream bug
  281. gpr_setenv("grpc_cfstream", "0");
  282. #endif
  283. credentials_types = GetCredentialsProvider()->GetSecureCredentialsTypeList();
  284. // Only allow insecure credentials type when it is registered with the
  285. // provider. User may create providers that do not have insecure.
  286. if (GetCredentialsProvider()->GetChannelCredentials(kInsecureCredentialsType,
  287. nullptr) != nullptr) {
  288. credentials_types.push_back(kInsecureCredentialsType);
  289. }
  290. GPR_ASSERT(!credentials_types.empty());
  291. for (const auto& cred : credentials_types) {
  292. for (auto server_has_port : {true, false}) {
  293. for (auto queue_pending_data : {true, false}) {
  294. scenarios.emplace_back(server_has_port, queue_pending_data, cred);
  295. }
  296. }
  297. }
  298. return scenarios;
  299. }
  300. TEST_P(PortSharingEnd2endTest, HandoffAndDirectCalls) {
  301. ResetStubs();
  302. SendRpc(stub_handoff1_.get(), 5);
  303. if (GetParam().server_has_port) {
  304. SendRpc(stub_direct_.get(), 5);
  305. }
  306. }
  307. TEST_P(PortSharingEnd2endTest, MultipleHandoff) {
  308. for (int i = 0; i < 3; i++) {
  309. ResetStubs();
  310. SendRpc(stub_handoff2_.get(), 1);
  311. }
  312. }
  313. TEST_P(PortSharingEnd2endTest, TwoHandoffPorts) {
  314. for (int i = 0; i < 3; i++) {
  315. ResetStubs();
  316. SendRpc(stub_handoff1_.get(), 5);
  317. SendRpc(stub_handoff2_.get(), 5);
  318. }
  319. }
  320. INSTANTIATE_TEST_SUITE_P(PortSharingEnd2end, PortSharingEnd2endTest,
  321. ::testing::ValuesIn(CreateTestScenarios()));
  322. } // namespace
  323. } // namespace testing
  324. } // namespace grpc
  325. #endif // GRPC_POSIX_SOCKET_TCP_SERVER
  326. int main(int argc, char** argv) {
  327. grpc::testing::TestEnvironment env(argc, argv);
  328. ::testing::InitGoogleTest(&argc, argv);
  329. return RUN_ALL_TESTS();
  330. }