Files
spark/src/lib/orderman/ilink3/IL3Reactor.cpp
T

245 lines
7.2 KiB
C++

#include "IL3Reactor.h"
#include "IL3ReceiveBuffer.h"
#include "lib/tracing/PerfLog.h"
#include "lib/utils/bts_assert.h"
#include <arpa/inet.h>
#include <array>
#include <fcntl.h>
#include <fstream>
#include <netinet/tcp.h>
#include <queue>
#include <stdlib.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
namespace bts {
namespace orderman {
namespace ilink3 {
struct IL3Reactor::Connection : public IL3Connection {
int epoll_fd;
int fd;
bool is_connected;
IL3ConnectionHandler *handler;
std::queue<TCPEndpoint> end_points;
IL3ReceiveBuffer rc_buffer;
Connection(int epoll_fd, const std::vector<TCPEndpoint> &end_points)
: epoll_fd(epoll_fd), fd(0), is_connected(false), handler(nullptr),
end_points(
std::deque<TCPEndpoint>{end_points.begin(), end_points.end()}),
rc_buffer() {}
~Connection() {
if (is_connected)
disconnect();
}
void connect(IL3ConnectionHandler &h) override {
bts_assert(!is_connected);
handler = &h;
fd = socket(AF_INET, SOCK_STREAM, 0);
int flag = 1;
auto result = ::setsockopt(
fd, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(int));
bts_assert(result == 0);
bts_assert(fd >= 0);
struct sockaddr_in serv_addr;
memset(&serv_addr, '0', sizeof(serv_addr));
auto end_point = current_end_point();
auto &host = end_point.host;
auto port = end_point.port;
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
result = inet_pton(AF_INET, host.c_str(), &serv_addr.sin_addr);
bts_assert(result > 0);
result = ::connect(fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
if (result < 0) {
auto er = errno;
char msg[256];
LOG(iLink3, Error, "Failed to connect: {} {}:{}",
std::string(strerror_r(er, msg, sizeof(msg))), host, port);
disconnect();
} else {
int flag = 1;
result = ::setsockopt(
fd, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(int));
bts_assert(result == 0);
epoll_event ev;
ev.events = EPOLLIN | EPOLLHUP | EPOLLERR | EPOLLRDHUP;
ev.data.ptr = this;
auto result = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev);
bts_assert_msg(result == 0, "epoll");
is_connected = true;
handler->on_connect_success();
}
}
void disconnect() override {
if (fd)
close(fd);
fd = 0;
is_connected = false;
handler->on_disconnect();
}
void send(const std::string_view data) override {
if (!is_connected) {
LOG(iLink3, Error, "Attempted to send on closed connection. {}:{}",
current_end_point().host, current_end_point().port);
return;
}
auto result = write(fd, data.data(), data.size());
if (result < 0) {
auto er = errno;
char msg[256];
auto host = current_end_point().host;
auto port = current_end_point().port;
LOG(iLink3, Warn, "Could not write to reactor connection. {}:{}",
std::string(strerror_r(er, msg, sizeof(msg))), host, port);
disconnect();
}
}
void send(const std::vector<std::string_view> &dt, trace::CorID const &corid)
override {
if (!is_connected) {
LOG(iLink3, Error, "Attempted to send on closed connection. {}:{}",
current_end_point().host, current_end_point().port);
return;
}
iovec *iv = (iovec *)alloca(sizeof(iovec) * dt.size());
for (size_t i = 0; i < dt.size(); i++) {
iv[i].iov_base = (void *)dt[i].data();
iv[i].iov_len = dt[i].size();
}
auto before_write = utils::TimeStamp::now();
auto result = ::writev(fd, iv, dt.size());
LOG(Latency, Info,
"entry_type:socket_write channel:{} sn:{} app_arrival:{} now:{} "
"delta:{}",
log::CharPtrWrapper{corid.channel}, corid.sn,
corid.app_arrival.to_uint64(), before_write.to_uint64(),
(before_write - corid.app_arrival).nanoseconds());
if (result < 0) {
auto er = errno;
char msg[256];
auto host = current_end_point().host;
auto port = current_end_point().port;
LOG(iLink3, Warn, "Could not write to reactor connection. {}:{}",
std::string(strerror_r(er, msg, sizeof(msg))), host, port);
disconnect();
}
}
void on_data(const std::string_view data) {
bts_assert_d(is_connected);
// Copy input data into a permanent buffer
rc_buffer.append(data);
bts_assert_d(rc_buffer.unread() > 0);
auto read = handler->on_data(rc_buffer.data());
rc_buffer.advance(read);
}
void failover() override {
bts_assert(!is_connected);
next_end_point();
}
TCPEndpoint current_end_point() { return end_points.front(); }
void next_end_point() {
auto next = end_points.front();
end_points.pop();
end_points.push(next);
}
};
struct IL3Reactor::PImpl {
int epoll_fd = -1;
std::vector<std::unique_ptr<Connection>> connections;
};
IL3Reactor::IL3Reactor() : me(new PImpl()) {
me->epoll_fd = epoll_create(100);
bts_assert(me->epoll_fd >= 0);
}
IL3Reactor::~IL3Reactor() {
me->connections.clear();
close(me->epoll_fd);
me->epoll_fd = -1;
}
IL3Connection &
IL3Reactor::register_connection(const std::vector<TCPEndpoint> &end_points) {
me->connections.emplace_back(
std::make_unique<Connection>(me->epoll_fd, end_points));
return *me->connections.back();
}
[[gnu::noinline]] void non_inline_assert() { bts_assert(false); }
constexpr bool has_error(int events) {
return events & (EPOLLHUP | EPOLLERR | EPOLLRDHUP);
}
void IL3Reactor::do_work() {
std::array<epoll_event, 100> ev_list;
#ifndef __clang__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
#endif
// A bug in gcc causes bogus errors related to 'unitialized' variables
// (particularly when accessing array<T>::size).
// https://cplusplus.com/forum/beginner/22044/
auto ready = epoll_wait(me->epoll_fd, ev_list.data(), ev_list.size(), 0);
#ifndef __clang__
#pragma GCC diagnostic pop
#endif
if (ready == -1) {
if (errno == EINTR)
return;
else
non_inline_assert();
}
for (int i = 0; i < ready; ++i) {
auto &ev = ev_list[i];
auto handler = (Connection *)(ev.data.ptr);
if (ev.events & EPOLLIN) {
char buffer[4096];
auto sz = read(handler->fd, buffer, sizeof(buffer));
if (sz > 0) {
bts_assert_d(handler->is_connected);
handler->on_data(std::string_view(buffer, sz));
} else if (has_error(ev.events)) {
handler->disconnect();
}
} else if (has_error(ev.events)) {
// if EPOLLIN was set along with
// EPOLLHUP/EPOLLERR/EPOLLRDHUP, we pretend it is a normal
// read so that we drain the bytes in the socket. The error
// or hup condition would remain and we would catch in the
// next iteration.
handler->disconnect();
}
}
}
} // namespace ilink3
} // namespace orderman
} // namespace bts