Debian Codegraph @

test/core/event_engine/posix/posix_endpoint_test.cc

raw
1 // Copyright 2022 gRPC Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "src/core/lib/event_engine/posix_engine/posix_endpoint.h"
16
17 #include <algorithm>
18 #include <chrono>
19 #include <list>
20 #include <memory>
21 #include <ratio>
22 #include <string>
23 #include <thread>
24 #include <vector>
25
26 #include "absl/status/statusor.h"
27 #include "absl/strings/str_cat.h"
28 #include "absl/strings/str_split.h"
29 #include "absl/strings/string_view.h"
30 #include "gtest/gtest.h"
31
32 #include <grpc/event_engine/event_engine.h>
33 #include <grpc/grpc.h>
34
35 #include "src/core/lib/channel/channel_args.h"
36 #include "src/core/lib/event_engine/channel_args_endpoint_config.h"
37 #include "src/core/lib/event_engine/poller.h"
38 #include "src/core/lib/event_engine/posix_engine/event_poller.h"
39 #include "src/core/lib/event_engine/posix_engine/event_poller_posix_default.h"
40 #include "src/core/lib/event_engine/posix_engine/posix_engine.h"
41 #include "src/core/lib/event_engine/posix_engine/posix_engine_closure.h"
42 #include "src/core/lib/event_engine/posix_engine/tcp_socket_utils.h"
43 #include "src/core/lib/gprpp/dual_ref_counted.h"
44 #include "src/core/lib/gprpp/global_config.h"
45 #include "src/core/lib/gprpp/memory.h"
46 #include "src/core/lib/gprpp/notification.h"
47 #include "src/core/lib/gprpp/ref_counted_ptr.h"
48 #include "src/core/lib/resource_quota/resource_quota.h"
49 #include "test/core/event_engine/posix/posix_engine_test_utils.h"
50 #include "test/core/event_engine/test_suite/event_engine_test_utils.h"
51 #include "test/core/event_engine/test_suite/oracle_event_engine_posix.h"
52 #include "test/core/util/port.h"
53
54 GPR_GLOBAL_CONFIG_DECLARE_STRING(grpc_poll_strategy);
55
56 namespace grpc_event_engine {
57 namespace posix_engine {
58
59 namespace {
60
61 using ::grpc_event_engine::experimental::ChannelArgsEndpointConfig;
62 using ::grpc_event_engine::experimental::EventEngine;
63 using ::grpc_event_engine::experimental::GetNextSendMessage;
64 using ::grpc_event_engine::experimental::Poller;
65 using ::grpc_event_engine::experimental::PosixEventEngine;
66 using ::grpc_event_engine::experimental::PosixOracleEventEngine;
67 using ::grpc_event_engine::experimental::URIToResolvedAddress;
68 using ::grpc_event_engine::experimental::WaitForSingleOwner;
69 using Endpoint = ::grpc_event_engine::experimental::EventEngine::Endpoint;
70 using Listener = ::grpc_event_engine::experimental::EventEngine::Listener;
71 using namespace std::chrono_literals;
72
73 constexpr int kMinMessageSize = 1024;
74 constexpr int kNumConnections = 10;
75 constexpr int kNumExchangedMessages = 100;
76 std::atomic<int> g_num_active_connections{0};
77
78 struct Connection {
79 std::unique_ptr<EventEngine::Endpoint> client_endpoint;
80 std::unique_ptr<EventEngine::Endpoint> server_endpoint;
81 };
82
83 std::list<Connection> CreateConnectedEndpoints(
84 PosixEventPoller& poller, bool is_zero_copy_enabled, int num_connections,
85 std::shared_ptr<EventEngine> posix_ee,
86 std::shared_ptr<EventEngine> oracle_ee) {
87 std::list<Connection> connections;
88 auto memory_quota = std::make_unique<grpc_core::MemoryQuota>("bar");
89 std::string target_addr = absl::StrCat(
90 "ipv6:[::1]:", std::to_string(grpc_pick_unused_port_or_die()));
91 EventEngine::ResolvedAddress resolved_addr =
92 URIToResolvedAddress(target_addr);
93 std::unique_ptr<EventEngine::Endpoint> server_endpoint;
94 grpc_core::Notification* server_signal = new grpc_core::Notification();
95
96 Listener::AcceptCallback accept_cb =
97 [&server_endpoint, &server_signal](
98 std::unique_ptr<Endpoint> ep,
99 grpc_core::MemoryAllocator /*memory_allocator*/) {
100 server_endpoint = std::move(ep);
101 server_signal->Notify();
102 };
103 grpc_core::ChannelArgs args;
104 auto quota = grpc_core::ResourceQuota::Default();
105 args = args.Set(GRPC_ARG_RESOURCE_QUOTA, quota);
106 if (is_zero_copy_enabled) {
107 args = args.Set(GRPC_ARG_TCP_TX_ZEROCOPY_ENABLED, 1);
108 args = args.Set(GRPC_ARG_TCP_TX_ZEROCOPY_SEND_BYTES_THRESHOLD,
109 kMinMessageSize);
110 }
111 ChannelArgsEndpointConfig config(args);
112 auto listener = oracle_ee->CreateListener(
113 std::move(accept_cb),
114 [](absl::Status status) { ASSERT_TRUE(status.ok()); }, config,
115 std::make_unique<grpc_core::MemoryQuota>("foo"));
116 GPR_ASSERT(listener.ok());
117
118 EXPECT_TRUE((*listener)->Bind(resolved_addr).ok());
119 EXPECT_TRUE((*listener)->Start().ok());
120
121 // Create client socket and connect to the target address.
122 for (int i = 0; i < num_connections; ++i) {
123 int client_fd = ConnectToServerOrDie(resolved_addr);
124 EventHandle* handle =
125 poller.CreateHandle(client_fd, "test", poller.CanTrackErrors());
126 EXPECT_NE(handle, nullptr);
127 server_signal->WaitForNotification();
128 EXPECT_NE(server_endpoint, nullptr);
129 ++g_num_active_connections;
130 PosixTcpOptions options = TcpOptionsFromEndpointConfig(config);
131 connections.push_back(Connection{
132 CreatePosixEndpoint(
133 handle,
134 PosixEngineClosure::TestOnlyToClosure(
135 [&poller](absl::Status /*status*/) {
136 if (--g_num_active_connections == 0) {
137 poller.Kick();
138 }
139 }),
140 posix_ee,
141 options.resource_quota->memory_quota()->CreateMemoryAllocator(
142 "test"),
143 options),
144 std::move(server_endpoint)});
145 delete server_signal;
146 server_signal = new grpc_core::Notification();
147 }
148 delete server_signal;
149 return connections;
150 }
151
152 } // namespace
153
154 std::string TestScenarioName(const ::testing::TestParamInfo<bool>& info) {
155 return absl::StrCat("is_zero_copy_enabled_", info.param);
156 }
157
158 // A helper class to drive the polling of Fds. It repeatedly calls the Work(..)
159 // method on the poller to get pet pending events, then schedules another
160 // parallel Work(..) instantiation and processes these pending events. This
161 // continues until all Fds have orphaned themselves.
162 class Worker : public grpc_core::DualRefCounted<Worker> {
163 public:
164 Worker(std::shared_ptr<EventEngine> engine, PosixEventPoller* poller)
165 : engine_(std::move(engine)), poller_(poller) {
166 WeakRef().release();
167 }
168 void Orphan() override { signal.Notify(); }
169 void Start() {
170 // Start executing Work(..).
171 engine_->Run([this]() { Work(); });
172 }
173
174 void Wait() {
175 signal.WaitForNotification();
176 WeakUnref();
177 }
178
179 private:
180 void Work() {
181 auto result = poller_->Work(24h, [this]() {
182 // Schedule next work instantiation immediately and take a Ref for
183 // the next instantiation.
184 Ref().release();
185 engine_->Run([this]() { Work(); });
186 });
187 ASSERT_TRUE(result == Poller::WorkResult::kOk ||
188 result == Poller::WorkResult::kKicked);
189 // Corresponds to the Ref taken for the current instantiation. If the
190 // result was Poller::WorkResult::kKicked, then the next work instantiation
191 // would not have been scheduled and the poll_again callback would have
192 // been deleted.
193 Unref();
194 }
195 std::shared_ptr<EventEngine> engine_;
196 // The poller is not owned by the Worker. Rather it is owned by the test
197 // which creates the worker instance.
198 PosixEventPoller* poller_;
199 grpc_core::Notification signal;
200 };
201
202 class PosixEndpointTest : public ::testing::TestWithParam<bool> {
203 void SetUp() override {
204 oracle_ee_ = std::make_shared<PosixOracleEventEngine>();
205 scheduler_ =
206 std::make_unique<grpc_event_engine::posix_engine::TestScheduler>(
207 posix_ee_.get());
208 EXPECT_NE(scheduler_, nullptr);
209 poller_ = MakeDefaultPoller(scheduler_.get());
210 posix_ee_ = PosixEventEngine::MakeTestOnlyPosixEventEngine(poller_);
211 EXPECT_NE(posix_ee_, nullptr);
212 scheduler_->ChangeCurrentEventEngine(posix_ee_.get());
213 if (poller_ != nullptr) {
214 gpr_log(GPR_INFO, "Using poller: %s", poller_->Name().c_str());
215 }
216 }
217
218 void TearDown() override {
219 if (poller_ != nullptr) {
220 poller_->Shutdown();
221 }
222 WaitForSingleOwner(std::move(posix_ee_));
223 WaitForSingleOwner(std::move(oracle_ee_));
224 }
225
226 public:
227 TestScheduler* Scheduler() { return scheduler_.get(); }
228
229 std::shared_ptr<EventEngine> GetPosixEE() { return posix_ee_; }
230
231 std::shared_ptr<EventEngine> GetOracleEE() { return oracle_ee_; }
232
233 PosixEventPoller* PosixPoller() { return poller_; }
234
235 private:
236 PosixEventPoller* poller_;
237 std::unique_ptr<TestScheduler> scheduler_;
238 std::shared_ptr<EventEngine> posix_ee_;
239 std::shared_ptr<EventEngine> oracle_ee_;
240 };
241
242 TEST_P(PosixEndpointTest, ConnectExchangeBidiDataTransferTest) {
243 if (PosixPoller() == nullptr) {
244 return;
245 }
246 Worker* worker = new Worker(GetPosixEE(), PosixPoller());
247 worker->Start();
248 {
249 auto connections = CreateConnectedEndpoints(*PosixPoller(), GetParam(), 1,
250 GetPosixEE(), GetOracleEE());
251 auto it = connections.begin();
252 auto client_endpoint = std::move((*it).client_endpoint);
253 auto server_endpoint = std::move((*it).server_endpoint);
254 EXPECT_NE(client_endpoint, nullptr);
255 EXPECT_NE(server_endpoint, nullptr);
256 connections.erase(it);
257
258 // Alternate message exchanges between client -- server and server --
259 // client.
260 for (int i = 0; i < kNumExchangedMessages; i++) {
261 // Send from client to server and verify data read at the server.
262 ASSERT_TRUE(SendValidatePayload(GetNextSendMessage(),
263 client_endpoint.get(),
264 server_endpoint.get())
265 .ok());
266 // Send from server to client and verify data read at the client.
267 ASSERT_TRUE(SendValidatePayload(GetNextSendMessage(),
268 server_endpoint.get(),
269 client_endpoint.get())
270 .ok());
271 }
272 }
273 worker->Wait();
274 }
275
276 // Create N connections and exchange and verify random number of messages over
277 // each connection in parallel.
278 TEST_P(PosixEndpointTest, MultipleIPv6ConnectionsToOneOracleListenerTest) {
279 if (PosixPoller() == nullptr) {
280 return;
281 }
282 Worker* worker = new Worker(GetPosixEE(), PosixPoller());
283 worker->Start();
284 auto connections = CreateConnectedEndpoints(
285 *PosixPoller(), GetParam(), kNumConnections, GetPosixEE(), GetOracleEE());
286 std::vector<std::thread> threads;
287 // Create one thread for each connection. For each connection, create
288 // 2 more worker threads: to exchange and verify bi-directional data transfer.
289 threads.reserve(kNumConnections);
290 for (int i = 0; i < kNumConnections; i++) {
291 // For each connection, simulate a parallel bi-directional data transfer.
292 // All bi-directional transfers are run in parallel across all connections.
293 auto it = connections.begin();
294 auto client_endpoint = std::move((*it).client_endpoint);
295 auto server_endpoint = std::move((*it).server_endpoint);
296 EXPECT_NE(client_endpoint, nullptr);
297 EXPECT_NE(server_endpoint, nullptr);
298 connections.erase(it);
299 threads.emplace_back([client_endpoint = std::move(client_endpoint),
300 server_endpoint = std::move(server_endpoint)]() {
301 std::vector<std::thread> workers;
302 workers.reserve(2);
303 auto worker = [client_endpoint = client_endpoint.get(),
304 server_endpoint =
305 server_endpoint.get()](bool client_to_server) {
306 for (int i = 0; i < kNumExchangedMessages; i++) {
307 // If client_to_server is true, send from client to server and
308 // verify data read at the server. Otherwise send data from server
309 // to client and verify data read at client.
310 if (client_to_server) {
311 EXPECT_TRUE(SendValidatePayload(GetNextSendMessage(),
312 client_endpoint, server_endpoint)
313 .ok());
314 } else {
315 EXPECT_TRUE(SendValidatePayload(GetNextSendMessage(),
316 server_endpoint, client_endpoint)
317 .ok());
318 }
319 }
320 };
321 // worker[0] simulates a flow from client to server endpoint
322 workers.emplace_back([&worker]() { worker(true); });
323 // worker[1] simulates a flow from server to client endpoint
324 workers.emplace_back([&worker]() { worker(false); });
325 workers[0].join();
326 workers[1].join();
327 });
328 }
329 for (auto& t : threads) {
330 t.join();
331 }
332 worker->Wait();
333 }
334
335 // Test with zero copy enabled and disabled.
336 INSTANTIATE_TEST_SUITE_P(PosixEndpoint, PosixEndpointTest,
337 ::testing::ValuesIn({false, true}), &TestScenarioName);
338
339 } // namespace posix_engine
340 } // namespace grpc_event_engine
341
342 int main(int argc, char** argv) {
343 ::testing::InitGoogleTest(&argc, argv);
344 grpc_core::UniquePtr<char> poll_strategy =
345 GPR_GLOBAL_CONFIG_GET(grpc_poll_strategy);
346 GPR_GLOBAL_CONFIG_GET(grpc_poll_strategy);
347 auto strings = absl::StrSplit(poll_strategy.get(), ',');
348 if (std::find(strings.begin(), strings.end(), "none") != strings.end()) {
349 // Skip the test entirely if poll strategy is none.
350 return 0;
351 }
352 // TODO(ctiller): EventEngine temporarily needs grpc to be initialized first
353 // until we clear out the iomgr shutdown code.
354 grpc_init();
355 int r = RUN_ALL_TESTS();
356 grpc_shutdown();
357 return r;
358 }