Debian Codegraph @

test/core/event_engine/windows/iocp_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 #include <grpc/support/port_platform.h>
15
16 #ifdef GPR_WINDOWS
17 #include <thread>
18
19 #include <gmock/gmock.h>
20 #include <gtest/gtest.h>
21
22 #include "absl/status/status.h"
23 #include "absl/time/time.h"
24 #include "absl/types/variant.h"
25
26 #include <grpc/grpc.h>
27 #include <grpc/support/log_windows.h>
28
29 #include "src/core/lib/event_engine/common_closures.h"
30 #include "src/core/lib/event_engine/poller.h"
31 #include "src/core/lib/event_engine/thread_pool.h"
32 #include "src/core/lib/event_engine/windows/iocp.h"
33 #include "src/core/lib/event_engine/windows/win_socket.h"
34 #include "src/core/lib/gprpp/notification.h"
35 #include "src/core/lib/iomgr/error.h"
36 #include "test/core/event_engine/windows/create_sockpair.h"
37
38 namespace {
39 using ::grpc_event_engine::experimental::AnyInvocableClosure;
40 using ::grpc_event_engine::experimental::CreateSockpair;
41 using ::grpc_event_engine::experimental::EventEngine;
42 using ::grpc_event_engine::experimental::IOCP;
43 using ::grpc_event_engine::experimental::Poller;
44 using ::grpc_event_engine::experimental::SelfDeletingClosure;
45 using ::grpc_event_engine::experimental::ThreadPool;
46 using ::grpc_event_engine::experimental::WinSocket;
47 } // namespace
48
49 class IOCPTest : public testing::Test {};
50
51 TEST_F(IOCPTest, ClientReceivesNotificationOfServerSend) {
52 ThreadPool executor;
53 IOCP iocp(&executor);
54 SOCKET sockpair[2];
55 CreateSockpair(sockpair, iocp.GetDefaultSocketFlags());
56 WinSocket* wrapped_client_socket =
57 static_cast<WinSocket*>(iocp.Watch(sockpair[0]));
58 WinSocket* wrapped_server_socket =
59 static_cast<WinSocket*>(iocp.Watch(sockpair[1]));
60 grpc_core::Notification read_called;
61 grpc_core::Notification write_called;
62 DWORD flags = 0;
63 AnyInvocableClosure* on_read;
64 AnyInvocableClosure* on_write;
65 {
66 // When the client gets some data, ensure it matches what we expect.
67 WSABUF read_wsabuf;
68 read_wsabuf.len = 2048;
69 char read_char_buffer[2048];
70 read_wsabuf.buf = read_char_buffer;
71 DWORD bytes_rcvd;
72 memset(wrapped_client_socket->read_info()->overlapped(), 0,
73 sizeof(OVERLAPPED));
74 int status =
75 WSARecv(wrapped_client_socket->socket(), &read_wsabuf, 1, &bytes_rcvd,
76 &flags, wrapped_client_socket->read_info()->overlapped(), NULL);
77 // Expecting error 997, WSA_IO_PENDING
78 EXPECT_EQ(status, -1);
79 int last_error = WSAGetLastError();
80 ASSERT_EQ(last_error, WSA_IO_PENDING);
81 on_read = new AnyInvocableClosure([wrapped_client_socket, &read_called,
82 &read_wsabuf, &bytes_rcvd]() {
83 gpr_log(GPR_DEBUG, "Notified on read");
84 EXPECT_GE(wrapped_client_socket->read_info()->bytes_transferred(), 10);
85 EXPECT_STREQ(read_wsabuf.buf, "hello!");
86 read_called.Notify();
87 });
88 wrapped_client_socket->NotifyOnRead(on_read);
89 }
90 {
91 // Have the server send a message to the client
92 WSABUF write_wsabuf;
93 char write_char_buffer[2048] = "hello!";
94 write_wsabuf.len = 2048;
95 write_wsabuf.buf = write_char_buffer;
96 DWORD bytes_sent;
97 memset(wrapped_server_socket->write_info()->overlapped(), 0,
98 sizeof(OVERLAPPED));
99 int status =
100 WSASend(wrapped_server_socket->socket(), &write_wsabuf, 1, &bytes_sent,
101 0, wrapped_server_socket->write_info()->overlapped(), NULL);
102 EXPECT_EQ(status, 0);
103 if (status != 0) {
104 int error_num = WSAGetLastError();
105 char* utf8_message = gpr_format_message(error_num);
106 gpr_log(GPR_INFO, "Error sending data: (%d) %s", error_num, utf8_message);
107 gpr_free(utf8_message);
108 }
109 on_write = new AnyInvocableClosure([&write_called] {
110 gpr_log(GPR_DEBUG, "Notified on write");
111 write_called.Notify();
112 });
113 wrapped_server_socket->NotifyOnWrite(on_write);
114 }
115 // Doing work for WSASend
116 bool cb_invoked = false;
117 auto work_result = iocp.Work(std::chrono::seconds(10),
118 [&cb_invoked]() { cb_invoked = true; });
119 ASSERT_TRUE(work_result == Poller::WorkResult::kOk);
120 ASSERT_TRUE(cb_invoked);
121 // Doing work for WSARecv
122 cb_invoked = false;
123 work_result = iocp.Work(std::chrono::seconds(10),
124 [&cb_invoked]() { cb_invoked = true; });
125 ASSERT_TRUE(work_result == Poller::WorkResult::kOk);
126 ASSERT_TRUE(cb_invoked);
127 // wait for the callbacks to run
128 read_called.WaitForNotification();
129 write_called.WaitForNotification();
130
131 delete on_read;
132 delete on_write;
133 wrapped_client_socket->MaybeShutdown(absl::OkStatus());
134 wrapped_server_socket->MaybeShutdown(absl::OkStatus());
135 delete wrapped_client_socket;
136 delete wrapped_server_socket;
137 executor.Quiesce();
138 }
139
140 TEST_F(IOCPTest, IocpWorkTimeoutDueToNoNotificationRegistered) {
141 ThreadPool executor;
142 IOCP iocp(&executor);
143 SOCKET sockpair[2];
144 CreateSockpair(sockpair, iocp.GetDefaultSocketFlags());
145 WinSocket* wrapped_client_socket =
146 static_cast<WinSocket*>(iocp.Watch(sockpair[0]));
147 grpc_core::Notification read_called;
148 DWORD flags = 0;
149 AnyInvocableClosure* on_read;
150 {
151 // Set the client to receive asynchronously
152 // Prepare a notification callback, but don't register it yet.
153 WSABUF read_wsabuf;
154 read_wsabuf.len = 2048;
155 char read_char_buffer[2048];
156 read_wsabuf.buf = read_char_buffer;
157 DWORD bytes_rcvd;
158 memset(wrapped_client_socket->read_info()->overlapped(), 0,
159 sizeof(OVERLAPPED));
160 int status =
161 WSARecv(wrapped_client_socket->socket(), &read_wsabuf, 1, &bytes_rcvd,
162 &flags, wrapped_client_socket->read_info()->overlapped(), NULL);
163 // Expecting error 997, WSA_IO_PENDING
164 EXPECT_EQ(status, -1);
165 int last_error = WSAGetLastError();
166 ASSERT_EQ(last_error, WSA_IO_PENDING);
167 on_read = new AnyInvocableClosure([wrapped_client_socket, &read_called,
168 &read_wsabuf, &bytes_rcvd]() {
169 gpr_log(GPR_DEBUG, "Notified on read");
170 EXPECT_GE(wrapped_client_socket->read_info()->bytes_transferred(), 10);
171 EXPECT_STREQ(read_wsabuf.buf, "hello!");
172 read_called.Notify();
173 });
174 }
175 {
176 // Have the server send a message to the client. No need to track via IOCP
177 WSABUF write_wsabuf;
178 char write_char_buffer[2048] = "hello!";
179 write_wsabuf.len = 2048;
180 write_wsabuf.buf = write_char_buffer;
181 DWORD bytes_sent;
182 OVERLAPPED write_overlapped;
183 memset(&write_overlapped, 0, sizeof(OVERLAPPED));
184 int status = WSASend(sockpair[1], &write_wsabuf, 1, &bytes_sent, 0,
185 &write_overlapped, NULL);
186 EXPECT_EQ(status, 0);
187 }
188 // IOCP::Work without any notification callbacks should still return Ok.
189 bool cb_invoked = false;
190 auto work_result = iocp.Work(std::chrono::seconds(2),
191 [&cb_invoked]() { cb_invoked = true; });
192 ASSERT_TRUE(work_result == Poller::WorkResult::kOk);
193 ASSERT_TRUE(cb_invoked);
194 // register the closure, which should trigger it immediately.
195 wrapped_client_socket->NotifyOnRead(on_read);
196 // wait for the callbacks to run
197 read_called.WaitForNotification();
198
199 delete on_read;
200 wrapped_client_socket->MaybeShutdown(absl::OkStatus());
201 delete wrapped_client_socket;
202 executor.Quiesce();
203 }
204
205 TEST_F(IOCPTest, KickWorks) {
206 ThreadPool executor;
207 IOCP iocp(&executor);
208 grpc_core::Notification kicked;
209 executor.Run([&iocp, &kicked] {
210 bool cb_invoked = false;
211 Poller::WorkResult result = iocp.Work(
212 std::chrono::seconds(30), [&cb_invoked]() { cb_invoked = true; });
213 ASSERT_TRUE(result == Poller::WorkResult::kKicked);
214 ASSERT_FALSE(cb_invoked);
215 kicked.Notify();
216 });
217 executor.Run([&iocp] {
218 // give the worker thread a chance to start
219 absl::SleepFor(absl::Milliseconds(42));
220 iocp.Kick();
221 });
222 // wait for the callbacks to run
223 kicked.WaitForNotification();
224 executor.Quiesce();
225 }
226
227 TEST_F(IOCPTest, KickThenShutdownCasusesNextWorkerToBeKicked) {
228 // TODO(hork): evaluate if a kick count is going to be useful.
229 // This documents the existing poller's behavior of maintaining a kick count,
230 // but it's unclear if it's going to be needed.
231 ThreadPool executor;
232 IOCP iocp(&executor);
233 // kick twice
234 iocp.Kick();
235 iocp.Kick();
236 bool cb_invoked = false;
237 // Assert the next two WorkResults are kicks
238 auto result = iocp.Work(std::chrono::milliseconds(1),
239 [&cb_invoked]() { cb_invoked = true; });
240 ASSERT_TRUE(result == Poller::WorkResult::kKicked);
241 ASSERT_FALSE(cb_invoked);
242 result = iocp.Work(std::chrono::milliseconds(1),
243 [&cb_invoked]() { cb_invoked = true; });
244 ASSERT_TRUE(result == Poller::WorkResult::kKicked);
245 ASSERT_FALSE(cb_invoked);
246 // followed by a DeadlineExceeded
247 result = iocp.Work(std::chrono::milliseconds(1),
248 [&cb_invoked]() { cb_invoked = true; });
249 ASSERT_TRUE(result == Poller::WorkResult::kDeadlineExceeded);
250 ASSERT_FALSE(cb_invoked);
251 executor.Quiesce();
252 }
253
254 TEST_F(IOCPTest, CrashOnWatchingAClosedSocket) {
255 ThreadPool executor;
256 IOCP iocp(&executor);
257 SOCKET sockpair[2];
258 CreateSockpair(sockpair, iocp.GetDefaultSocketFlags());
259 closesocket(sockpair[0]);
260 ASSERT_DEATH(
261 {
262 WinSocket* wrapped_client_socket =
263 static_cast<WinSocket*>(iocp.Watch(sockpair[0]));
264 },
265 "");
266 executor.Quiesce();
267 }
268
269 TEST_F(IOCPTest, StressTestThousandsOfSockets) {
270 // Start 10 threads, each with their own IOCP
271 // On each thread, create 50 socket pairs (100 sockets) and have them exchange
272 // a message before shutting down.
273 int thread_count = 10;
274 int sockets_per_thread = 50;
275 std::atomic<int> read_count{0};
276 std::atomic<int> write_count{0};
277 std::vector<std::thread> threads;
278 threads.reserve(thread_count);
279 for (int thread_n = 0; thread_n < thread_count; thread_n++) {
280 threads.emplace_back([thread_n, sockets_per_thread, &read_count,
281 &write_count] {
282 ThreadPool executor;
283 IOCP iocp(&executor);
284 // Start a looping worker thread with a moderate timeout
285 std::thread iocp_worker([&iocp, &executor] {
286 Poller::WorkResult result;
287 do {
288 result = iocp.Work(std::chrono::seconds(1), []() {});
289 } while (result != Poller::WorkResult::kDeadlineExceeded);
290 });
291 for (int i = 0; i < sockets_per_thread; i++) {
292 SOCKET sockpair[2];
293 CreateSockpair(sockpair, iocp.GetDefaultSocketFlags());
294 WinSocket* wrapped_client_socket =
295 static_cast<WinSocket*>(iocp.Watch(sockpair[0]));
296 WinSocket* wrapped_server_socket =
297 static_cast<WinSocket*>(iocp.Watch(sockpair[1]));
298 wrapped_client_socket->NotifyOnRead(
299 SelfDeletingClosure::Create([&read_count, wrapped_client_socket] {
300 read_count.fetch_add(1);
301 wrapped_client_socket->MaybeShutdown(absl::OkStatus());
302 }));
303 wrapped_server_socket->NotifyOnWrite(
304 SelfDeletingClosure::Create([&write_count, wrapped_server_socket] {
305 write_count.fetch_add(1);
306 wrapped_server_socket->MaybeShutdown(absl::OkStatus());
307 }));
308 {
309 // Set the client to receive
310 WSABUF read_wsabuf;
311 read_wsabuf.len = 20;
312 char read_char_buffer[20];
313 read_wsabuf.buf = read_char_buffer;
314 DWORD bytes_rcvd;
315 DWORD flags = 0;
316 memset(wrapped_client_socket->read_info()->overlapped(), 0,
317 sizeof(OVERLAPPED));
318 int status = WSARecv(
319 wrapped_client_socket->socket(), &read_wsabuf, 1, &bytes_rcvd,
320 &flags, wrapped_client_socket->read_info()->overlapped(), NULL);
321 // Expecting error 997, WSA_IO_PENDING
322 EXPECT_EQ(status, -1);
323 int last_error = WSAGetLastError();
324 ASSERT_EQ(last_error, WSA_IO_PENDING);
325 }
326 {
327 // Have the server send a message to the client.
328 WSABUF write_wsabuf;
329 char write_char_buffer[20] = "hello!";
330 write_wsabuf.len = 20;
331 write_wsabuf.buf = write_char_buffer;
332 DWORD bytes_sent;
333 memset(wrapped_server_socket->write_info()->overlapped(), 0,
334 sizeof(OVERLAPPED));
335 int status = WSASend(
336 wrapped_server_socket->socket(), &write_wsabuf, 1, &bytes_sent, 0,
337 wrapped_server_socket->write_info()->overlapped(), NULL);
338 EXPECT_EQ(status, 0);
339 }
340 }
341 iocp_worker.join();
342 executor.Quiesce();
343 });
344 }
345 for (auto& t : threads) {
346 t.join();
347 }
348 absl::Time deadline = absl::Now() + absl::Seconds(30);
349 while (read_count.load() != thread_count * sockets_per_thread ||
350 write_count.load() != thread_count * sockets_per_thread) {
351 absl::SleepFor(absl::Milliseconds(50));
352 if (deadline < absl::Now()) {
353 FAIL() << "Deadline exceeded with " << read_count.load() << " reads and "
354 << write_count.load() << " writes";
355 }
356 }
357 ASSERT_EQ(read_count.load(), thread_count * sockets_per_thread);
358 ASSERT_EQ(write_count.load(), thread_count * sockets_per_thread);
359 }
360
361 int main(int argc, char** argv) {
362 ::testing::InitGoogleTest(&argc, argv);
363 grpc_init();
364 int status = RUN_ALL_TESTS();
365 grpc_shutdown();
366 return status;
367 }
368 #else // not GPR_WINDOWS
369 int main(int /* argc */, char** /* argv */) { return 0; }
370 #endif