| 1 |
// Copyright 2022 The 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 <stdint.h> |
| 16 |
#include <sys/select.h> |
| 17 |
|
| 18 |
#include <algorithm> |
| 19 |
#include <atomic> |
| 20 |
#include <chrono> |
| 21 |
#include <cstring> |
| 22 |
#include <memory> |
| 23 |
#include <string> |
| 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/grpc.h> |
| 33 |
|
| 34 |
#include "src/core/lib/event_engine/poller.h" |
| 35 |
#include "src/core/lib/event_engine/posix_engine/wakeup_fd_pipe.h" |
| 36 |
#include "src/core/lib/event_engine/posix_engine/wakeup_fd_posix.h" |
| 37 |
#include "src/core/lib/gprpp/memory.h" |
| 38 |
#include "src/core/lib/gprpp/ref_counted_ptr.h" |
| 39 |
#include "src/core/lib/iomgr/port.h" |
| 40 |
|
| 41 |
// IWYU pragma: no_include <arpa/inet.h> |
| 42 |
// IWYU pragma: no_include <ratio> |
| 43 |
|
| 44 |
// This test won't work except with posix sockets enabled |
| 45 |
#ifdef GRPC_POSIX_SOCKET_EV |
| 46 |
|
| 47 |
#include <errno.h> |
| 48 |
#include <fcntl.h> |
| 49 |
#include <netinet/in.h> |
| 50 |
#include <poll.h> |
| 51 |
#include <stdlib.h> |
| 52 |
#include <sys/socket.h> |
| 53 |
#include <unistd.h> |
| 54 |
|
| 55 |
#include "absl/status/status.h" |
| 56 |
|
| 57 |
#include <grpc/support/alloc.h> |
| 58 |
#include <grpc/support/log.h> |
| 59 |
#include <grpc/support/sync.h> |
| 60 |
|
| 61 |
#include "src/core/lib/event_engine/common_closures.h" |
| 62 |
#include "src/core/lib/event_engine/posix_engine/event_poller.h" |
| 63 |
#include "src/core/lib/event_engine/posix_engine/event_poller_posix_default.h" |
| 64 |
#include "src/core/lib/event_engine/posix_engine/posix_engine.h" |
| 65 |
#include "src/core/lib/event_engine/posix_engine/posix_engine_closure.h" |
| 66 |
#include "src/core/lib/gprpp/dual_ref_counted.h" |
| 67 |
#include "src/core/lib/gprpp/global_config.h" |
| 68 |
#include "src/core/lib/gprpp/notification.h" |
| 69 |
#include "src/core/lib/gprpp/strerror.h" |
| 70 |
#include "test/core/event_engine/posix/posix_engine_test_utils.h" |
| 71 |
#include "test/core/util/port.h" |
| 72 |
|
| 73 |
GPR_GLOBAL_CONFIG_DECLARE_STRING(grpc_poll_strategy); |
| 74 |
|
| 75 |
using ::grpc_event_engine::experimental::PosixEventEngine; |
| 76 |
using ::grpc_event_engine::posix_engine::PosixEventPoller; |
| 77 |
|
| 78 |
static gpr_mu g_mu; |
| 79 |
static PosixEventPoller* g_event_poller = nullptr; |
| 80 |
|
| 81 |
// buffer size used to send and receive data. |
| 82 |
// 1024 is the minimal value to set TCP send and receive buffer. |
| 83 |
#define BUF_SIZE 1024 |
| 84 |
// Max number of connections pending to be accepted by listen(). |
| 85 |
#define MAX_NUM_FD 1024 |
| 86 |
// Client write buffer size |
| 87 |
#define CLIENT_WRITE_BUF_SIZE 10 |
| 88 |
// Total number of times that the client fills up the write buffer |
| 89 |
#define CLIENT_TOTAL_WRITE_CNT 3 |
| 90 |
|
| 91 |
namespace grpc_event_engine { |
| 92 |
namespace posix_engine { |
| 93 |
|
| 94 |
using ::grpc_event_engine::experimental::Poller; |
| 95 |
using ::grpc_event_engine::experimental::SelfDeletingClosure; |
| 96 |
using ::grpc_event_engine::posix_engine::PosixEventPoller; |
| 97 |
using namespace std::chrono_literals; |
| 98 |
|
| 99 |
namespace { |
| 100 |
|
| 101 |
absl::Status SetSocketSendBuf(int fd, int buffer_size_bytes) { |
| 102 |
return 0 == setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &buffer_size_bytes, |
| 103 |
sizeof(buffer_size_bytes)) |
| 104 |
? absl::OkStatus() |
| 105 |
: absl::Status(absl::StatusCode::kInternal, |
| 106 |
grpc_core::StrError(errno).c_str()); |
| 107 |
} |
| 108 |
|
| 109 |
// Create a test socket with the right properties for testing. |
| 110 |
// port is the TCP port to listen or connect to. |
| 111 |
// Return a socket FD and sockaddr_in. |
| 112 |
void CreateTestSocket(int port, int* socket_fd, struct sockaddr_in6* sin) { |
| 113 |
int fd; |
| 114 |
int one = 1; |
| 115 |
int buffer_size_bytes = BUF_SIZE; |
| 116 |
int flags; |
| 117 |
|
| 118 |
fd = socket(AF_INET6, SOCK_STREAM, 0); |
| 119 |
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); |
| 120 |
// Reset the size of socket send buffer to the minimal value to facilitate |
| 121 |
// buffer filling up and triggering notify_on_write |
| 122 |
EXPECT_TRUE(SetSocketSendBuf(fd, buffer_size_bytes).ok()); |
| 123 |
EXPECT_TRUE(SetSocketSendBuf(fd, buffer_size_bytes).ok()); |
| 124 |
// Make fd non-blocking. |
| 125 |
flags = fcntl(fd, F_GETFL, 0); |
| 126 |
EXPECT_EQ(fcntl(fd, F_SETFL, flags | O_NONBLOCK), 0); |
| 127 |
*socket_fd = fd; |
| 128 |
|
| 129 |
// Use local address for test. |
| 130 |
memset(sin, 0, sizeof(struct sockaddr_in6)); |
| 131 |
sin->sin6_family = AF_INET6; |
| 132 |
(reinterpret_cast<char*>(&sin->sin6_addr))[15] = 1; |
| 133 |
EXPECT_TRUE(port >= 0 && port < 65536); |
| 134 |
sin->sin6_port = htons(static_cast<uint16_t>(port)); |
| 135 |
} |
| 136 |
|
| 137 |
// =======An upload server to test notify_on_read=========== |
| 138 |
// The server simply reads and counts a stream of bytes. |
| 139 |
|
| 140 |
// An upload server. |
| 141 |
typedef struct { |
| 142 |
EventHandle* em_fd; /* listening fd */ |
| 143 |
ssize_t read_bytes_total; /* total number of received bytes */ |
| 144 |
int done; /* set to 1 when a server finishes serving */ |
| 145 |
PosixEngineClosure* listen_closure; |
| 146 |
} server; |
| 147 |
|
| 148 |
void ServerInit(server* sv) { |
| 149 |
sv->read_bytes_total = 0; |
| 150 |
sv->done = 0; |
| 151 |
} |
| 152 |
|
| 153 |
// An upload session. |
| 154 |
// Created when a new upload request arrives in the server. |
| 155 |
typedef struct { |
| 156 |
server* sv; /* not owned by a single session */ |
| 157 |
EventHandle* em_fd; /* fd to read upload bytes */ |
| 158 |
char read_buf[BUF_SIZE]; /* buffer to store upload bytes */ |
| 159 |
PosixEngineClosure* session_read_closure; |
| 160 |
} session; |
| 161 |
|
| 162 |
// Called when an upload session can be safely shutdown. |
| 163 |
// Close session FD and start to shutdown listen FD. |
| 164 |
void SessionShutdownCb(session* se, bool /*success*/) { |
| 165 |
server* sv = se->sv; |
| 166 |
se->em_fd->OrphanHandle(nullptr, nullptr, "a"); |
| 167 |
gpr_free(se); |
| 168 |
// Start to shutdown listen fd. |
| 169 |
sv->em_fd->ShutdownHandle( |
| 170 |
absl::Status(absl::StatusCode::kUnknown, "SessionShutdownCb")); |
| 171 |
} |
| 172 |
|
| 173 |
// Called when data become readable in a session. |
| 174 |
void SessionReadCb(session* se, absl::Status status) { |
| 175 |
int fd = se->em_fd->WrappedFd(); |
| 176 |
|
| 177 |
ssize_t read_once = 0; |
| 178 |
ssize_t read_total = 0; |
| 179 |
|
| 180 |
if (!status.ok()) { |
| 181 |
SessionShutdownCb(se, true); |
| 182 |
return; |
| 183 |
} |
| 184 |
|
| 185 |
do { |
| 186 |
read_once = read(fd, se->read_buf, BUF_SIZE); |
| 187 |
if (read_once > 0) read_total += read_once; |
| 188 |
} while (read_once > 0); |
| 189 |
se->sv->read_bytes_total += read_total; |
| 190 |
|
| 191 |
// read() returns 0 to indicate the TCP connection was closed by the |
| 192 |
// client read(fd, read_buf, 0) also returns 0 which should never be called as |
| 193 |
// such. It is possible to read nothing due to spurious edge event or data has |
| 194 |
// been drained, In such a case, read() returns -1 and set errno to |
| 195 |
// EAGAIN. |
| 196 |
if (read_once == 0) { |
| 197 |
SessionShutdownCb(se, true); |
| 198 |
} else if (read_once == -1) { |
| 199 |
EXPECT_EQ(errno, EAGAIN); |
| 200 |
// An edge triggered event is cached in the kernel until next poll. |
| 201 |
// In the current single thread implementation, SessionReadCb is called |
| 202 |
// in the polling thread, such that polling only happens after this |
| 203 |
// callback, and will catch read edge event if data is available again |
| 204 |
// before notify_on_read. |
| 205 |
se->session_read_closure = PosixEngineClosure::TestOnlyToClosure( |
| 206 |
[se](absl::Status status) { SessionReadCb(se, status); }); |
| 207 |
se->em_fd->NotifyOnRead(se->session_read_closure); |
| 208 |
} |
| 209 |
} |
| 210 |
|
| 211 |
// Called when the listen FD can be safely shutdown. Close listen FD and |
| 212 |
// signal that server can be shutdown. |
| 213 |
void ListenShutdownCb(server* sv) { |
| 214 |
sv->em_fd->OrphanHandle(nullptr, nullptr, "b"); |
| 215 |
gpr_mu_lock(&g_mu); |
| 216 |
sv->done = 1; |
| 217 |
g_event_poller->Kick(); |
| 218 |
gpr_mu_unlock(&g_mu); |
| 219 |
} |
| 220 |
|
| 221 |
// Called when a new TCP connection request arrives in the listening port. |
| 222 |
void ListenCb(server* sv, absl::Status status) { |
| 223 |
int fd; |
| 224 |
int flags; |
| 225 |
session* se; |
| 226 |
struct sockaddr_storage ss; |
| 227 |
socklen_t slen = sizeof(ss); |
| 228 |
EventHandle* listen_em_fd = sv->em_fd; |
| 229 |
|
| 230 |
if (!status.ok()) { |
| 231 |
ListenShutdownCb(sv); |
| 232 |
return; |
| 233 |
} |
| 234 |
|
| 235 |
do { |
| 236 |
fd = accept(listen_em_fd->WrappedFd(), |
| 237 |
reinterpret_cast<struct sockaddr*>(&ss), &slen); |
| 238 |
} while (fd < 0 && errno == EINTR); |
| 239 |
if (fd < 0 && errno == EAGAIN) { |
| 240 |
sv->listen_closure = PosixEngineClosure::TestOnlyToClosure( |
| 241 |
[sv](absl::Status status) { ListenCb(sv, status); }); |
| 242 |
listen_em_fd->NotifyOnRead(sv->listen_closure); |
| 243 |
return; |
| 244 |
} else if (fd < 0) { |
| 245 |
gpr_log(GPR_ERROR, "Failed to acceot a connection, returned error: %s", |
| 246 |
grpc_core::StrError(errno).c_str()); |
| 247 |
} |
| 248 |
EXPECT_GE(fd, 0); |
| 249 |
EXPECT_LT(fd, FD_SETSIZE); |
| 250 |
flags = fcntl(fd, F_GETFL, 0); |
| 251 |
fcntl(fd, F_SETFL, flags | O_NONBLOCK); |
| 252 |
se = static_cast<session*>(gpr_malloc(sizeof(*se))); |
| 253 |
se->sv = sv; |
| 254 |
se->em_fd = g_event_poller->CreateHandle(fd, "listener", false); |
| 255 |
se->session_read_closure = PosixEngineClosure::TestOnlyToClosure( |
| 256 |
[se](absl::Status status) { SessionReadCb(se, status); }); |
| 257 |
se->em_fd->NotifyOnRead(se->session_read_closure); |
| 258 |
sv->listen_closure = PosixEngineClosure::TestOnlyToClosure( |
| 259 |
[sv](absl::Status status) { ListenCb(sv, status); }); |
| 260 |
listen_em_fd->NotifyOnRead(sv->listen_closure); |
| 261 |
} |
| 262 |
|
| 263 |
// Start a test server, return the TCP listening port bound to listen_fd. |
| 264 |
// ListenCb() is registered to be interested in reading from listen_fd. |
| 265 |
// When connection request arrives, ListenCb() is called to accept the |
| 266 |
// connection request. |
| 267 |
int ServerStart(server* sv) { |
| 268 |
int port = grpc_pick_unused_port_or_die(); |
| 269 |
int fd; |
| 270 |
struct sockaddr_in6 sin; |
| 271 |
socklen_t addr_len; |
| 272 |
|
| 273 |
CreateTestSocket(port, &fd, &sin); |
| 274 |
addr_len = sizeof(sin); |
| 275 |
EXPECT_EQ(bind(fd, (struct sockaddr*)&sin, addr_len), 0); |
| 276 |
EXPECT_EQ(getsockname(fd, (struct sockaddr*)&sin, &addr_len), 0); |
| 277 |
port = ntohs(sin.sin6_port); |
| 278 |
EXPECT_EQ(listen(fd, MAX_NUM_FD), 0); |
| 279 |
|
| 280 |
sv->em_fd = g_event_poller->CreateHandle(fd, "server", false); |
| 281 |
sv->listen_closure = PosixEngineClosure::TestOnlyToClosure( |
| 282 |
[sv](absl::Status status) { ListenCb(sv, status); }); |
| 283 |
sv->em_fd->NotifyOnRead(sv->listen_closure); |
| 284 |
return port; |
| 285 |
} |
| 286 |
|
| 287 |
// ===An upload client to test notify_on_write=== |
| 288 |
|
| 289 |
// An upload client. |
| 290 |
typedef struct { |
| 291 |
EventHandle* em_fd; |
| 292 |
char write_buf[CLIENT_WRITE_BUF_SIZE]; |
| 293 |
ssize_t write_bytes_total; |
| 294 |
// Number of times that the client fills up the write buffer and calls |
| 295 |
// notify_on_write to schedule another write. |
| 296 |
int client_write_cnt; |
| 297 |
int done; |
| 298 |
PosixEngineClosure* write_closure; |
| 299 |
} client; |
| 300 |
|
| 301 |
void ClientInit(client* cl) { |
| 302 |
memset(cl->write_buf, 0, sizeof(cl->write_buf)); |
| 303 |
cl->write_bytes_total = 0; |
| 304 |
cl->client_write_cnt = 0; |
| 305 |
cl->done = 0; |
| 306 |
} |
| 307 |
|
| 308 |
// Called when a client upload session is ready to shutdown. |
| 309 |
void ClientSessionShutdownCb(client* cl) { |
| 310 |
cl->em_fd->OrphanHandle(nullptr, nullptr, "c"); |
| 311 |
gpr_mu_lock(&g_mu); |
| 312 |
cl->done = 1; |
| 313 |
g_event_poller->Kick(); |
| 314 |
gpr_mu_unlock(&g_mu); |
| 315 |
} |
| 316 |
|
| 317 |
// Write as much as possible, then register notify_on_write. |
| 318 |
void ClientSessionWrite(client* cl, absl::Status status) { |
| 319 |
int fd = cl->em_fd->WrappedFd(); |
| 320 |
ssize_t write_once = 0; |
| 321 |
|
| 322 |
if (!status.ok()) { |
| 323 |
ClientSessionShutdownCb(cl); |
| 324 |
return; |
| 325 |
} |
| 326 |
|
| 327 |
do { |
| 328 |
write_once = write(fd, cl->write_buf, CLIENT_WRITE_BUF_SIZE); |
| 329 |
if (write_once > 0) cl->write_bytes_total += write_once; |
| 330 |
} while (write_once > 0); |
| 331 |
|
| 332 |
EXPECT_EQ(errno, EAGAIN); |
| 333 |
gpr_mu_lock(&g_mu); |
| 334 |
if (cl->client_write_cnt < CLIENT_TOTAL_WRITE_CNT) { |
| 335 |
cl->write_closure = PosixEngineClosure::TestOnlyToClosure( |
| 336 |
[cl](absl::Status status) { ClientSessionWrite(cl, status); }); |
| 337 |
cl->client_write_cnt++; |
| 338 |
gpr_mu_unlock(&g_mu); |
| 339 |
cl->em_fd->NotifyOnWrite(cl->write_closure); |
| 340 |
} else { |
| 341 |
gpr_mu_unlock(&g_mu); |
| 342 |
ClientSessionShutdownCb(cl); |
| 343 |
} |
| 344 |
} |
| 345 |
|
| 346 |
// Start a client to send a stream of bytes. |
| 347 |
void ClientStart(client* cl, int port) { |
| 348 |
int fd; |
| 349 |
struct sockaddr_in6 sin; |
| 350 |
CreateTestSocket(port, &fd, &sin); |
| 351 |
if (connect(fd, reinterpret_cast<struct sockaddr*>(&sin), sizeof(sin)) == |
| 352 |
-1) { |
| 353 |
if (errno == EINPROGRESS) { |
| 354 |
struct pollfd pfd; |
| 355 |
pfd.fd = fd; |
| 356 |
pfd.events = POLLOUT; |
| 357 |
pfd.revents = 0; |
| 358 |
if (poll(&pfd, 1, -1) == -1) { |
| 359 |
gpr_log(GPR_ERROR, "poll() failed during connect; errno=%d", errno); |
| 360 |
abort(); |
| 361 |
} |
| 362 |
} else { |
| 363 |
gpr_log(GPR_ERROR, "Failed to connect to the server (errno=%d)", errno); |
| 364 |
abort(); |
| 365 |
} |
| 366 |
} |
| 367 |
|
| 368 |
cl->em_fd = g_event_poller->CreateHandle(fd, "client", false); |
| 369 |
ClientSessionWrite(cl, absl::OkStatus()); |
| 370 |
} |
| 371 |
|
| 372 |
// Wait for the signal to shutdown client and server. |
| 373 |
void WaitAndShutdown(server* sv, client* cl) { |
| 374 |
Poller::WorkResult result; |
| 375 |
gpr_mu_lock(&g_mu); |
| 376 |
while (!sv->done || !cl->done) { |
| 377 |
gpr_mu_unlock(&g_mu); |
| 378 |
result = g_event_poller->Work(24h, []() {}); |
| 379 |
ASSERT_FALSE(result == Poller::WorkResult::kDeadlineExceeded); |
| 380 |
gpr_mu_lock(&g_mu); |
| 381 |
} |
| 382 |
gpr_mu_unlock(&g_mu); |
| 383 |
} |
| 384 |
|
| 385 |
class EventPollerTest : public ::testing::Test { |
| 386 |
void SetUp() override { |
| 387 |
engine_ = |
| 388 |
std::make_unique<grpc_event_engine::experimental::PosixEventEngine>(); |
| 389 |
EXPECT_NE(engine_, nullptr); |
| 390 |
scheduler_ = |
| 391 |
std::make_unique<grpc_event_engine::posix_engine::TestScheduler>( |
| 392 |
engine_.get()); |
| 393 |
EXPECT_NE(scheduler_, nullptr); |
| 394 |
g_event_poller = MakeDefaultPoller(scheduler_.get()); |
| 395 |
engine_ = PosixEventEngine::MakeTestOnlyPosixEventEngine(g_event_poller); |
| 396 |
EXPECT_NE(engine_, nullptr); |
| 397 |
scheduler_->ChangeCurrentEventEngine(engine_.get()); |
| 398 |
if (g_event_poller != nullptr) { |
| 399 |
gpr_log(GPR_INFO, "Using poller: %s", g_event_poller->Name().c_str()); |
| 400 |
} |
| 401 |
} |
| 402 |
|
| 403 |
void TearDown() override { |
| 404 |
if (g_event_poller != nullptr) { |
| 405 |
g_event_poller->Shutdown(); |
| 406 |
} |
| 407 |
} |
| 408 |
|
| 409 |
public: |
| 410 |
TestScheduler* Scheduler() { return scheduler_.get(); } |
| 411 |
|
| 412 |
private: |
| 413 |
std::shared_ptr<grpc_event_engine::experimental::PosixEventEngine> engine_; |
| 414 |
std::unique_ptr<grpc_event_engine::posix_engine::TestScheduler> scheduler_; |
| 415 |
}; |
| 416 |
|
| 417 |
// Test grpc_fd. Start an upload server and client, upload a stream of bytes |
| 418 |
// from the client to the server, and verify that the total number of sent |
| 419 |
// bytes is equal to the total number of received bytes. |
| 420 |
TEST_F(EventPollerTest, TestEventPollerHandle) { |
| 421 |
server sv; |
| 422 |
client cl; |
| 423 |
int port; |
| 424 |
if (g_event_poller == nullptr) { |
| 425 |
return; |
| 426 |
} |
| 427 |
ServerInit(&sv); |
| 428 |
port = ServerStart(&sv); |
| 429 |
ClientInit(&cl); |
| 430 |
ClientStart(&cl, port); |
| 431 |
|
| 432 |
WaitAndShutdown(&sv, &cl); |
| 433 |
EXPECT_EQ(sv.read_bytes_total, cl.write_bytes_total); |
| 434 |
} |
| 435 |
|
| 436 |
typedef struct FdChangeData { |
| 437 |
void (*cb_that_ran)(struct FdChangeData*, absl::Status); |
| 438 |
} FdChangeData; |
| 439 |
|
| 440 |
void InitChangeData(FdChangeData* fdc) { fdc->cb_that_ran = nullptr; } |
| 441 |
|
| 442 |
void DestroyChangeData(FdChangeData* /*fdc*/) {} |
| 443 |
|
| 444 |
void FirstReadCallback(FdChangeData* fdc, absl::Status /*status*/) { |
| 445 |
gpr_mu_lock(&g_mu); |
| 446 |
fdc->cb_that_ran = FirstReadCallback; |
| 447 |
g_event_poller->Kick(); |
| 448 |
gpr_mu_unlock(&g_mu); |
| 449 |
} |
| 450 |
|
| 451 |
void SecondReadCallback(FdChangeData* fdc, absl::Status /*status*/) { |
| 452 |
gpr_mu_lock(&g_mu); |
| 453 |
fdc->cb_that_ran = SecondReadCallback; |
| 454 |
g_event_poller->Kick(); |
| 455 |
gpr_mu_unlock(&g_mu); |
| 456 |
} |
| 457 |
|
| 458 |
// Test that changing the callback we use for notify_on_read actually works. |
| 459 |
// Note that we have two different but almost identical callbacks above -- the |
| 460 |
// point is to have two different function pointers and two different data |
| 461 |
// pointers and make sure that changing both really works. |
| 462 |
TEST_F(EventPollerTest, TestEventPollerHandleChange) { |
| 463 |
EventHandle* em_fd; |
| 464 |
FdChangeData a, b; |
| 465 |
int flags; |
| 466 |
int sv[2]; |
| 467 |
char data; |
| 468 |
ssize_t result; |
| 469 |
if (g_event_poller == nullptr) { |
| 470 |
return; |
| 471 |
} |
| 472 |
PosixEngineClosure* first_closure = PosixEngineClosure::TestOnlyToClosure( |
| 473 |
[a = &a](absl::Status status) { FirstReadCallback(a, status); }); |
| 474 |
PosixEngineClosure* second_closure = PosixEngineClosure::TestOnlyToClosure( |
| 475 |
[b = &b](absl::Status status) { SecondReadCallback(b, status); }); |
| 476 |
InitChangeData(&a); |
| 477 |
InitChangeData(&b); |
| 478 |
|
| 479 |
EXPECT_EQ(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0); |
| 480 |
flags = fcntl(sv[0], F_GETFL, 0); |
| 481 |
EXPECT_EQ(fcntl(sv[0], F_SETFL, flags | O_NONBLOCK), 0); |
| 482 |
flags = fcntl(sv[1], F_GETFL, 0); |
| 483 |
EXPECT_EQ(fcntl(sv[1], F_SETFL, flags | O_NONBLOCK), 0); |
| 484 |
|
| 485 |
em_fd = |
| 486 |
g_event_poller->CreateHandle(sv[0], "TestEventPollerHandleChange", false); |
| 487 |
EXPECT_NE(em_fd, nullptr); |
| 488 |
// Register the first callback, then make its FD readable |
| 489 |
em_fd->NotifyOnRead(first_closure); |
| 490 |
data = 0; |
| 491 |
result = write(sv[1], &data, 1); |
| 492 |
EXPECT_EQ(result, 1); |
| 493 |
|
| 494 |
// And now wait for it to run. |
| 495 |
auto poller_work = [](FdChangeData* fdc) { |
| 496 |
Poller::WorkResult result; |
| 497 |
gpr_mu_lock(&g_mu); |
| 498 |
while (fdc->cb_that_ran == nullptr) { |
| 499 |
gpr_mu_unlock(&g_mu); |
| 500 |
result = g_event_poller->Work(24h, []() {}); |
| 501 |
ASSERT_FALSE(result == Poller::WorkResult::kDeadlineExceeded); |
| 502 |
gpr_mu_lock(&g_mu); |
| 503 |
} |
| 504 |
}; |
| 505 |
poller_work(&a); |
| 506 |
EXPECT_EQ(a.cb_that_ran, FirstReadCallback); |
| 507 |
gpr_mu_unlock(&g_mu); |
| 508 |
|
| 509 |
// And drain the socket so we can generate a new read edge |
| 510 |
result = read(sv[0], &data, 1); |
| 511 |
EXPECT_EQ(result, 1); |
| 512 |
|
| 513 |
// Now register a second callback with distinct change data, and do the same |
| 514 |
// thing again. |
| 515 |
em_fd->NotifyOnRead(second_closure); |
| 516 |
data = 0; |
| 517 |
result = write(sv[1], &data, 1); |
| 518 |
EXPECT_EQ(result, 1); |
| 519 |
|
| 520 |
// And now wait for it to run. |
| 521 |
poller_work(&b); |
| 522 |
// Except now we verify that SecondReadCallback ran instead. |
| 523 |
EXPECT_EQ(b.cb_that_ran, SecondReadCallback); |
| 524 |
gpr_mu_unlock(&g_mu); |
| 525 |
|
| 526 |
em_fd->OrphanHandle(nullptr, nullptr, "d"); |
| 527 |
DestroyChangeData(&a); |
| 528 |
DestroyChangeData(&b); |
| 529 |
close(sv[1]); |
| 530 |
} |
| 531 |
|
| 532 |
std::atomic<int> kTotalActiveWakeupFdHandles{0}; |
| 533 |
|
| 534 |
// A helper class representing one file descriptor. Its implemented using |
| 535 |
// a WakeupFd. It registers itself with the poller and waits to be notified |
| 536 |
// of read events. Upon receiving a read event, (1) it processes it, |
| 537 |
// (2) registes to be notified of the next read event and (3) schedules |
| 538 |
// generation of the next read event. The Fd orphanes itself after processing |
| 539 |
// a specified number of read events. |
| 540 |
class WakeupFdHandle : public grpc_core::DualRefCounted<WakeupFdHandle> { |
| 541 |
public: |
| 542 |
WakeupFdHandle(int num_wakeups, Scheduler* scheduler, |
| 543 |
PosixEventPoller* poller) |
| 544 |
: num_wakeups_(num_wakeups), |
| 545 |
scheduler_(scheduler), |
| 546 |
poller_(poller), |
| 547 |
on_read_( |
| 548 |
PosixEngineClosure::ToPermanentClosure([this](absl::Status status) { |
| 549 |
EXPECT_TRUE(status.ok()); |
| 550 |
status = ReadPipe(); |
| 551 |
if (!status.ok()) { |
| 552 |
// Rarely epoll1 poller may generate an EPOLLHUP - which is a |
| 553 |
// spurious wakeup. Poll based poller may also likely generate a |
| 554 |
// lot of spurious wakeups because of the level triggered nature |
| 555 |
// of poll In such cases do not bother changing the number of |
| 556 |
// wakeups received. |
| 557 |
EXPECT_EQ(status, absl::InternalError("Spurious Wakeup")); |
| 558 |
handle_->NotifyOnRead(on_read_); |
| 559 |
return; |
| 560 |
} |
| 561 |
if (--num_wakeups_ == 0) { |
| 562 |
// This should invoke the registered NotifyOnRead callbacks with |
| 563 |
// the shutdown error. When those callbacks call Unref(), the |
| 564 |
// WakeupFdHandle should call OrphanHandle in the Unref() method |
| 565 |
// implementation. |
| 566 |
handle_->ShutdownHandle(absl::InternalError("Shutting down")); |
| 567 |
Unref(); |
| 568 |
} else { |
| 569 |
handle_->NotifyOnRead(on_read_); |
| 570 |
Ref().release(); |
| 571 |
// Schedule next wakeup to trigger the registered NotifyOnRead |
| 572 |
// callback. |
| 573 |
scheduler_->Run(SelfDeletingClosure::Create([this]() { |
| 574 |
// Send next wakeup. |
| 575 |
EXPECT_TRUE(wakeup_fd_->Wakeup().ok()); |
| 576 |
Unref(); |
| 577 |
})); |
| 578 |
} |
| 579 |
})) { |
| 580 |
WeakRef().release(); |
| 581 |
++kTotalActiveWakeupFdHandles; |
| 582 |
EXPECT_GT(num_wakeups_, 0); |
| 583 |
EXPECT_NE(scheduler_, nullptr); |
| 584 |
EXPECT_NE(poller_, nullptr); |
| 585 |
wakeup_fd_ = *PipeWakeupFd::CreatePipeWakeupFd(); |
| 586 |
handle_ = poller_->CreateHandle(wakeup_fd_->ReadFd(), "test", false); |
| 587 |
EXPECT_NE(handle_, nullptr); |
| 588 |
handle_->NotifyOnRead(on_read_); |
| 589 |
// Send a wakeup initially. |
| 590 |
EXPECT_TRUE(wakeup_fd_->Wakeup().ok()); |
| 591 |
} |
| 592 |
|
| 593 |
~WakeupFdHandle() override { delete on_read_; } |
| 594 |
|
| 595 |
void Orphan() override { |
| 596 |
// Once the handle has orphaned itself, decrement |
| 597 |
// kTotalActiveWakeupFdHandles. Once all handles have orphaned themselves, |
| 598 |
// send a Kick to the poller. |
| 599 |
handle_->OrphanHandle( |
| 600 |
PosixEngineClosure::TestOnlyToClosure( |
| 601 |
[poller = poller_, wakeupfd_handle = this](absl::Status status) { |
| 602 |
EXPECT_TRUE(status.ok()); |
| 603 |
if (--kTotalActiveWakeupFdHandles == 0) { |
| 604 |
poller->Kick(); |
| 605 |
} |
| 606 |
wakeupfd_handle->WeakUnref(); |
| 607 |
}), |
| 608 |
nullptr, ""); |
| 609 |
} |
| 610 |
|
| 611 |
private: |
| 612 |
absl::Status ReadPipe() { |
| 613 |
char buf[128]; |
| 614 |
ssize_t r; |
| 615 |
int total_bytes_read = 0; |
| 616 |
for (;;) { |
| 617 |
r = read(wakeup_fd_->ReadFd(), buf, sizeof(buf)); |
| 618 |
if (r > 0) { |
| 619 |
total_bytes_read += r; |
| 620 |
continue; |
| 621 |
} |
| 622 |
if (r == 0) return absl::OkStatus(); |
| 623 |
switch (errno) { |
| 624 |
case EAGAIN: |
| 625 |
return total_bytes_read > 0 ? absl::OkStatus() |
| 626 |
: absl::InternalError("Spurious Wakeup"); |
| 627 |
case EINTR: |
| 628 |
continue; |
| 629 |
default: |
| 630 |
return absl::Status( |
| 631 |
absl::StatusCode::kInternal, |
| 632 |
absl::StrCat("read: ", grpc_core::StrError(errno))); |
| 633 |
} |
| 634 |
} |
| 635 |
} |
| 636 |
int num_wakeups_; |
| 637 |
Scheduler* scheduler_; |
| 638 |
PosixEventPoller* poller_; |
| 639 |
PosixEngineClosure* on_read_; |
| 640 |
std::unique_ptr<WakeupFd> wakeup_fd_; |
| 641 |
EventHandle* handle_; |
| 642 |
}; |
| 643 |
|
| 644 |
// A helper class to create Fds and drive the polling for these Fds. It |
| 645 |
// repeatedly calls the Work(..) method on the poller to get pet pending events, |
| 646 |
// then schedules another parallel Work(..) instantiation and processes these |
| 647 |
// pending events. This continues until all Fds have orphaned themselves. |
| 648 |
class Worker : public grpc_core::DualRefCounted<Worker> { |
| 649 |
public: |
| 650 |
Worker(Scheduler* scheduler, PosixEventPoller* poller, int num_handles, |
| 651 |
int num_wakeups_per_handle) |
| 652 |
: scheduler_(scheduler), poller_(poller) { |
| 653 |
handles_.reserve(num_handles); |
| 654 |
for (int i = 0; i < num_handles; i++) { |
| 655 |
handles_.push_back( |
| 656 |
new WakeupFdHandle(num_wakeups_per_handle, scheduler_, poller_)); |
| 657 |
} |
| 658 |
WeakRef().release(); |
| 659 |
} |
| 660 |
void Orphan() override { signal.Notify(); } |
| 661 |
void Start() { |
| 662 |
// Start executing Work(..). |
| 663 |
scheduler_->Run([this]() { Work(); }); |
| 664 |
} |
| 665 |
|
| 666 |
void Wait() { |
| 667 |
signal.WaitForNotification(); |
| 668 |
WeakUnref(); |
| 669 |
} |
| 670 |
|
| 671 |
private: |
| 672 |
void Work() { |
| 673 |
auto result = g_event_poller->Work(24h, [this]() { |
| 674 |
// Schedule next work instantiation immediately and take a Ref for |
| 675 |
// the next instantiation. |
| 676 |
Ref().release(); |
| 677 |
scheduler_->Run([this]() { Work(); }); |
| 678 |
}); |
| 679 |
ASSERT_TRUE(result == Poller::WorkResult::kOk || |
| 680 |
result == Poller::WorkResult::kKicked); |
| 681 |
// Corresponds to the Ref taken for the current instantiation. If the |
| 682 |
// result was Poller::WorkResult::kKicked, then the next work instantiation |
| 683 |
// would not have been scheduled and the poll_again callback should have |
| 684 |
// been deleted. |
| 685 |
Unref(); |
| 686 |
} |
| 687 |
Scheduler* scheduler_; |
| 688 |
PosixEventPoller* poller_; |
| 689 |
grpc_core::Notification signal; |
| 690 |
std::vector<WakeupFdHandle*> handles_; |
| 691 |
}; |
| 692 |
|
| 693 |
// This test creates kNumHandles file descriptors and kNumWakeupsPerHandle |
| 694 |
// separate read events to the created Fds. The Fds use the NotifyOnRead API to |
| 695 |
// wait for a read event, upon receiving a read event they process it |
| 696 |
// immediately and schedule the wait for the next read event. A new read event |
| 697 |
// is also generated for each fd in parallel after the previous one is |
| 698 |
// processed. |
| 699 |
TEST_F(EventPollerTest, TestMultipleHandles) { |
| 700 |
static constexpr int kNumHandles = 100; |
| 701 |
static constexpr int kNumWakeupsPerHandle = 100; |
| 702 |
if (g_event_poller == nullptr) { |
| 703 |
return; |
| 704 |
} |
| 705 |
Worker* worker = new Worker(Scheduler(), g_event_poller, kNumHandles, |
| 706 |
kNumWakeupsPerHandle); |
| 707 |
worker->Start(); |
| 708 |
worker->Wait(); |
| 709 |
} |
| 710 |
|
| 711 |
} // namespace |
| 712 |
} // namespace posix_engine |
| 713 |
} // namespace grpc_event_engine |
| 714 |
|
| 715 |
int main(int argc, char** argv) { |
| 716 |
::testing::InitGoogleTest(&argc, argv); |
| 717 |
gpr_mu_init(&g_mu); |
| 718 |
grpc_core::UniquePtr<char> poll_strategy = |
| 719 |
GPR_GLOBAL_CONFIG_GET(grpc_poll_strategy); |
| 720 |
GPR_GLOBAL_CONFIG_GET(grpc_poll_strategy); |
| 721 |
auto strings = absl::StrSplit(poll_strategy.get(), ','); |
| 722 |
if (std::find(strings.begin(), strings.end(), "none") != strings.end()) { |
| 723 |
// Skip the test entirely if poll strategy is none. |
| 724 |
return 0; |
| 725 |
} |
| 726 |
// TODO(ctiller): EventEngine temporarily needs grpc to be initialized first |
| 727 |
// until we clear out the iomgr shutdown code. |
| 728 |
grpc_init(); |
| 729 |
int r = RUN_ALL_TESTS(); |
| 730 |
grpc_shutdown(); |
| 731 |
return r; |
| 732 |
} |
| 733 |
|
| 734 |
#else /* GRPC_POSIX_SOCKET_EV */ |
| 735 |
|
| 736 |
int main(int argc, char** argv) { return 1; } |
| 737 |
|
| 738 |
#endif /* GRPC_POSIX_SOCKET_EV */ |