Debian Codegraph @

src/core/lib/event_engine/posix_engine/posix_engine.cc

raw
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 #include <grpc/support/port_platform.h>
15
16 #include "src/core/lib/event_engine/posix_engine/posix_engine.h"
17
18 #include <algorithm>
19 #include <atomic>
20 #include <chrono>
21 #include <cstring>
22 #include <memory>
23 #include <string>
24 #include <utility>
25
26 #include "absl/cleanup/cleanup.h"
27 #include "absl/functional/any_invocable.h"
28 #include "absl/meta/type_traits.h"
29 #include "absl/status/status.h"
30 #include "absl/strings/str_cat.h"
31
32 #include <grpc/event_engine/event_engine.h>
33 #include <grpc/event_engine/memory_allocator.h>
34 #include <grpc/support/cpu.h>
35 #include <grpc/support/log.h>
36
37 #include "src/core/lib/debug/trace.h"
38 #include "src/core/lib/event_engine/poller.h"
39 #include "src/core/lib/event_engine/posix_engine/timer.h"
40 #include "src/core/lib/event_engine/trace.h"
41 #include "src/core/lib/event_engine/utils.h"
42 #include "src/core/lib/experiments/experiments.h"
43 #include "src/core/lib/gprpp/sync.h"
44
45 #ifdef GRPC_POSIX_SOCKET_TCP
46 #include <errno.h> // IWYU pragma: keep
47 #include <stdint.h> // IWYU pragma: keep
48 #include <sys/socket.h> // IWYU pragma: keep
49
50 #include "src/core/lib/event_engine/posix_engine/event_poller.h"
51 #include "src/core/lib/event_engine/posix_engine/event_poller_posix_default.h"
52 #include "src/core/lib/event_engine/posix_engine/posix_endpoint.h"
53 #endif // GRPC_POSIX_SOCKET_TCP
54
55 // IWYU pragma: no_include <ratio>
56
57 using namespace std::chrono_literals;
58
59 namespace grpc_event_engine {
60 namespace experimental {
61
62 #ifdef GRPC_POSIX_SOCKET_TCP
63 using ::grpc_event_engine::posix_engine::EventHandle;
64 using ::grpc_event_engine::posix_engine::PosixEngineClosure;
65 using ::grpc_event_engine::posix_engine::PosixEventPoller;
66 using ::grpc_event_engine::posix_engine::PosixSocketWrapper;
67 using ::grpc_event_engine::posix_engine::PosixTcpOptions;
68 using ::grpc_event_engine::posix_engine::SockaddrToString;
69 using ::grpc_event_engine::posix_engine::TcpOptionsFromEndpointConfig;
70
71 void AsyncConnect::Start(EventEngine::Duration timeout) {
72 on_writable_ = PosixEngineClosure::ToPermanentClosure(
73 [this](absl::Status status) { OnWritable(std::move(status)); });
74 alarm_handle_ = engine_->RunAfter(timeout, [this]() {
75 OnTimeoutExpired(absl::DeadlineExceededError("connect() timed out"));
76 });
77 fd_->NotifyOnWrite(on_writable_);
78 }
79
80 AsyncConnect ::~AsyncConnect() { delete on_writable_; }
81
82 void AsyncConnect::OnTimeoutExpired(absl::Status status) {
83 bool done = false;
84 {
85 grpc_core::MutexLock lock(&mu_);
86 if (fd_ != nullptr) {
87 fd_->ShutdownHandle(std::move(status));
88 }
89 done = (--refs_ == 0);
90 }
91 if (done) {
92 delete this;
93 }
94 }
95
96 void AsyncConnect::OnWritable(absl::Status status)
97 ABSL_NO_THREAD_SAFETY_ANALYSIS {
98 int so_error = 0;
99 socklen_t so_error_size;
100 int err;
101 int done;
102 int consumed_refs = 1;
103 EventHandle* fd;
104 absl::StatusOr<std::unique_ptr<EventEngine::Endpoint>> ep;
105
106 mu_.Lock();
107 GPR_ASSERT(fd_ != nullptr);
108 fd = std::exchange(fd_, nullptr);
109 bool connect_cancelled = connect_cancelled_;
110 if (fd->IsHandleShutdown() && status.ok()) {
111 if (!connect_cancelled) {
112 // status is OK and handle has been shutdown but the connect was not
113 // cancelled. This can happen if the timeout expired and the while the
114 // OnWritable just started executing.
115 status = absl::DeadlineExceededError("connect() timed out");
116 } else {
117 // This can happen if the connection was cancelled while the OnWritable
118 // just started executing.
119 status = absl::FailedPreconditionError("Connection cancelled");
120 }
121 }
122 mu_.Unlock();
123
124 if (engine_->Cancel(alarm_handle_)) {
125 ++consumed_refs;
126 }
127
128 auto on_writable_finish = absl::MakeCleanup([&]() -> void {
129 mu_.AssertHeld();
130 if (!connect_cancelled) {
131 reinterpret_cast<PosixEventEngine*>(engine_.get())
132 ->OnConnectFinishInternal(connection_handle_);
133 }
134 if (fd != nullptr) {
135 fd->OrphanHandle(nullptr, nullptr, "tcp_client_orphan");
136 fd = nullptr;
137 }
138 if (!status.ok()) {
139 ep = absl::CancelledError(
140 absl::StrCat("Failed to connect to remote host: ", resolved_addr_str_,
141 " with error: ", status.ToString()));
142 }
143 // Run the OnConnect callback asynchronously.
144 if (!connect_cancelled) {
145 executor_->Run(
146 [ep = std::move(ep), on_connect = std::move(on_connect_)]() mutable {
147 if (on_connect) {
148 on_connect(std::move(ep));
149 }
150 });
151 }
152 done = ((refs_ -= consumed_refs) == 0);
153 mu_.Unlock();
154 if (done) {
155 delete this;
156 }
157 });
158
159 mu_.Lock();
160 if (!status.ok() || connect_cancelled) {
161 return;
162 }
163
164 do {
165 so_error_size = sizeof(so_error);
166 err = getsockopt(fd->WrappedFd(), SOL_SOCKET, SO_ERROR, &so_error,
167 &so_error_size);
168 } while (err < 0 && errno == EINTR);
169 if (err < 0) {
170 status = absl::FailedPreconditionError(
171 absl::StrCat("getsockopt: ", std::strerror(errno)));
172 return;
173 }
174
175 switch (so_error) {
176 case 0:
177 ep = CreatePosixEndpoint(fd, nullptr, engine_, std::move(allocator_),
178 options_);
179 fd = nullptr;
180 break;
181 case ENOBUFS:
182 // We will get one of these errors if we have run out of
183 // memory in the kernel for the data structures allocated
184 // when you connect a socket. If this happens it is very
185 // likely that if we wait a little bit then try again the
186 // connection will work (since other programs or this
187 // program will close their network connections and free up
188 // memory). This does _not_ indicate that there is anything
189 // wrong with the server we are connecting to, this is a
190 // local problem.
191
192 // If you are looking at this code, then chances are that
193 // your program or another program on the same computer
194 // opened too many network connections. The "easy" fix:
195 // don't do that!
196 gpr_log(GPR_ERROR, "kernel out of buffers");
197 mu_.Unlock();
198 fd->NotifyOnWrite(on_writable_);
199 // Don't run the cleanup function for this case.
200 std::move(on_writable_finish).Cancel();
201 return;
202 case ECONNREFUSED:
203 // This error shouldn't happen for anything other than connect().
204 status = absl::FailedPreconditionError(
205 absl::StrCat("connect: ", std::strerror(so_error)));
206 break;
207 default:
208 // We don't really know which syscall triggered the problem here, so
209 // punt by reporting getsockopt().
210 status = absl::FailedPreconditionError(
211 absl::StrCat("getsockopt(SO_ERROR): ", std::strerror(so_error)));
212 break;
213 }
214 }
215
216 EventEngine::ConnectionHandle PosixEventEngine::ConnectInternal(
217 PosixSocketWrapper sock, OnConnectCallback on_connect, ResolvedAddress addr,
218 MemoryAllocator&& allocator, const PosixTcpOptions& options,
219 Duration timeout) {
220 int err;
221 int saved_errno;
222 do {
223 err = connect(sock.Fd(), addr.address(), addr.size());
224 } while (err < 0 && errno == EINTR);
225 saved_errno = errno;
226
227 auto addr_uri = SockaddrToString(&addr, true);
228 if (!addr_uri.ok()) {
229 Run([on_connect = std::move(on_connect),
230 ep = absl::FailedPreconditionError(absl::StrCat(
231 "connect failed: ", "invalid addr: ",
232 addr_uri.value()))]() mutable { on_connect(std::move(ep)); });
233 return {0, 0};
234 }
235
236 std::string name = absl::StrCat("tcp-client:", addr_uri.value());
237 PosixEventPoller* poller = poller_manager_->Poller();
238 EventHandle* handle =
239 poller->CreateHandle(sock.Fd(), name, poller->CanTrackErrors());
240 int64_t connection_id = 0;
241 if (saved_errno == EWOULDBLOCK || saved_errno == EINPROGRESS) {
242 // Connection is still in progress.
243 connection_id = last_connection_id_.fetch_add(1, std::memory_order_acq_rel);
244 }
245
246 if (err >= 0) {
247 // Connection already succeded. Return 0 to discourage any cancellation
248 // attempts.
249 Run([on_connect = std::move(on_connect),
250 ep = CreatePosixEndpoint(handle, nullptr, shared_from_this(),
251 std::move(allocator), options)]() mutable {
252 on_connect(std::move(ep));
253 });
254 return {0, 0};
255 }
256 if (saved_errno != EWOULDBLOCK && saved_errno != EINPROGRESS) {
257 // Connection already failed. Return 0 to discourage any cancellation
258 // attempts.
259 handle->OrphanHandle(nullptr, nullptr, "tcp_client_connect_error");
260 Run([on_connect = std::move(on_connect),
261 ep = absl::FailedPreconditionError(
262 absl::StrCat("connect failed: ", "addr: ", addr_uri.value(),
263 " error: ", std::strerror(saved_errno)))]() mutable {
264 on_connect(std::move(ep));
265 });
266 return {0, 0};
267 }
268 AsyncConnect* ac = new AsyncConnect(
269 std::move(on_connect), shared_from_this(), executor_.get(), handle,
270 std::move(allocator), options, addr_uri.value(), connection_id);
271 int shard_number = connection_id % connection_shards_.size();
272 struct ConnectionShard* shard = &connection_shards_[shard_number];
273 {
274 grpc_core::MutexLock lock(&shard->mu);
275 shard->pending_connections.insert_or_assign(connection_id, ac);
276 }
277 // Start asynchronous connect and return the connection id.
278 ac->Start(timeout);
279 return {static_cast<intptr_t>(connection_id), 0};
280 }
281
282 void PosixEventEngine::OnConnectFinishInternal(int connection_handle) {
283 int shard_number = connection_handle % connection_shards_.size();
284 struct ConnectionShard* shard = &connection_shards_[shard_number];
285 {
286 grpc_core::MutexLock lock(&shard->mu);
287 shard->pending_connections.erase(connection_handle);
288 }
289 }
290
291 PosixEnginePollerManager::PosixEnginePollerManager(
292 std::shared_ptr<ThreadPool> executor)
293 : poller_(grpc_event_engine::posix_engine::MakeDefaultPoller(this)),
294 executor_(std::move(executor)) {}
295
296 PosixEnginePollerManager::PosixEnginePollerManager(PosixEventPoller* poller)
297 : poller_(poller),
298 poller_state_(PollerState::kExternal),
299 executor_(nullptr) {
300 GPR_DEBUG_ASSERT(poller_ != nullptr);
301 }
302
303 void PosixEnginePollerManager::Run(
304 experimental::EventEngine::Closure* closure) {
305 if (executor_ != nullptr) {
306 executor_->Run(closure);
307 }
308 }
309
310 void PosixEnginePollerManager::Run(absl::AnyInvocable<void()> cb) {
311 if (executor_ != nullptr) {
312 executor_->Run(std::move(cb));
313 }
314 }
315
316 void PosixEnginePollerManager::TriggerShutdown() {
317 // If the poller is external, dont try to shut it down. Otherwise
318 // set poller state to PollerState::kShuttingDown.
319 if (poller_state_.exchange(PollerState::kShuttingDown) ==
320 PollerState::kExternal) {
321 poller_ = nullptr;
322 return;
323 }
324 poller_->Kick();
325 }
326
327 PosixEnginePollerManager::~PosixEnginePollerManager() {
328 if (poller_ != nullptr) {
329 poller_->Shutdown();
330 }
331 }
332
333 PosixEventEngine::PosixEventEngine(PosixEventPoller* poller)
334 : connection_shards_(std::max(2 * gpr_cpu_num_cores(), 1u)),
335 executor_(std::make_shared<ThreadPool>()),
336 timer_manager_(executor_) {
337 poller_manager_ = std::make_shared<PosixEnginePollerManager>(poller);
338 }
339
340 PosixEventEngine::PosixEventEngine()
341 : connection_shards_(std::max(2 * gpr_cpu_num_cores(), 1u)),
342 executor_(std::make_shared<ThreadPool>()),
343 timer_manager_(executor_) {
344 if (grpc_core::IsPosixEventEngineEnablePollingEnabled()) {
345 poller_manager_ = std::make_shared<PosixEnginePollerManager>(executor_);
346 if (poller_manager_->Poller() != nullptr) {
347 executor_->Run([poller_manager = poller_manager_]() {
348 PollerWorkInternal(poller_manager);
349 });
350 }
351 }
352 }
353
354 void PosixEventEngine::PollerWorkInternal(
355 std::shared_ptr<PosixEnginePollerManager> poller_manager) {
356 // TODO(vigneshbabu): The timeout specified here is arbitrary. For instance,
357 // this can be improved by setting the timeout to the next expiring timer.
358 PosixEventPoller* poller = poller_manager->Poller();
359 ThreadPool* executor = poller_manager->Executor();
360 auto result = poller->Work(24h, [executor, &poller_manager]() {
361 executor->Run([poller_manager]() mutable {
362 PollerWorkInternal(std::move(poller_manager));
363 });
364 });
365 if (result == Poller::WorkResult::kDeadlineExceeded) {
366 // The event engine is not shutting down but the next asynchronous
367 // PollerWorkInternal did not get scheduled. Schedule it now.
368 executor->Run([poller_manager = std::move(poller_manager)]() {
369 PollerWorkInternal(poller_manager);
370 });
371 } else if (result == Poller::WorkResult::kKicked &&
372 poller_manager->IsShuttingDown()) {
373 // The Poller Got Kicked and poller_state_ is set to
374 // PollerState::kShuttingDown. This can currently happen only from the
375 // EventEngine destructor. Sample the use_count of poller_manager. If the
376 // sampled use_count is > 1, there is one more instance of Work(...)
377 // which hasn't returned yet. Send another Kick to be safe to ensure the
378 // pending instance of Work(..) also breaks out. Its possible that the other
379 // instance of Work(..) had already broken out before this Kick is sent. In
380 // that case, the Kick is spurious but it shouldn't cause any side effects.
381 if (poller_manager.use_count() > 1) {
382 poller->Kick();
383 }
384 }
385 }
386
387 #endif // GRPC_POSIX_SOCKET_TCP
388
389 struct PosixEventEngine::ClosureData final : public EventEngine::Closure {
390 absl::AnyInvocable<void()> cb;
391 posix_engine::Timer timer;
392 PosixEventEngine* engine;
393 EventEngine::TaskHandle handle;
394
395 void Run() override {
396 GRPC_EVENT_ENGINE_TRACE("PosixEventEngine:%p executing callback:%s", engine,
397 HandleToString(handle).c_str());
398 {
399 grpc_core::MutexLock lock(&engine->mu_);
400 engine->known_handles_.erase(handle);
401 }
402 cb();
403 delete this;
404 }
405 };
406
407 PosixEventEngine::~PosixEventEngine() {
408 {
409 grpc_core::MutexLock lock(&mu_);
410 if (GRPC_TRACE_FLAG_ENABLED(grpc_event_engine_trace)) {
411 for (auto handle : known_handles_) {
412 gpr_log(GPR_ERROR,
413 "(event_engine) PosixEventEngine:%p uncleared "
414 "TaskHandle at "
415 "shutdown:%s",
416 this, HandleToString(handle).c_str());
417 }
418 }
419 GPR_ASSERT(GPR_LIKELY(known_handles_.empty()));
420 }
421 timer_manager_.Shutdown();
422 #ifdef GRPC_POSIX_SOCKET_TCP
423 if (poller_manager_ != nullptr) {
424 poller_manager_->TriggerShutdown();
425 }
426 #endif // GRPC_POSIX_SOCKET_TCP
427 executor_->Quiesce();
428 }
429
430 bool PosixEventEngine::Cancel(EventEngine::TaskHandle handle) {
431 grpc_core::MutexLock lock(&mu_);
432 if (!known_handles_.contains(handle)) return false;
433 auto* cd = reinterpret_cast<ClosureData*>(handle.keys[0]);
434 bool r = timer_manager_.TimerCancel(&cd->timer);
435 known_handles_.erase(handle);
436 if (r) delete cd;
437 return r;
438 }
439
440 EventEngine::TaskHandle PosixEventEngine::RunAfter(
441 Duration when, absl::AnyInvocable<void()> closure) {
442 return RunAfterInternal(when, std::move(closure));
443 }
444
445 EventEngine::TaskHandle PosixEventEngine::RunAfter(
446 Duration when, EventEngine::Closure* closure) {
447 return RunAfterInternal(when, [closure]() { closure->Run(); });
448 }
449
450 void PosixEventEngine::Run(absl::AnyInvocable<void()> closure) {
451 executor_->Run(std::move(closure));
452 }
453
454 void PosixEventEngine::Run(EventEngine::Closure* closure) {
455 executor_->Run(closure);
456 }
457
458 EventEngine::TaskHandle PosixEventEngine::RunAfterInternal(
459 Duration when, absl::AnyInvocable<void()> cb) {
460 auto when_ts = ToTimestamp(timer_manager_.Now(), when);
461 auto* cd = new ClosureData;
462 cd->cb = std::move(cb);
463 cd->engine = this;
464 EventEngine::TaskHandle handle{reinterpret_cast<intptr_t>(cd),
465 aba_token_.fetch_add(1)};
466 grpc_core::MutexLock lock(&mu_);
467 known_handles_.insert(handle);
468 cd->handle = handle;
469 GRPC_EVENT_ENGINE_TRACE("PosixEventEngine:%p scheduling callback:%s", this,
470 HandleToString(handle).c_str());
471 timer_manager_.TimerInit(&cd->timer, when_ts, cd);
472 return handle;
473 }
474
475 std::unique_ptr<EventEngine::DNSResolver> PosixEventEngine::GetDNSResolver(
476 EventEngine::DNSResolver::ResolverOptions const& /*options*/) {
477 GPR_ASSERT(false && "unimplemented");
478 }
479
480 bool PosixEventEngine::IsWorkerThread() {
481 GPR_ASSERT(false && "unimplemented");
482 }
483
484 bool PosixEventEngine::CancelConnect(EventEngine::ConnectionHandle handle) {
485 #ifdef GRPC_POSIX_SOCKET_TCP
486 int connection_handle = handle.keys[0];
487 if (connection_handle <= 0) {
488 return false;
489 }
490 int shard_number = connection_handle % connection_shards_.size();
491 struct ConnectionShard* shard = &connection_shards_[shard_number];
492 AsyncConnect* ac = nullptr;
493 {
494 grpc_core::MutexLock lock(&shard->mu);
495 auto it = shard->pending_connections.find(connection_handle);
496 if (it != shard->pending_connections.end()) {
497 ac = it->second;
498 GPR_ASSERT(ac != nullptr);
499 // Trying to acquire ac->mu here would could cause a deadlock because
500 // the OnWritable method tries to acquire the two mutexes used
501 // here in the reverse order. But we dont need to acquire ac->mu before
502 // incrementing ac->refs here. This is because the OnWritable
503 // method decrements ac->refs only after deleting the connection handle
504 // from the corresponding hashmap. If the code enters here, it means
505 // that deletion hasn't happened yet. The deletion can only happen after
506 // the corresponding g_shard_mu is unlocked.
507 ++ac->refs_;
508 // Remove connection from list of active connections.
509 shard->pending_connections.erase(it);
510 }
511 }
512 if (ac == nullptr) {
513 return false;
514 }
515 ac->mu_.Lock();
516 bool connection_cancel_success = (ac->fd_ != nullptr);
517 if (connection_cancel_success) {
518 // Connection is still pending. The OnWritable callback hasn't executed
519 // yet because ac->fd != nullptr.
520 ac->connect_cancelled_ = true;
521 // Shutdown the fd. This would cause OnWritable to run as soon as
522 // possible. We dont need to pass a custom error here because it wont be
523 // used since the on_connect_closure is not run if connect cancellation is
524 // successfull.
525 ac->fd_->ShutdownHandle(
526 absl::FailedPreconditionError("Connection cancelled"));
527 }
528 bool done = (--ac->refs_ == 0);
529 ac->mu_.Unlock();
530 if (done) {
531 delete ac;
532 }
533 return connection_cancel_success;
534 #else // GRPC_POSIX_SOCKET_TCP
535 GPR_ASSERT(false &&
536 "EventEngine::CancelConnect is not supported on this platform");
537 #endif // GRPC_POSIX_SOCKET_TCP
538 }
539
540 EventEngine::ConnectionHandle PosixEventEngine::Connect(
541 OnConnectCallback on_connect, const ResolvedAddress& addr,
542 const EndpointConfig& args, MemoryAllocator memory_allocator,
543 Duration timeout) {
544 #ifdef GRPC_POSIX_SOCKET_TCP
545 if (!grpc_core::IsPosixEventEngineEnablePollingEnabled()) {
546 GPR_ASSERT(
547 false &&
548 "EventEngine::Connect is not supported because polling is not enabled");
549 }
550 GPR_ASSERT(poller_manager_ != nullptr);
551 PosixTcpOptions options = TcpOptionsFromEndpointConfig(args);
552 absl::StatusOr<PosixSocketWrapper::PosixSocketCreateResult> socket =
553 PosixSocketWrapper::CreateAndPrepareTcpClientSocket(options, addr);
554 if (!socket.ok()) {
555 Run([on_connect = std::move(on_connect),
556 status = socket.status()]() mutable { on_connect(status); });
557 return {0, 0};
558 }
559 return ConnectInternal((*socket).sock, std::move(on_connect),
560 (*socket).mapped_target_addr,
561 std::move(memory_allocator), options, timeout);
562 #else // GRPC_POSIX_SOCKET_TCP
563 GPR_ASSERT(false && "EventEngine::Connect is not supported on this platform");
564 #endif // GRPC_POSIX_SOCKET_TCP
565 }
566
567 absl::StatusOr<std::unique_ptr<EventEngine::Listener>>
568 PosixEventEngine::CreateListener(
569 Listener::AcceptCallback /*on_accept*/,
570 absl::AnyInvocable<void(absl::Status)> /*on_shutdown*/,
571 const EndpointConfig& /*config*/,
572 std::unique_ptr<MemoryAllocatorFactory> /*memory_allocator_factory*/) {
573 GPR_ASSERT(false && "unimplemented");
574 }
575
576 } // namespace experimental
577 } // namespace grpc_event_engine