Skip to content

Commit c1083ad

Browse files
d4l3kfacebook-github-bot
authored andcommitted
gloo/tcp/attr: hold on to bound socket to avoid port conflict issues (#429)
Summary: This is a minor refactor to attr in the TCP backend for Gloo so that we don't close the bound fd between allocating it in `lookupAddrForHostname` and binding it in `Listener`. Listener sets `SO_REUSEADDR` so it's fine for us to bind twice to the same address but we will only listen on it in `Listener`. Reviewed By: fduwjj Differential Revision: D73148977
1 parent c610704 commit c1083ad

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

gloo/transport/tcp/attr.h

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,30 @@
1111
#include <string>
1212

1313
#include <sys/socket.h>
14+
#include <unistd.h>
15+
#include <memory>
1416

1517
namespace gloo {
1618
namespace transport {
1719
namespace tcp {
1820

21+
// RAII for fds so they'll close when all references to them are freed.
22+
class FDHolder {
23+
public:
24+
explicit FDHolder(int fd) : fd_(fd) {}
25+
~FDHolder() {
26+
close(fd_);
27+
}
28+
29+
FDHolder(const FDHolder&) = delete;
30+
FDHolder& operator=(const FDHolder&) = delete;
31+
FDHolder(FDHolder&&) = delete;
32+
FDHolder& operator=(FDHolder&&) = delete;
33+
34+
private:
35+
const int fd_;
36+
};
37+
1938
struct attr {
2039
attr() {}
2140
/* implicit */ attr(const char* ptr) : hostname(ptr) {}
@@ -31,6 +50,8 @@ struct attr {
3150
int ai_protocol;
3251
struct sockaddr_storage ai_addr;
3352
int ai_addrlen;
53+
54+
std::shared_ptr<FDHolder> fd{nullptr};
3455
};
3556

3657
} // namespace tcp

gloo/transport/tcp/device.cc

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,10 @@ static void lookupAddrForHostname(struct attr& attr) {
117117
attr.ai_protocol = rp->ai_protocol;
118118
memcpy(&attr.ai_addr, rp->ai_addr, rp->ai_addrlen);
119119
attr.ai_addrlen = rp->ai_addrlen;
120-
close(fd);
120+
121+
// We explicitly don't close this FD here as we want to hold on to it until
122+
// the listener binds the server socket to the port.
123+
attr.fd = std::make_shared<FDHolder>(fd);
121124
break;
122125
}
123126

0 commit comments

Comments
 (0)