Debian Codegraph @

src/core/lib/iomgr/tcp_client_posix.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 <grpc/support/port_platform.h>
20
21 #include "src/core/lib/iomgr/port.h"
22
23 #ifdef GRPC_POSIX_SOCKET_TCP_CLIENT
24
25 #include <errno.h>
26 #include <netinet/in.h>
27 #include <string.h>
28 #include <unistd.h>
29
30 #include "absl/container/flat_hash_map.h"
31 #include "absl/strings/str_cat.h"
32
33 #include <grpc/support/alloc.h>
34 #include <grpc/support/log.h>
35 #include <grpc/support/time.h>
36
37 #include "src/core/lib/address_utils/sockaddr_utils.h"
38 #include "src/core/lib/gpr/string.h"
39 #include "src/core/lib/iomgr/ev_posix.h"
40 #include "src/core/lib/iomgr/executor.h"
41 #include "src/core/lib/iomgr/iomgr_internal.h"
42 #include "src/core/lib/iomgr/sockaddr.h"
43 #include "src/core/lib/iomgr/socket_mutator.h"
44 #include "src/core/lib/iomgr/socket_utils_posix.h"
45 #include "src/core/lib/iomgr/tcp_client_posix.h"
46 #include "src/core/lib/iomgr/tcp_posix.h"
47 #include "src/core/lib/iomgr/timer.h"
48 #include "src/core/lib/iomgr/unix_sockets_posix.h"
49 #include "src/core/lib/slice/slice_internal.h"
50
51 extern grpc_core::TraceFlag grpc_tcp_trace;
52
53 using ::grpc_event_engine::experimental::EndpointConfig;
54
55 struct async_connect {
56 gpr_mu mu;
57 grpc_fd* fd;
58 grpc_timer alarm;
59 grpc_closure on_alarm;
60 int refs;
61 grpc_closure write_closure;
62 grpc_pollset_set* interested_parties;
63 std::string addr_str;
64 grpc_endpoint** ep;
65 grpc_closure* closure;
66 int64_t connection_handle;
67 bool connect_cancelled;
68 grpc_core::PosixTcpOptions options;
69 };
70
71 struct ConnectionShard {
72 grpc_core::Mutex mu;
73 absl::flat_hash_map<int64_t, async_connect*> pending_connections
74 ABSL_GUARDED_BY(&mu);
75 };
76
77 namespace {
78
79 gpr_once g_tcp_client_posix_init = GPR_ONCE_INIT;
80 std::vector<ConnectionShard>* g_connection_shards = nullptr;
81 std::atomic<int64_t> g_connection_id{1};
82
83 void do_tcp_client_global_init(void) {
84 size_t num_shards = std::max(2 * gpr_cpu_num_cores(), 1u);
85 g_connection_shards = new std::vector<struct ConnectionShard>(num_shards);
86 }
87
88 } // namespace
89
90 void grpc_tcp_client_global_init() {
91 gpr_once_init(&g_tcp_client_posix_init, do_tcp_client_global_init);
92 }
93
94 static grpc_error_handle prepare_socket(
95 const grpc_resolved_address* addr, int fd,
96 const grpc_core::PosixTcpOptions& options) {
97 grpc_error_handle err;
98
99 GPR_ASSERT(fd >= 0);
100
101 err = grpc_set_socket_nonblocking(fd, 1);
102 if (!err.ok()) goto error;
103 err = grpc_set_socket_cloexec(fd, 1);
104 if (!err.ok()) goto error;
105 if (!grpc_is_unix_socket(addr)) {
106 err = grpc_set_socket_low_latency(fd, 1);
107 if (!err.ok()) goto error;
108 err = grpc_set_socket_reuse_addr(fd, 1);
109 if (!err.ok()) goto error;
110 err = grpc_set_socket_tcp_user_timeout(fd, options, true /* is_client */);
111 if (!err.ok()) goto error;
112 }
113 err = grpc_set_socket_no_sigpipe_if_possible(fd);
114 if (!err.ok()) goto error;
115
116 err = grpc_apply_socket_mutator_in_args(fd, GRPC_FD_CLIENT_CONNECTION_USAGE,
117 options);
118 if (!err.ok()) goto error;
119
120 goto done;
121
122 error:
123 if (fd >= 0) {
124 close(fd);
125 }
126 done:
127 return err;
128 }
129
130 static void tc_on_alarm(void* acp, grpc_error_handle error) {
131 int done;
132 async_connect* ac = static_cast<async_connect*>(acp);
133 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
134 gpr_log(GPR_INFO, "CLIENT_CONNECT: %s: on_alarm: error=%s",
135 ac->addr_str.c_str(), grpc_core::StatusToString(error).c_str());
136 }
137 gpr_mu_lock(&ac->mu);
138 if (ac->fd != nullptr) {
139 grpc_fd_shutdown(ac->fd, GRPC_ERROR_CREATE("connect() timed out"));
140 }
141 done = (--ac->refs == 0);
142 gpr_mu_unlock(&ac->mu);
143 if (done) {
144 gpr_mu_destroy(&ac->mu);
145 delete ac;
146 }
147 }
148
149 static grpc_endpoint* grpc_tcp_client_create_from_fd(
150 grpc_fd* fd, const grpc_core::PosixTcpOptions& options,
151 absl::string_view addr_str) {
152 return grpc_tcp_create(fd, options, addr_str);
153 }
154
155 grpc_endpoint* grpc_tcp_create_from_fd(
156 grpc_fd* fd, const grpc_event_engine::experimental::EndpointConfig& config,
157 absl::string_view addr_str) {
158 return grpc_tcp_create(fd, TcpOptionsFromEndpointConfig(config), addr_str);
159 }
160
161 static void on_writable(void* acp, grpc_error_handle error) {
162 async_connect* ac = static_cast<async_connect*>(acp);
163 int so_error = 0;
164 socklen_t so_error_size;
165 int err;
166 int done;
167 grpc_endpoint** ep = ac->ep;
168 grpc_closure* closure = ac->closure;
169 std::string addr_str = ac->addr_str;
170 grpc_fd* fd;
171
172 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
173 gpr_log(GPR_INFO, "CLIENT_CONNECT: %s: on_writable: error=%s",
174 ac->addr_str.c_str(), grpc_core::StatusToString(error).c_str());
175 }
176
177 gpr_mu_lock(&ac->mu);
178 GPR_ASSERT(ac->fd);
179 fd = ac->fd;
180 ac->fd = nullptr;
181 bool connect_cancelled = ac->connect_cancelled;
182 gpr_mu_unlock(&ac->mu);
183
184 grpc_timer_cancel(&ac->alarm);
185
186 gpr_mu_lock(&ac->mu);
187 if (!error.ok()) {
188 error = grpc_error_set_str(error, grpc_core::StatusStrProperty::kOsError,
189 "Timeout occurred");
190 goto finish;
191 }
192
193 if (connect_cancelled) {
194 // The callback should not get scheduled in this case.
195 error = absl::OkStatus();
196 goto finish;
197 }
198
199 do {
200 so_error_size = sizeof(so_error);
201 err = getsockopt(grpc_fd_wrapped_fd(fd), SOL_SOCKET, SO_ERROR, &so_error,
202 &so_error_size);
203 } while (err < 0 && errno == EINTR);
204 if (err < 0) {
205 error = GRPC_OS_ERROR(errno, "getsockopt");
206 goto finish;
207 }
208
209 switch (so_error) {
210 case 0:
211 grpc_pollset_set_del_fd(ac->interested_parties, fd);
212 *ep = grpc_tcp_client_create_from_fd(fd, ac->options, ac->addr_str);
213 fd = nullptr;
214 break;
215 case ENOBUFS:
216 /* We will get one of these errors if we have run out of
217 memory in the kernel for the data structures allocated
218 when you connect a socket. If this happens it is very
219 likely that if we wait a little bit then try again the
220 connection will work (since other programs or this
221 program will close their network connections and free up
222 memory). This does _not_ indicate that there is anything
223 wrong with the server we are connecting to, this is a
224 local problem.
225
226 If you are looking at this code, then chances are that
227 your program or another program on the same computer
228 opened too many network connections. The "easy" fix:
229 don't do that! */
230 gpr_log(GPR_ERROR, "kernel out of buffers");
231 gpr_mu_unlock(&ac->mu);
232 grpc_fd_notify_on_write(fd, &ac->write_closure);
233 return;
234 case ECONNREFUSED:
235 /* This error shouldn't happen for anything other than connect(). */
236 error = GRPC_OS_ERROR(so_error, "connect");
237 break;
238 default:
239 /* We don't really know which syscall triggered the problem here,
240 so punt by reporting getsockopt(). */
241 error = GRPC_OS_ERROR(so_error, "getsockopt(SO_ERROR)");
242 break;
243 }
244
245 finish:
246 if (!connect_cancelled) {
247 int shard_number = ac->connection_handle % (*g_connection_shards).size();
248 struct ConnectionShard* shard = &(*g_connection_shards)[shard_number];
249 {
250 grpc_core::MutexLock lock(&shard->mu);
251 shard->pending_connections.erase(ac->connection_handle);
252 }
253 }
254 if (fd != nullptr) {
255 grpc_pollset_set_del_fd(ac->interested_parties, fd);
256 grpc_fd_orphan(fd, nullptr, nullptr, "tcp_client_orphan");
257 fd = nullptr;
258 }
259 done = (--ac->refs == 0);
260 gpr_mu_unlock(&ac->mu);
261 if (!error.ok()) {
262 std::string str;
263 bool ret = grpc_error_get_str(
264 error, grpc_core::StatusStrProperty::kDescription, &str);
265 GPR_ASSERT(ret);
266 std::string description =
267 absl::StrCat("Failed to connect to remote host: ", str);
268 error = grpc_error_set_str(
269 error, grpc_core::StatusStrProperty::kDescription, description);
270 error = grpc_error_set_str(
271 error, grpc_core::StatusStrProperty::kTargetAddress, addr_str);
272 }
273 if (done) {
274 // This is safe even outside the lock, because "done", the sentinel, is
275 // populated *inside* the lock.
276 gpr_mu_destroy(&ac->mu);
277 delete ac;
278 }
279 // Push async connect closure to the executor since this may actually be
280 // called during the shutdown process, in which case a deadlock could form
281 // between the core shutdown mu and the connector mu (b/188239051)
282 if (!connect_cancelled) {
283 grpc_core::Executor::Run(closure, error);
284 }
285 }
286
287 grpc_error_handle grpc_tcp_client_prepare_fd(
288 const grpc_core::PosixTcpOptions& options,
289 const grpc_resolved_address* addr, grpc_resolved_address* mapped_addr,
290 int* fd) {
291 grpc_dualstack_mode dsmode;
292 grpc_error_handle error;
293 *fd = -1;
294 /* Use dualstack sockets where available. Set mapped to v6 or v4 mapped to
295 v6. */
296 if (!grpc_sockaddr_to_v4mapped(addr, mapped_addr)) {
297 /* addr is v4 mapped to v6 or v6. */
298 memcpy(mapped_addr, addr, sizeof(*mapped_addr));
299 }
300 error =
301 grpc_create_dualstack_socket(mapped_addr, SOCK_STREAM, 0, &dsmode, fd);
302 if (!error.ok()) {
303 return error;
304 }
305 if (dsmode == GRPC_DSMODE_IPV4) {
306 /* Original addr is either v4 or v4 mapped to v6. Set mapped_addr to v4. */
307 if (!grpc_sockaddr_is_v4mapped(addr, mapped_addr)) {
308 memcpy(mapped_addr, addr, sizeof(*mapped_addr));
309 }
310 }
311 if ((error = prepare_socket(mapped_addr, *fd, options)) != absl::OkStatus()) {
312 return error;
313 }
314 return absl::OkStatus();
315 }
316
317 int64_t grpc_tcp_client_create_from_prepared_fd(
318 grpc_pollset_set* interested_parties, grpc_closure* closure, const int fd,
319 const grpc_core::PosixTcpOptions& options,
320 const grpc_resolved_address* addr, grpc_core::Timestamp deadline,
321 grpc_endpoint** ep) {
322 int err;
323 do {
324 err = connect(fd, reinterpret_cast<const grpc_sockaddr*>(addr->addr),
325 addr->len);
326 } while (err < 0 && errno == EINTR);
327
328 auto addr_uri = grpc_sockaddr_to_uri(addr);
329 if (!addr_uri.ok()) {
330 grpc_error_handle error = GRPC_ERROR_CREATE(addr_uri.status().ToString());
331 grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error);
332 return 0;
333 }
334
335 std::string name = absl::StrCat("tcp-client:", addr_uri.value());
336 grpc_fd* fdobj = grpc_fd_create(fd, name.c_str(), true);
337 int64_t connection_id = 0;
338 if (errno == EWOULDBLOCK || errno == EINPROGRESS) {
339 // Connection is still in progress.
340 connection_id = g_connection_id.fetch_add(1, std::memory_order_acq_rel);
341 }
342
343 if (err >= 0) {
344 // Connection already succeded. Return 0 to discourage any cancellation
345 // attempts.
346 *ep = grpc_tcp_client_create_from_fd(fdobj, options, addr_uri.value());
347 grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, absl::OkStatus());
348 return 0;
349 }
350 if (errno != EWOULDBLOCK && errno != EINPROGRESS) {
351 // Connection already failed. Return 0 to discourage any cancellation
352 // attempts.
353 grpc_error_handle error = GRPC_OS_ERROR(errno, "connect");
354 error = grpc_error_set_str(
355 error, grpc_core::StatusStrProperty::kTargetAddress, addr_uri.value());
356 grpc_fd_orphan(fdobj, nullptr, nullptr, "tcp_client_connect_error");
357 grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error);
358 return 0;
359 }
360
361 grpc_pollset_set_add_fd(interested_parties, fdobj);
362
363 async_connect* ac = new async_connect();
364 ac->closure = closure;
365 ac->ep = ep;
366 ac->fd = fdobj;
367 ac->interested_parties = interested_parties;
368 ac->addr_str = addr_uri.value();
369 ac->connection_handle = connection_id;
370 ac->connect_cancelled = false;
371 gpr_mu_init(&ac->mu);
372 ac->refs = 2;
373 GRPC_CLOSURE_INIT(&ac->write_closure, on_writable, ac,
374 grpc_schedule_on_exec_ctx);
375 ac->options = options;
376
377 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
378 gpr_log(GPR_INFO, "CLIENT_CONNECT: %s: asynchronously connecting fd %p",
379 ac->addr_str.c_str(), fdobj);
380 }
381
382 int shard_number = connection_id % (*g_connection_shards).size();
383 struct ConnectionShard* shard = &(*g_connection_shards)[shard_number];
384 {
385 grpc_core::MutexLock lock(&shard->mu);
386 shard->pending_connections.insert_or_assign(connection_id, ac);
387 }
388
389 gpr_mu_lock(&ac->mu);
390 GRPC_CLOSURE_INIT(&ac->on_alarm, tc_on_alarm, ac, grpc_schedule_on_exec_ctx);
391 grpc_timer_init(&ac->alarm, deadline, &ac->on_alarm);
392 grpc_fd_notify_on_write(ac->fd, &ac->write_closure);
393 gpr_mu_unlock(&ac->mu);
394 return connection_id;
395 }
396
397 static int64_t tcp_connect(grpc_closure* closure, grpc_endpoint** ep,
398 grpc_pollset_set* interested_parties,
399 const EndpointConfig& config,
400 const grpc_resolved_address* addr,
401 grpc_core::Timestamp deadline) {
402 grpc_resolved_address mapped_addr;
403 grpc_core::PosixTcpOptions options(TcpOptionsFromEndpointConfig(config));
404 int fd = -1;
405 grpc_error_handle error;
406 *ep = nullptr;
407 if ((error = grpc_tcp_client_prepare_fd(options, addr, &mapped_addr, &fd)) !=
408 absl::OkStatus()) {
409 grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error);
410 return 0;
411 }
412 return grpc_tcp_client_create_from_prepared_fd(
413 interested_parties, closure, fd, options, &mapped_addr, deadline, ep);
414 }
415
416 static bool tcp_cancel_connect(int64_t connection_handle) {
417 if (connection_handle <= 0) {
418 return false;
419 }
420 int shard_number = connection_handle % (*g_connection_shards).size();
421 struct ConnectionShard* shard = &(*g_connection_shards)[shard_number];
422 async_connect* ac = nullptr;
423 {
424 grpc_core::MutexLock lock(&shard->mu);
425 auto it = shard->pending_connections.find(connection_handle);
426 if (it != shard->pending_connections.end()) {
427 ac = it->second;
428 GPR_ASSERT(ac != nullptr);
429 // Trying to acquire ac->mu here would could cause a deadlock because
430 // the on_writable method tries to acquire the two mutexes used
431 // here in the reverse order. But we dont need to acquire ac->mu before
432 // incrementing ac->refs here. This is because the on_writable
433 // method decrements ac->refs only after deleting the connection handle
434 // from the corresponding hashmap. If the code enters here, it means that
435 // deletion hasn't happened yet. The deletion can only happen after the
436 // corresponding g_shard_mu is unlocked.
437 ++ac->refs;
438 // Remove connection from list of active connections.
439 shard->pending_connections.erase(it);
440 }
441 }
442 if (ac == nullptr) {
443 return false;
444 }
445 gpr_mu_lock(&ac->mu);
446 bool connection_cancel_success = (ac->fd != nullptr);
447 if (connection_cancel_success) {
448 // Connection is still pending. The on_writable callback hasn't executed
449 // yet because ac->fd != nullptr.
450 ac->connect_cancelled = true;
451 // Shutdown the fd. This would cause on_writable to run as soon as possible.
452 // We dont need to pass a custom error here because it wont be used since
453 // the on_connect_closure is not run if connect cancellation is successfull.
454 grpc_fd_shutdown(ac->fd, absl::OkStatus());
455 }
456 bool done = (--ac->refs == 0);
457 gpr_mu_unlock(&ac->mu);
458 if (done) {
459 // This is safe even outside the lock, because "done", the sentinel, is
460 // populated *inside* the lock.
461 gpr_mu_destroy(&ac->mu);
462 delete ac;
463 }
464 return connection_cancel_success;
465 }
466
467 grpc_tcp_client_vtable grpc_posix_tcp_client_vtable = {tcp_connect,
468 tcp_cancel_connect};
469 #endif