Debian Codegraph @

test/core/iomgr/fd_posix_test.cc

raw
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
19 #include <gtest/gtest.h>
20
21 #include "src/core/lib/iomgr/port.h"
22 #include "test/core/util/test_config.h"
23
24 // This test won't work except with posix sockets enabled
25 #ifdef GRPC_POSIX_SOCKET_EV
26
27 #include <ctype.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <netinet/in.h>
31 #include <poll.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <sys/socket.h>
36 #include <sys/time.h>
37 #include <unistd.h>
38
39 #include <grpc/grpc.h>
40 #include <grpc/support/alloc.h>
41 #include <grpc/support/log.h>
42 #include <grpc/support/sync.h>
43 #include <grpc/support/time.h>
44
45 #include "src/core/lib/gprpp/strerror.h"
46 #include "src/core/lib/iomgr/ev_posix.h"
47 #include "src/core/lib/iomgr/iomgr.h"
48 #include "src/core/lib/iomgr/socket_utils_posix.h"
49
50 static gpr_mu* g_mu;
51 static grpc_pollset* g_pollset;
52
53 /* buffer size used to send and receive data.
54 1024 is the minimal value to set TCP send and receive buffer. */
55 #define BUF_SIZE 1024
56
57 /* Create a test socket with the right properties for testing.
58 port is the TCP port to listen or connect to.
59 Return a socket FD and sockaddr_in. */
60 static void create_test_socket(int port, int* socket_fd,
61 struct sockaddr_in* sin) {
62 int fd;
63 int one = 1;
64 int buffer_size_bytes = BUF_SIZE;
65 int flags;
66
67 fd = socket(AF_INET, SOCK_STREAM, 0);
68 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
69 /* Reset the size of socket send buffer to the minimal value to facilitate
70 buffer filling up and triggering notify_on_write */
71 ASSERT_EQ(grpc_set_socket_sndbuf(fd, buffer_size_bytes), absl::OkStatus());
72 ASSERT_EQ(grpc_set_socket_rcvbuf(fd, buffer_size_bytes), absl::OkStatus());
73 /* Make fd non-blocking */
74 flags = fcntl(fd, F_GETFL, 0);
75 ASSERT_EQ(fcntl(fd, F_SETFL, flags | O_NONBLOCK), 0);
76 *socket_fd = fd;
77
78 /* Use local address for test */
79 sin->sin_family = AF_INET;
80 sin->sin_addr.s_addr = htonl(0x7f000001);
81 ASSERT_GE(port, 0);
82 ASSERT_LT(port, 65536);
83 sin->sin_port = htons(static_cast<uint16_t>(port));
84 }
85
86 /* Phony gRPC callback */
87 void no_op_cb(void* /*arg*/, int /*success*/) {}
88
89 /* =======An upload server to test notify_on_read===========
90 The server simply reads and counts a stream of bytes. */
91
92 /* An upload server. */
93 typedef struct {
94 grpc_fd* em_fd; /* listening fd */
95 ssize_t read_bytes_total; /* total number of received bytes */
96 int done; /* set to 1 when a server finishes serving */
97 grpc_closure listen_closure;
98 } server;
99
100 static void server_init(server* sv) {
101 sv->read_bytes_total = 0;
102 sv->done = 0;
103 }
104
105 /* An upload session.
106 Created when a new upload request arrives in the server. */
107 typedef struct {
108 server* sv; /* not owned by a single session */
109 grpc_fd* em_fd; /* fd to read upload bytes */
110 char read_buf[BUF_SIZE]; /* buffer to store upload bytes */
111 grpc_closure session_read_closure;
112 } session;
113
114 /* Called when an upload session can be safely shutdown.
115 Close session FD and start to shutdown listen FD. */
116 static void session_shutdown_cb(void* arg, /*session */
117 bool /*success*/) {
118 session* se = static_cast<session*>(arg);
119 server* sv = se->sv;
120 grpc_fd_orphan(se->em_fd, nullptr, nullptr, "a");
121 gpr_free(se);
122 /* Start to shutdown listen fd. */
123 grpc_fd_shutdown(sv->em_fd, GRPC_ERROR_CREATE("session_shutdown_cb"));
124 }
125
126 /* Called when data become readable in a session. */
127 static void session_read_cb(void* arg, /*session */
128 grpc_error_handle error) {
129 session* se = static_cast<session*>(arg);
130 int fd = grpc_fd_wrapped_fd(se->em_fd);
131
132 ssize_t read_once = 0;
133 ssize_t read_total = 0;
134
135 if (!error.ok()) {
136 session_shutdown_cb(arg, true);
137 return;
138 }
139
140 do {
141 read_once = read(fd, se->read_buf, BUF_SIZE);
142 if (read_once > 0) read_total += read_once;
143 } while (read_once > 0);
144 se->sv->read_bytes_total += read_total;
145
146 /* read() returns 0 to indicate the TCP connection was closed by the client.
147 read(fd, read_buf, 0) also returns 0 which should never be called as such.
148 It is possible to read nothing due to spurious edge event or data has
149 been drained, In such a case, read() returns -1 and set errno to EAGAIN. */
150 if (read_once == 0) {
151 session_shutdown_cb(arg, true);
152 } else if (read_once == -1) {
153 if (errno == EAGAIN) {
154 /* An edge triggered event is cached in the kernel until next poll.
155 In the current single thread implementation, session_read_cb is called
156 in the polling thread, such that polling only happens after this
157 callback, and will catch read edge event if data is available again
158 before notify_on_read.
159 TODO(chenw): in multi-threaded version, callback and polling can be
160 run in different threads. polling may catch a persist read edge event
161 before notify_on_read is called. */
162 grpc_fd_notify_on_read(se->em_fd, &se->session_read_closure);
163 } else {
164 gpr_log(GPR_ERROR, "Unhandled read error %s",
165 grpc_core::StrError(errno).c_str());
166 abort();
167 }
168 }
169 }
170
171 /* Called when the listen FD can be safely shutdown.
172 Close listen FD and signal that server can be shutdown. */
173 static void listen_shutdown_cb(void* arg /*server*/, int /*success*/) {
174 server* sv = static_cast<server*>(arg);
175
176 grpc_fd_orphan(sv->em_fd, nullptr, nullptr, "b");
177
178 gpr_mu_lock(g_mu);
179 sv->done = 1;
180 ASSERT_TRUE(
181 GRPC_LOG_IF_ERROR("pollset_kick", grpc_pollset_kick(g_pollset, nullptr)));
182 gpr_mu_unlock(g_mu);
183 }
184
185 /* Called when a new TCP connection request arrives in the listening port. */
186 static void listen_cb(void* arg, /*=sv_arg*/
187 grpc_error_handle error) {
188 server* sv = static_cast<server*>(arg);
189 int fd;
190 int flags;
191 session* se;
192 struct sockaddr_storage ss;
193 socklen_t slen = sizeof(ss);
194 grpc_fd* listen_em_fd = sv->em_fd;
195
196 if (!error.ok()) {
197 listen_shutdown_cb(arg, 1);
198 return;
199 }
200
201 fd = accept(grpc_fd_wrapped_fd(listen_em_fd),
202 reinterpret_cast<struct sockaddr*>(&ss), &slen);
203 ASSERT_GE(fd, 0);
204 ASSERT_LT(fd, FD_SETSIZE);
205 flags = fcntl(fd, F_GETFL, 0);
206 fcntl(fd, F_SETFL, flags | O_NONBLOCK);
207 se = static_cast<session*>(gpr_malloc(sizeof(*se)));
208 se->sv = sv;
209 se->em_fd = grpc_fd_create(fd, "listener", false);
210 grpc_pollset_add_fd(g_pollset, se->em_fd);
211 GRPC_CLOSURE_INIT(&se->session_read_closure, session_read_cb, se,
212 grpc_schedule_on_exec_ctx);
213 grpc_fd_notify_on_read(se->em_fd, &se->session_read_closure);
214
215 grpc_fd_notify_on_read(listen_em_fd, &sv->listen_closure);
216 }
217
218 /* Max number of connections pending to be accepted by listen(). */
219 #define MAX_NUM_FD 1024
220
221 /* Start a test server, return the TCP listening port bound to listen_fd.
222 listen_cb() is registered to be interested in reading from listen_fd.
223 When connection request arrives, listen_cb() is called to accept the
224 connection request. */
225 static int server_start(server* sv) {
226 int port = 0;
227 int fd;
228 struct sockaddr_in sin;
229 socklen_t addr_len;
230
231 create_test_socket(port, &fd, &sin);
232 addr_len = sizeof(sin);
233 EXPECT_EQ(bind(fd, (struct sockaddr*)&sin, addr_len), 0);
234 EXPECT_EQ(getsockname(fd, (struct sockaddr*)&sin, &addr_len), 0);
235 port = ntohs(sin.sin_port);
236 EXPECT_EQ(listen(fd, MAX_NUM_FD), 0);
237
238 sv->em_fd = grpc_fd_create(fd, "server", false);
239 grpc_pollset_add_fd(g_pollset, sv->em_fd);
240 /* Register to be interested in reading from listen_fd. */
241 GRPC_CLOSURE_INIT(&sv->listen_closure, listen_cb, sv,
242 grpc_schedule_on_exec_ctx);
243 grpc_fd_notify_on_read(sv->em_fd, &sv->listen_closure);
244
245 return port;
246 }
247
248 /* Wait and shutdown a sever. */
249 static void server_wait_and_shutdown(server* sv) {
250 gpr_mu_lock(g_mu);
251 while (!sv->done) {
252 grpc_core::ExecCtx exec_ctx;
253 grpc_pollset_worker* worker = nullptr;
254 ASSERT_TRUE(GRPC_LOG_IF_ERROR(
255 "pollset_work", grpc_pollset_work(g_pollset, &worker,
256 grpc_core::Timestamp::InfFuture())));
257 gpr_mu_unlock(g_mu);
258
259 gpr_mu_lock(g_mu);
260 }
261 gpr_mu_unlock(g_mu);
262 }
263
264 /* ===An upload client to test notify_on_write=== */
265
266 /* Client write buffer size */
267 #define CLIENT_WRITE_BUF_SIZE 10
268 /* Total number of times that the client fills up the write buffer */
269 #define CLIENT_TOTAL_WRITE_CNT 3
270
271 /* An upload client. */
272 typedef struct {
273 grpc_fd* em_fd;
274 char write_buf[CLIENT_WRITE_BUF_SIZE];
275 ssize_t write_bytes_total;
276 /* Number of times that the client fills up the write buffer and calls
277 notify_on_write to schedule another write. */
278 int client_write_cnt;
279
280 int done; /* set to 1 when a client finishes sending */
281 grpc_closure write_closure;
282 } client;
283
284 static void client_init(client* cl) {
285 memset(cl->write_buf, 0, sizeof(cl->write_buf));
286 cl->write_bytes_total = 0;
287 cl->client_write_cnt = 0;
288 cl->done = 0;
289 }
290
291 /* Called when a client upload session is ready to shutdown. */
292 static void client_session_shutdown_cb(void* arg /*client*/, int /*success*/) {
293 client* cl = static_cast<client*>(arg);
294 grpc_fd_orphan(cl->em_fd, nullptr, nullptr, "c");
295 cl->done = 1;
296 ASSERT_TRUE(
297 GRPC_LOG_IF_ERROR("pollset_kick", grpc_pollset_kick(g_pollset, nullptr)));
298 }
299
300 /* Write as much as possible, then register notify_on_write. */
301 static void client_session_write(void* arg, /*client */
302 grpc_error_handle error) {
303 client* cl = static_cast<client*>(arg);
304 int fd = grpc_fd_wrapped_fd(cl->em_fd);
305 ssize_t write_once = 0;
306
307 if (!error.ok()) {
308 gpr_mu_lock(g_mu);
309 client_session_shutdown_cb(arg, 1);
310 gpr_mu_unlock(g_mu);
311 return;
312 }
313
314 do {
315 write_once = write(fd, cl->write_buf, CLIENT_WRITE_BUF_SIZE);
316 if (write_once > 0) cl->write_bytes_total += write_once;
317 } while (write_once > 0);
318
319 if (errno == EAGAIN) {
320 gpr_mu_lock(g_mu);
321 if (cl->client_write_cnt < CLIENT_TOTAL_WRITE_CNT) {
322 GRPC_CLOSURE_INIT(&cl->write_closure, client_session_write, cl,
323 grpc_schedule_on_exec_ctx);
324 grpc_fd_notify_on_write(cl->em_fd, &cl->write_closure);
325 cl->client_write_cnt++;
326 } else {
327 client_session_shutdown_cb(arg, 1);
328 }
329 gpr_mu_unlock(g_mu);
330 } else {
331 gpr_log(GPR_ERROR, "unknown errno %s", grpc_core::StrError(errno).c_str());
332 abort();
333 }
334 }
335
336 /* Start a client to send a stream of bytes. */
337 static void client_start(client* cl, int port) {
338 int fd;
339 struct sockaddr_in sin;
340 create_test_socket(port, &fd, &sin);
341 if (connect(fd, reinterpret_cast<struct sockaddr*>(&sin), sizeof(sin)) ==
342 -1) {
343 if (errno == EINPROGRESS) {
344 struct pollfd pfd;
345 pfd.fd = fd;
346 pfd.events = POLLOUT;
347 pfd.revents = 0;
348 if (poll(&pfd, 1, -1) == -1) {
349 gpr_log(GPR_ERROR, "poll() failed during connect; errno=%d", errno);
350 abort();
351 }
352 } else {
353 gpr_log(GPR_ERROR, "Failed to connect to the server (errno=%d)", errno);
354 abort();
355 }
356 }
357
358 cl->em_fd = grpc_fd_create(fd, "client", false);
359 grpc_pollset_add_fd(g_pollset, cl->em_fd);
360
361 client_session_write(cl, absl::OkStatus());
362 }
363
364 /* Wait for the signal to shutdown a client. */
365 static void client_wait_and_shutdown(client* cl) {
366 gpr_mu_lock(g_mu);
367 while (!cl->done) {
368 grpc_pollset_worker* worker = nullptr;
369 grpc_core::ExecCtx exec_ctx;
370 ASSERT_TRUE(GRPC_LOG_IF_ERROR(
371 "pollset_work", grpc_pollset_work(g_pollset, &worker,
372 grpc_core::Timestamp::InfFuture())));
373 gpr_mu_unlock(g_mu);
374
375 gpr_mu_lock(g_mu);
376 }
377 gpr_mu_unlock(g_mu);
378 }
379
380 /* Test grpc_fd. Start an upload server and client, upload a stream of
381 bytes from the client to the server, and verify that the total number of
382 sent bytes is equal to the total number of received bytes. */
383 static void test_grpc_fd(void) {
384 server sv;
385 client cl;
386 int port;
387 grpc_core::ExecCtx exec_ctx;
388
389 server_init(&sv);
390 port = server_start(&sv);
391 client_init(&cl);
392 client_start(&cl, port);
393
394 client_wait_and_shutdown(&cl);
395 server_wait_and_shutdown(&sv);
396 ASSERT_EQ(sv.read_bytes_total, cl.write_bytes_total);
397 gpr_log(GPR_INFO, "Total read bytes %" PRIdPTR, sv.read_bytes_total);
398 }
399
400 typedef struct fd_change_data {
401 grpc_iomgr_cb_func cb_that_ran;
402 } fd_change_data;
403
404 void init_change_data(fd_change_data* fdc) { fdc->cb_that_ran = nullptr; }
405
406 void destroy_change_data(fd_change_data* /*fdc*/) {}
407
408 static void first_read_callback(void* arg /* fd_change_data */,
409 grpc_error_handle /*error*/) {
410 fd_change_data* fdc = static_cast<fd_change_data*>(arg);
411
412 gpr_mu_lock(g_mu);
413 fdc->cb_that_ran = first_read_callback;
414 ASSERT_TRUE(
415 GRPC_LOG_IF_ERROR("pollset_kick", grpc_pollset_kick(g_pollset, nullptr)));
416 gpr_mu_unlock(g_mu);
417 }
418
419 static void second_read_callback(void* arg /* fd_change_data */,
420 grpc_error_handle /*error*/) {
421 fd_change_data* fdc = static_cast<fd_change_data*>(arg);
422
423 gpr_mu_lock(g_mu);
424 fdc->cb_that_ran = second_read_callback;
425 ASSERT_TRUE(
426 GRPC_LOG_IF_ERROR("pollset_kick", grpc_pollset_kick(g_pollset, nullptr)));
427 gpr_mu_unlock(g_mu);
428 }
429
430 /* Test that changing the callback we use for notify_on_read actually works.
431 Note that we have two different but almost identical callbacks above -- the
432 point is to have two different function pointers and two different data
433 pointers and make sure that changing both really works. */
434 static void test_grpc_fd_change(void) {
435 grpc_fd* em_fd;
436 fd_change_data a, b;
437 int flags;
438 int sv[2];
439 char data;
440 ssize_t result;
441 grpc_closure first_closure;
442 grpc_closure second_closure;
443 grpc_core::ExecCtx exec_ctx;
444
445 GRPC_CLOSURE_INIT(&first_closure, first_read_callback, &a,
446 grpc_schedule_on_exec_ctx);
447 GRPC_CLOSURE_INIT(&second_closure, second_read_callback, &b,
448 grpc_schedule_on_exec_ctx);
449
450 init_change_data(&a);
451 init_change_data(&b);
452
453 ASSERT_EQ(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0);
454 flags = fcntl(sv[0], F_GETFL, 0);
455 ASSERT_EQ(fcntl(sv[0], F_SETFL, flags | O_NONBLOCK), 0);
456 flags = fcntl(sv[1], F_GETFL, 0);
457 ASSERT_EQ(fcntl(sv[1], F_SETFL, flags | O_NONBLOCK), 0);
458
459 em_fd = grpc_fd_create(sv[0], "test_grpc_fd_change", false);
460 grpc_pollset_add_fd(g_pollset, em_fd);
461
462 /* Register the first callback, then make its FD readable */
463 grpc_fd_notify_on_read(em_fd, &first_closure);
464 data = 0;
465 result = write(sv[1], &data, 1);
466 ASSERT_EQ(result, 1);
467
468 /* And now wait for it to run. */
469 gpr_mu_lock(g_mu);
470 while (a.cb_that_ran == nullptr) {
471 grpc_pollset_worker* worker = nullptr;
472 ASSERT_TRUE(GRPC_LOG_IF_ERROR(
473 "pollset_work", grpc_pollset_work(g_pollset, &worker,
474 grpc_core::Timestamp::InfFuture())));
475 gpr_mu_unlock(g_mu);
476
477 gpr_mu_lock(g_mu);
478 }
479 ASSERT_EQ(a.cb_that_ran, first_read_callback);
480 gpr_mu_unlock(g_mu);
481
482 /* And drain the socket so we can generate a new read edge */
483 result = read(sv[0], &data, 1);
484 ASSERT_EQ(result, 1);
485
486 /* Now register a second callback with distinct change data, and do the same
487 thing again. */
488 grpc_fd_notify_on_read(em_fd, &second_closure);
489 data = 0;
490 result = write(sv[1], &data, 1);
491 ASSERT_EQ(result, 1);
492
493 gpr_mu_lock(g_mu);
494 while (b.cb_that_ran == nullptr) {
495 grpc_pollset_worker* worker = nullptr;
496 ASSERT_TRUE(GRPC_LOG_IF_ERROR(
497 "pollset_work", grpc_pollset_work(g_pollset, &worker,
498 grpc_core::Timestamp::InfFuture())));
499 gpr_mu_unlock(g_mu);
500
501 gpr_mu_lock(g_mu);
502 }
503 /* Except now we verify that second_read_callback ran instead */
504 ASSERT_EQ(b.cb_that_ran, second_read_callback);
505 gpr_mu_unlock(g_mu);
506
507 grpc_fd_orphan(em_fd, nullptr, nullptr, "d");
508
509 destroy_change_data(&a);
510 destroy_change_data(&b);
511 close(sv[1]);
512 }
513
514 static void destroy_pollset(void* p, grpc_error_handle /*error*/) {
515 grpc_pollset_destroy(static_cast<grpc_pollset*>(p));
516 }
517
518 TEST(FdPosixTest, MainTest) {
519 grpc_closure destroyed;
520 grpc_init();
521 {
522 grpc_core::ExecCtx exec_ctx;
523 g_pollset = static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size()));
524 grpc_pollset_init(g_pollset, &g_mu);
525 test_grpc_fd();
526 test_grpc_fd_change();
527 GRPC_CLOSURE_INIT(&destroyed, destroy_pollset, g_pollset,
528 grpc_schedule_on_exec_ctx);
529 grpc_pollset_shutdown(g_pollset, &destroyed);
530 grpc_core::ExecCtx::Get()->Flush();
531 gpr_free(g_pollset);
532 }
533 grpc_shutdown();
534 }
535
536 #endif /* GRPC_POSIX_SOCKET_EV */
537
538 int main(int argc, char** argv) {
539 grpc::testing::TestEnvironment env(&argc, argv);
540 ::testing::InitGoogleTest(&argc, argv);
541 return RUN_ALL_TESTS();
542 }