Skip to content

Commit 45f1e10

Browse files
authored
network: restore the network namespace when listener socket setup throws (#48392)
1 parent 9ceed47 commit 45f1e10

5 files changed

Lines changed: 118 additions & 13 deletions

File tree

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Fixed a listener with a ``network_namespace_filepath`` leaving the main thread in that network
2+
namespace when setting up its socket failed, for example because the address was already in use.
3+
The main thread then kept creating its sockets in that namespace, such as those of other listeners
4+
and of xDS and health check connections. Worker threads started afterwards inherited it as well.

‎source/common/network/utility.h‎

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -368,7 +368,7 @@ class Utility {
368368
/**
369369
* Changes the calling thread's network namespace to the one referenced by the file at `netns`,
370370
* calls the function `f`, and returns its result after switching back to the original network
371-
* namespace.
371+
* namespace. It also switches back if `f` throws.
372372
*
373373
* @param f the function to execute in the specified network namespace.
374374
* @param netns filepath referencing the network namespace in which `f` is executed.
@@ -391,7 +391,7 @@ class Utility {
391391
return absl::InternalError(fmt::format("failed to open netns file {}: {}", curr_netns_file,
392392
errorDetails(og_netns_fd_result.errno_)));
393393
}
394-
Cleanup cleanup_og_fd([&og_netns_fd, &posix]() { posix.close(og_netns_fd); });
394+
Cleanup cleanup_og_fd([og_netns_fd, &posix]() { posix.close(og_netns_fd); });
395395

396396
// Open the fd for the network namespace we want the socket in.
397397
auto netns_fd_result = posix.open(netns, O_RDONLY);
@@ -400,7 +400,7 @@ class Utility {
400400
return absl::InternalError(fmt::format("failed to open netns file {}: {}", netns,
401401
errorDetails(netns_fd_result.errno_)));
402402
}
403-
Cleanup cleanup_netns_fd([&posix, &netns_fd]() { posix.close(netns_fd); });
403+
Cleanup cleanup_netns_fd([&posix, netns_fd]() { posix.close(netns_fd); });
404404

405405
// Change the network namespace of this thread.
406406
auto setns_result = Api::LinuxOsSysCallsSingleton().get().setns(netns_fd, CLONE_NEWNET);
@@ -409,18 +409,21 @@ class Utility {
409409
netns_fd, errorDetails(errno)));
410410
}
411411

412-
// Calling function from the specified network namespace.
413-
auto result = std::forward<Func>(f)();
412+
// Restore the original network namespace even if `f` throws.
413+
Cleanup restore_og_netns([og_netns_fd, netns_fd]() {
414+
const auto restore_result =
415+
Api::LinuxOsSysCallsSingleton().get().setns(og_netns_fd, CLONE_NEWNET);
414416

415-
// Restore the original network namespace before returning the function result.
416-
setns_result = Api::LinuxOsSysCallsSingleton().get().setns(og_netns_fd, CLONE_NEWNET);
417+
// If we cannot jump back into the original network namespace, this is an unrecoverable
418+
// error. It would leave the current thread in another network namespace indefinitely, so we
419+
// cannot continue running in that state.
420+
RELEASE_ASSERT(restore_result.return_value_ == 0,
421+
fmt::format("failed to restore original netns (fd={}): {}", netns_fd,
422+
errorDetails(errno)));
423+
});
417424

418-
// If we cannot jump back into the original network namespace, this is an unrecoverable error.
419-
// It would leave the current thread in another network namespace indefinitely, so we cannot
420-
// continue running in that state.
421-
RELEASE_ASSERT(
422-
setns_result.return_value_ == 0,
423-
fmt::format("failed to restore original netns (fd={}): {}", netns_fd, errorDetails(errno)));
425+
// Calling function from the specified network namespace.
426+
auto result = std::forward<Func>(f)();
424427

425428
return result;
426429
}

‎test/common/network/utility_test.cc‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -990,6 +990,31 @@ TEST_F(ExecInNetnsTest, Basic) {
990990
EXPECT_EQ(getCurrentNetns(), "/proc/thread-self/ns/net");
991991
}
992992

993+
TEST_F(ExecInNetnsTest, RestoresOriginalNetnsWhenCallbackThrows) {
994+
// Make the tests use mock syscalls.
995+
testing::StrictMock<Api::MockLinuxOsSysCalls> linux_os_syscalls;
996+
testing::StrictMock<Api::MockOsSysCalls> os_syscalls;
997+
TestThreadsafeSingletonInjector<Api::OsSysCallsImpl> os_calls(&os_syscalls);
998+
TestThreadsafeSingletonInjector<Api::LinuxOsSysCallsImpl> linux_os_calls(&linux_os_syscalls);
999+
1000+
testing::InSequence s;
1001+
EXPECT_CALL(os_syscalls, open(testing::StrEq("/proc/thread-self/ns/net"), O_RDONLY))
1002+
.WillOnce(Return(Api::SysCallIntResult{1337, 0}));
1003+
EXPECT_CALL(os_syscalls, open(testing::StrEq("ns1"), O_RDONLY))
1004+
.WillOnce(Return(Api::SysCallIntResult{1338, 0}));
1005+
EXPECT_CALL(linux_os_syscalls, setns(1338, CLONE_NEWNET))
1006+
.WillOnce(Return(Api::SysCallIntResult{0, 0}));
1007+
// The original netns is restored before its fd is closed.
1008+
EXPECT_CALL(linux_os_syscalls, setns(1337, CLONE_NEWNET))
1009+
.WillOnce(Return(Api::SysCallIntResult{0, 0}));
1010+
EXPECT_CALL(os_syscalls, close(1338)).WillOnce(Return(Api::SysCallIntResult{0, 0}));
1011+
EXPECT_CALL(os_syscalls, close(1337)).WillOnce(Return(Api::SysCallIntResult{0, 0}));
1012+
1013+
EXPECT_THROW_WITH_MESSAGE(std::ignore = Utility::execInNetworkNamespace(
1014+
[]() -> int { throw EnvoyException("callback failed"); }, "ns1"),
1015+
EnvoyException, "callback failed");
1016+
}
1017+
9931018
TEST_F(ExecInNetnsTest, OpenFail) {
9941019
// Make the tests use mock syscalls.
9951020
testing::StrictMock<Api::MockLinuxOsSysCalls> linux_os_syscalls;
@@ -1008,6 +1033,28 @@ TEST_F(ExecInNetnsTest, OpenFail) {
10081033
EXPECT_THAT(result, HasStatusMessage(testing::StartsWith("failed to open netns file")));
10091034
}
10101035

1036+
TEST_F(ExecInNetnsTest, SetnsFail) {
1037+
// Make the tests use mock syscalls.
1038+
testing::StrictMock<Api::MockLinuxOsSysCalls> linux_os_syscalls;
1039+
testing::StrictMock<Api::MockOsSysCalls> os_syscalls;
1040+
TestThreadsafeSingletonInjector<Api::OsSysCallsImpl> os_calls(&os_syscalls);
1041+
TestThreadsafeSingletonInjector<Api::LinuxOsSysCallsImpl> linux_os_calls(&linux_os_syscalls);
1042+
1043+
testing::InSequence s;
1044+
EXPECT_CALL(os_syscalls, open(testing::StrEq("/proc/thread-self/ns/net"), O_RDONLY))
1045+
.WillOnce(Return(Api::SysCallIntResult{1337, 0}));
1046+
EXPECT_CALL(os_syscalls, open(testing::StrEq("ns1"), O_RDONLY))
1047+
.WillOnce(Return(Api::SysCallIntResult{1338, 0}));
1048+
// The thread never left its netns, so there is nothing to restore.
1049+
EXPECT_CALL(linux_os_syscalls, setns(1338, CLONE_NEWNET))
1050+
.WillOnce(Return(Api::SysCallIntResult{-1, EPERM}));
1051+
EXPECT_CALL(os_syscalls, close(1338)).WillOnce(Return(Api::SysCallIntResult{0, 0}));
1052+
EXPECT_CALL(os_syscalls, close(1337)).WillOnce(Return(Api::SysCallIntResult{0, 0}));
1053+
1054+
auto result = Utility::execInNetworkNamespace([]() -> int { return 0; }, "ns1");
1055+
EXPECT_THAT(result, HasStatusMessage(testing::StartsWith("failed to set netns to ns1")));
1056+
}
1057+
10111058
TEST_F(ExecInNetnsTest, FailtoReturnToOriginalNetns) {
10121059
EXPECT_DEATH(
10131060
{

‎test/integration/BUILD‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1764,6 +1764,7 @@ envoy_cc_test(
17641764
":http_integration_lib",
17651765
":integration_test_lib",
17661766
"//envoy/registry",
1767+
"//source/common/api:os_sys_calls_lib",
17671768
"//source/common/common:cpu_affinity_lib",
17681769
"//source/common/http:header_map_lib",
17691770
"//source/common/http:headers_lib",
@@ -1780,6 +1781,7 @@ envoy_cc_test(
17801781
"//test/integration/filters:stop_iteration_and_continue",
17811782
"//test/mocks/http:http_mocks",
17821783
"//test/test_common:registry_lib",
1784+
"//test/test_common:threadsafe_singleton_injector_lib",
17831785
"//test/test_common:utility_lib",
17841786
"@envoy_api//envoy/config/bootstrap/v3:pkg_cc_proto",
17851787
"@envoy_api//envoy/config/listener/v3:pkg_cc_proto",

‎test/integration/integration_test.cc‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@
88
#include "envoy/extensions/filters/network/http_connection_manager/v3/http_connection_manager.pb.h"
99
#include "envoy/registry/registry.h"
1010

11+
#if defined(__linux__)
12+
#include "source/common/api/os_sys_calls_impl_linux.h"
13+
#endif
1114
#include "source/common/common/cpu_affinity.h"
1215
#include "source/common/http/header_map_impl.h"
1316
#include "source/common/http/headers.h"
@@ -24,6 +27,7 @@
2427
#include "test/test_common/network_utility.h"
2528
#include "test/test_common/printers.h"
2629
#include "test/test_common/registry.h"
30+
#include "test/test_common/threadsafe_singleton_injector.h"
2731
#include "test/test_common/utility.h"
2832

2933
#include "gtest/gtest.h"
@@ -127,6 +131,51 @@ TEST_P(IntegrationTest, BadPostListenSocketOption) {
127131
test_server_->waitForCounter("listener_manager.listener_create_failure", Ge(1));
128132
}
129133

134+
#if defined(__linux__)
135+
// Entering a network namespace requires CAP_SYS_ADMIN, so setns() is faked and only counted.
136+
class FakeSetns : public Api::LinuxOsSysCallsImpl {
137+
public:
138+
Api::SysCallIntResult setns(int, int) const override {
139+
calls_++;
140+
return {0, 0};
141+
}
142+
143+
uint32_t calls() const { return calls_; }
144+
145+
private:
146+
mutable std::atomic<uint32_t> calls_{0};
147+
};
148+
149+
// Verify that the main thread leaves the network namespace of a listener that fails to bind there.
150+
TEST_P(IntegrationTest, BindFailureInNetworkNamespace) {
151+
FakeSetns fake_setns;
152+
TestThreadsafeSingletonInjector<Api::LinuxOsSysCallsImpl> linux_os_calls{&fake_setns};
153+
// The namespace file only has to exist since setns() is faked.
154+
const std::string netns_path = TestEnvironment::writeStringToFileForTest("netns", "");
155+
// Reserve a port without reuse_port so that the listener fails to bind it.
156+
auto addr_socket =
157+
Network::Test::bindFreeLoopbackPort(version_, Network::Socket::Type::Stream, false);
158+
// Do not wait for listeners to start as the listener will fail.
159+
defer_listener_finalization_ = true;
160+
161+
config_helper_.addConfigModifier([&](envoy::config::bootstrap::v3::Bootstrap& bootstrap) -> void {
162+
auto* socket_address = bootstrap.mutable_static_resources()
163+
->mutable_listeners(0)
164+
->mutable_address()
165+
->mutable_socket_address();
166+
socket_address->set_port_value(
167+
addr_socket.second->connectionInfoProvider().localAddress()->ip()->port());
168+
socket_address->set_network_namespace_filepath(netns_path);
169+
});
170+
initialize();
171+
test_server_->waitForCounter("listener_manager.listener_create_failure", Ge(1));
172+
// One call enters the network namespace and one leaves it.
173+
EXPECT_EQ(2, fake_setns.calls());
174+
// Shut down the server before linux_os_calls and fake_setns go out of scope.
175+
test_server_.reset();
176+
}
177+
#endif
178+
130179
// Make sure we have correctly specified per-worker performance stats.
131180
TEST_P(IntegrationTest, PerWorkerStatsAndBalancing) {
132181
DISABLE_IF_ADMIN_DISABLED; // Uses admin stats

0 commit comments

Comments
 (0)