1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
|
#include <algorithm>
#include <deque>
#include <exception>
#include <memory>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include <c10/util/thread_name.h>
#include <fmt/format.h>
#include <torch/csrc/distributed/c10d/TCPStore.hpp>
#include <torch/csrc/distributed/c10d/TCPStoreBackend.hpp>
#include <torch/csrc/distributed/c10d/logging.h>
#include <torch/csrc/distributed/c10d/socket_fmt.h>
#ifdef TORCH_USE_LIBUV
#include <uv.h>
#endif
namespace c10d::detail {
#ifdef TORCH_USE_LIBUV
/*
Exception safety:
It's ok to use exceptions during client processing.
Other callbacks don't provide exception safety so avoid there.
*/
// This controls how many un-accepted TCP connections can be waiting in the
// backlog. This should be at least world size to avoid issues on init. We set
// it to -1 to use the host max value which is controlled by `soconnmax`.
auto constexpr DEFAULT_BACKLOG = -1;
auto constexpr MAX_KEY_COUNT = size_t(128 * 1024);
auto constexpr MAX_STRING_LEN = 8 * 1024;
auto constexpr MAX_PAYLOAD_LEN = 8 * 1024 * 1024;
// This controls the preferred size for buffers.
// Too small and we'll need multiple buffers for one request
// Too big and we might taxing malloc
auto constexpr ALLOC_BUFFER_SIZE = size_t(4000);
class UvHandle : public c10::intrusive_ptr_target {
public:
~UvHandle() override = default;
c10::intrusive_ptr<UvHandle> iptr() {
return c10::intrusive_ptr<UvHandle>::reclaim_copy(this);
}
void close() {
if (uv_is_closing(unsafeGetHandle())) {
return;
}
uv_close(unsafeGetHandle(), on_close);
}
virtual uv_handle_t* unsafeGetHandle() = 0;
protected:
void handleReady() {
/*
This method must be called once the handle is ready and registered with the
loop.
Do not call this in the ctor, make_intrusive reset refcounts to one after
construction.
*/
uv_handle_set_data(unsafeGetHandle(), this);
at::raw::intrusive_ptr::incref(this);
}
virtual void onClose() = 0;
private:
static c10::intrusive_ptr<UvHandle> reclaim(uv_handle_t* handle) {
auto h = (UvHandle*)uv_handle_get_data(handle);
return c10::intrusive_ptr<UvHandle>::reclaim(h);
}
static void on_close(uv_handle_t* uv_handle) {
auto handle = reclaim(uv_handle);
handle->onClose();
}
};
class UvTcpSocket : public UvHandle {
uv_tcp_t client{};
std::string address_{"unknown"};
c10::intrusive_ptr<UvTcpSocket> iptr() {
return c10::intrusive_ptr<UvTcpSocket>::reclaim_copy(this);
}
static c10::intrusive_ptr<UvTcpSocket> borrow(uv_stream_t* handle) {
auto h = (UvTcpSocket*)uv_handle_get_data((uv_handle_t*)handle);
return h->iptr();
}
static void alloc_buffer(
uv_handle_t* handle,
size_t suggested_size,
uv_buf_t* buf) {
suggested_size = std::min(suggested_size, ALLOC_BUFFER_SIZE);
// NOLINTNEXTLINE(cppcoreguidelines-no-malloc)
buf->base = (char*)malloc(suggested_size);
buf->len = suggested_size;
}
static void read_callback(
uv_stream_t* client,
ssize_t nread,
const uv_buf_t* buf) {
auto uv_socket = UvTcpSocket::borrow(client);
if (nread < 0) {
C10D_DEBUG(
"Read callback failed. code:{} name:{} desc:{}",
nread,
uv_err_name(nread),
uv_strerror(nread));
uv_socket->close();
return;
}
if (nread > 0) {
try {
uv_socket->processBuf(buf, nread);
} catch (std::exception& ex) {
C10D_WARNING("Error processing client message: {}", ex.what());
uv_socket->close();
}
}
}
public:
explicit UvTcpSocket(uv_loop_t* loop) {
uv_tcp_init(loop, &client);
if (int err = uv_tcp_nodelay(&client, 1)) {
C10D_WARNING(
"The no-delay option cannot be enabled for the client socket. err={}",
err);
}
}
const std::string& address() const {
return address_;
}
void startRead() {
struct ::sockaddr_storage addr {};
int addrLen{sizeof(struct ::sockaddr_storage)};
if (int err = uv_tcp_getpeername(
&client, reinterpret_cast<struct ::sockaddr*>(&addr), &addrLen)) {
C10D_WARNING(
"The remote address of the client socket cannot be retrieved. err={}",
uv_strerror(err));
} else {
address_ =
formatSockAddr(reinterpret_cast<struct ::sockaddr*>(&addr), addrLen);
}
int res = uv_read_start((uv_stream_t*)&client, alloc_buffer, read_callback);
if (res) {
C10D_WARNING(
"Failed to setup read callback. client:{} code:{} name:{} desc:{}.",
(void*)this,
res,
uv_err_name(res),
uv_strerror(res));
close();
}
}
uv_handle_t* unsafeGetHandle() override {
return (uv_handle_t*)&client;
}
protected:
uv_stream_t* unsafeGetStream() {
return (uv_stream_t*)&client;
}
uv_tcp_t* unsafeGetSocket() {
return &client;
}
virtual void processBuf(const uv_buf_t* buf, size_t nread) {
TORCH_CHECK(
false, "Trying to read from a socket subclass that lacks processBuf");
}
void onClose() override {
// TODO use registerClient (and rename it to registerHandle) - this will
// significantly simplify things.
}
};
class UvTcpServer : public UvTcpSocket {
public:
typedef std::function<void(int)> OnConnectCallback;
explicit UvTcpServer(uv_loop_t* loop)
: UvTcpSocket(loop), onConnectCb_(missingOnConnect) {}
static c10::intrusive_ptr<UvTcpServer> makeWithSocket(
uv_loop_t* loop,
int socket) {
auto res = c10::make_intrusive<UvTcpServer>(loop);
res->handleReady();
try {
int uv_res = uv_tcp_open((uv_tcp_t*)res->unsafeGetStream(), socket);
TORCH_CHECK(
uv_res == 0,
"Failed to open existing socket. ",
"socket: ",
socket,
", code: ",
uv_res,
", name: ",
uv_err_name(uv_res),
", message: ",
uv_strerror(uv_res));
res->cacheSocketPort();
} catch (std::exception& ex) {
res->close();
throw;
}
return res;
}
void setOnConnectCallback(OnConnectCallback&& callback) {
onConnectCb_ = std::move(callback);
}
static c10::intrusive_ptr<UvTcpServer> makeWithPort(
uv_loop_t* loop,
uint16_t port,
bool useIpv6) {
auto res = c10::make_intrusive<UvTcpServer>(loop);
res->handleReady();
try {
struct sockaddr_storage addr {};
int uv_res = 0;
if (useIpv6) {
uv_res = uv_ip6_addr("::", port, (struct sockaddr_in6*)&addr);
} else {
uv_res = uv_ip4_addr("0.0.0.0", port, (struct sockaddr_in*)&addr);
}
TORCH_CHECK(
uv_res == 0,
"UV Store addr parsing failure. ",
"port: ",
port,
", useIpv6: ",
useIpv6,
", code: ",
uv_res,
", name: ",
uv_err_name(uv_res),
", message: ",
uv_strerror(uv_res));
uv_res = uv_tcp_bind(
res->unsafeGetSocket(), (const struct ::sockaddr*)&addr, 0);
TORCH_CHECK(
uv_res == 0,
"The server socket has failed to bind. ",
"port: ",
port,
", useIpv6: ",
useIpv6,
", code: ",
uv_res,
", name: ",
uv_err_name(uv_res),
", message: ",
uv_strerror(uv_res));
uv_res =
uv_listen(res->unsafeGetStream(), DEFAULT_BACKLOG, on_new_connection);
TORCH_CHECK(
uv_res == 0,
"The server socket has failed to listen on any local network address. ",
"port: ",
port,
", useIpv6: ",
useIpv6,
", code: ",
uv_res,
", name: ",
uv_err_name(uv_res),
", message: ",
uv_strerror(uv_res));
res->cacheSocketPort();
} catch (std::exception& ex) {
res->close();
throw;
}
return res;
}
uint16_t port() const {
return portNum_;
}
void accept(const c10::intrusive_ptr<UvTcpSocket>& socket) {
int res =
uv_accept(unsafeGetStream(), (uv_stream_t*)socket->unsafeGetHandle());
TORCH_CHECK(
res == 0,
"Failed to accept socket. ",
"code: ",
res,
", name: ",
uv_err_name(res),
", message: ",
uv_strerror(res));
}
private:
OnConnectCallback onConnectCb_;
uint16_t portNum_{};
c10::intrusive_ptr<UvTcpServer> iptr() {
return c10::intrusive_ptr<UvTcpServer>::reclaim_copy(this);
}
static c10::intrusive_ptr<UvTcpServer> borrow(uv_stream_t* handle) {
auto h = (UvTcpServer*)uv_handle_get_data((uv_handle_t*)handle);
return h->iptr();
}
void cacheSocketPort() {
sockaddr_storage addr_s{};
int addr_len = sizeof(addr_s);
if (uv_tcp_getsockname(
(uv_tcp_t*)unsafeGetStream(),
reinterpret_cast<::sockaddr*>(&addr_s),
&addr_len) != 0) {
throw std::runtime_error(
"The port number of the socket cannot be retrieved.");
}
if (addr_s.ss_family == AF_INET) {
portNum_ = ntohs(reinterpret_cast<sockaddr_in*>(&addr_s)->sin_port);
} else {
portNum_ = ntohs(reinterpret_cast<sockaddr_in6*>(&addr_s)->sin6_port);
}
}
static void missingOnConnect(int status) {
TORCH_CHECK(false, "Socket accepted byt onConnect callback missing");
}
static void on_new_connection(uv_stream_t* server, int status) {
borrow(server)->onConnectCb_(status);
}
};
class WriterPayload : public c10::intrusive_ptr_target {
static c10::intrusive_ptr<WriterPayload> reclaim(uv_write_t* request) {
/* This method returns a intrusive_ptr that does not increase the refcount.
*/
auto h = (WriterPayload*)uv_req_get_data((uv_req_t*)request);
return c10::intrusive_ptr<WriterPayload>::reclaim(h);
}
void registeredInLoop() {
/*
This refcount increment must be matched by a reclaim call.
Call this method after sucessfully scheduling this handle with a loop.
*/
at::raw::intrusive_ptr::incref(this);
}
static void write_done(uv_write_t* req, int status) {
/* Since we're no longer actively used by the event loop, transfer ownership
* to this frame. */
auto wp = WriterPayload::reclaim(req);
auto handle = wp->handle;
if (status) {
C10D_WARNING(
"Write to client failed. code:{} name:{} desc:{}.",
status,
uv_err_name(status),
uv_strerror(status));
handle->close();
}
}
std::vector<uint8_t> data;
uv_write_t req = {};
uv_buf_t buf = {};
c10::intrusive_ptr<UvHandle> handle;
public:
WriterPayload(
std::vector<uint8_t>&& in_data,
c10::intrusive_ptr<UvHandle> handle)
: data(std::move(in_data)), handle(std::move(handle)) {
uv_req_set_data((uv_req_t*)&req, this);
}
~WriterPayload() override = default;
void send() {
buf = uv_buf_init((char*)data.data(), data.size());
int res = uv_write(
&req, (uv_stream_t*)handle->unsafeGetHandle(), &buf, 1, write_done);
if (res) {
C10D_WARNING(
"Write setup to client failed. code:{} name:{} desc:{}.",
res,
uv_err_name(res),
uv_strerror(res));
handle->close();
} else {
/* This object was successfully registered with the event loop, so keep it
* alive until it's unregistered. */
registeredInLoop();
}
}
};
class StreamWriter {
std::vector<uint8_t> data;
c10::intrusive_ptr<UvHandle> handle;
// must be stack allocated
void* operator new(size_t);
public:
StreamWriter(c10::intrusive_ptr<UvHandle> handle)
: handle(std::move(handle)) {}
void write1(uint8_t val) {
data.push_back(val);
}
template <typename T>
void write_value(T val) {
uint8_t* val_ptr = (uint8_t*)&val;
data.insert(data.end(), val_ptr, val_ptr + sizeof(T));
}
void write_vector(const std::vector<uint8_t>& val) {
write_value<uint64_t>(val.size());
data.insert(data.end(), val.begin(), val.end());
}
void write_string(const std::string& val) {
write_value<uint64_t>(val.size());
data.insert(data.end(), val.data(), val.data() + val.size());
}
void send() {
auto wd = c10::make_intrusive<WriterPayload>(std::move(data), handle);
wd->send();
}
};
class ChunkedStream {
std::deque<uv_buf_t> buffers;
size_t buff_idx{0};
size_t buff_offset{0};
size_t capacity{0};
size_t buff_offset_commit{0};
size_t read_offset{0};
public:
ChunkedStream() = default;
size_t buf_count() {
return buffers.size();
}
void append(uv_buf_t buf) {
if (buf.len == 0) {
// NOLINTNEXTLINE(cppcoreguidelines-no-malloc)
free(buf.base);
} else {
capacity += buf.len;
buffers.push_back(buf);
}
}
bool read_many(char* dest, size_t size) {
if (available() < size) {
return false;
}
size_t remaining = size;
char* write_base = dest;
while (remaining > 0) {
auto to_read = std::min(buffers[buff_idx].len - buff_offset, remaining);
::memcpy(write_base, buffers[buff_idx].base + buff_offset, to_read);
buff_offset += to_read;
remaining -= to_read;
write_base += to_read;
if (buff_offset >= buffers[buff_idx].len) {
buff_offset = 0;
++buff_idx;
if (buff_idx >= buffers.size() && remaining > 0) {
TORCH_CHECK(
false,
"Trying to read past end of buffer. ",
"buffer_idx: ",
buff_idx,
", available: ",
buffers.size(),
", remaining: ",
remaining);
}
}
}
read_offset += size;
return true;
}
bool read1(uint8_t& byte) {
while (true) {
if (buff_idx >= buffers.size())
return false;
if (buff_offset >= buffers[buff_idx].len) {
buff_offset = 0;
++buff_idx;
continue;
}
break;
}
byte = buffers[buff_idx].base[buff_offset];
++buff_offset;
++read_offset;
return true;
}
template <typename T>
bool read_value(T& value) {
return read_many((char*)&value, sizeof(T));
}
bool read_key(std::string& str) {
uint64_t size = 0;
if (!read_value(size))
return false;
TORCH_CHECK(
size <= MAX_STRING_LEN,
"Invalid string size. ",
"size: ",
size,
", max: ",
MAX_STRING_LEN);
if (available() < size)
return false;
str.resize(size);
return read_many((char*)str.data(), size);
}
bool read_payload(std::vector<uint8_t>& data) {
uint64_t size = 0;
if (!read_value(size))
return false;
auto size_in_bytes = size * sizeof(uint8_t);
TORCH_CHECK(
size_in_bytes <= MAX_PAYLOAD_LEN,
"Invalid payload size. ",
"size: ",
size_in_bytes,
", max: ",
MAX_PAYLOAD_LEN);
if (available() < size_in_bytes)
return false;
data.resize(size);
return read_many((char*)data.data(), size_in_bytes);
}
size_t available() {
return capacity - read_offset;
}
void commit() {
if (buff_idx >= buffers.size() || buff_offset >= buffers[buff_idx].len) {
buff_offset = 0;
if (buff_idx < buffers.size())
++buff_idx;
}
for (size_t i = 0; i < buff_idx; ++i) {
// NOLINTNEXTLINE(cppcoreguidelines-no-malloc)
free(buffers[0].base);
capacity -= buffers[0].len;
buffers.pop_front();
}
buff_idx = 0;
read_offset = buff_offset_commit = buff_offset;
}
void reset() {
buff_idx = 0;
read_offset = buff_offset = buff_offset_commit;
}
};
class LibUVStoreDaemon : public BackgroundThread {
public:
explicit LibUVStoreDaemon(int port);
~LibUVStoreDaemon() override;
uint16_t port() const override;
void set(const std::string& key, const std::vector<uint8_t>& value);
const std::vector<uint8_t>& compareAndSet(
const std::string& key,
const std::vector<uint8_t>& expectedValue,
const std::vector<uint8_t>& newValue);
const std::vector<uint8_t>& get(const std::string& key);
int64_t add(const std::string& key, int64_t addVal);
bool checkKeys(const std::vector<std::string>& keys);
bool waitKeys(
const std::vector<std::string>& keys,
const c10::intrusive_ptr<UvHandle>& client);
int64_t size();
int64_t deleteKey(const std::string& key);
void append(const std::string& key, const std::vector<uint8_t>& value);
void registerClient(const c10::intrusive_ptr<UvHandle>& client);
void unregisterClient(const c10::intrusive_ptr<UvHandle>& client);
void clearClientWaitState(const c10::intrusive_ptr<UvHandle>& client);
bool isMiscellaneousClient(const c10::intrusive_ptr<UvHandle>& client);
uint16_t get_socket_port(uv_tcp_t* handle);
void init(const TCPStoreOptions& opts);
protected:
void run() override;
void stop() override;
private:
uv_loop_t loop_{};
c10::intrusive_ptr<UvTcpServer> tcpServer_;
uv_async_t exit_handle_{};
std::unordered_map<std::string, std::vector<uint8_t>> tcpStore_;
// From key -> the list of UvClient waiting on the key
std::unordered_map<std::string, std::vector<c10::intrusive_ptr<UvHandle>>>
waitingSockets_;
// From socket -> number of keys awaited
std::unordered_map<c10::intrusive_ptr<UvHandle>, size_t> keysAwaited_;
std::unordered_set<c10::intrusive_ptr<UvHandle>> clients_;
std::unordered_set<c10::intrusive_ptr<UvHandle>> miscellaneousClients_;
int port_;
static LibUVStoreDaemon& from_uv(uv_handle_t* stream) {
return *(LibUVStoreDaemon*)uv_handle_get_data(stream);
}
static void on_new_connection(uv_stream_t* server, int status) {
from_uv((uv_handle_t*)server).onConnect(status);
}
static void on_exit_request(uv_async_t* handle) {
from_uv((uv_handle_t*)handle).onExitRequest();
}
void onConnect(int status);
void onExitRequest();
void wakeupWaitingClients(const std::string& key);
// bool tryListen(bool use_ipv6);
static void print_active_handles(uv_handle_t* handle, void* arg);
};
class UvClient : public UvTcpSocket {
ChunkedStream stream;
LibUVStoreDaemon* store;
protected:
void processBuf(const uv_buf_t* buf, size_t nread) override {
auto tmp = *buf;
tmp.len = nread;
stream.append(tmp);
while (true) {
stream.reset();
uint8_t command = -1;
if (!stream.read1(command))
break;
if (store->isMiscellaneousClient(iptr())) {
if ((QueryType)command != QueryType::VALIDATE)
return;
if (!parse_validate_command())
return;
} else {
switch ((QueryType)command) {
case QueryType::PING:
if (!parse_ping_command())
return;
break;
case QueryType::SET:
if (!parse_set_command())
return;
break;
case QueryType::COMPARE_SET:
if (!parse_compare_set_command())
return;
break;
case QueryType::GET:
if (!parse_get_command())
return;
break;
case QueryType::ADD:
if (!parse_add_command())
return;
break;
case QueryType::CHECK:
if (!parse_check_command())
return;
break;
case QueryType::WAIT:
if (!parse_wait_command())
return;
break;
case QueryType::GETNUMKEYS:
if (!parse_getnumkeys_command())
return;
break;
case QueryType::DELETE_KEY:
if (!parse_delete_key_command())
return;
break;
case QueryType::APPEND:
if (!parse_append_command())
return;
break;
case QueryType::MULTI_GET:
if (!parse_multi_get_command())
return;
break;
case QueryType::MULTI_SET:
if (!parse_multi_set_command())
return;
break;
case QueryType::CANCEL_WAIT:
if (!parse_cancel_wait_command())
return;
break;
default:
C10D_DEBUG(
"Client sent invalid command. client:{} command:{}",
(void*)this,
(int)command);
close();
return;
}
}
stream.commit();
}
}
bool parse_validate_command() {
uint32_t validateNumber = 0;
if (!stream.read_value(validateNumber))
return false;
C10D_TRACE("validate magic:{} address:{}", validateNumber, this->address());
if (validateNumber != c10d::detail::validationMagicNumber)
return false;
return true;
}
bool parse_ping_command() {
uint32_t nonce = 0;
if (!stream.read_value(nonce)) {
return false;
}
C10D_TRACE("ping nonce:{} address:{}", nonce, this->address());
StreamWriter sw(iptr());
sw.write_value(nonce);
sw.send();
return true;
}
bool parse_set_command() {
std::string key;
if (!stream.read_key(key))
return false;
std::vector<uint8_t> newData;
if (!stream.read_payload(newData))
return false;
C10D_TRACE("set key:{} address:{}", key, this->address());
store->set(key, newData);
return true;
}
bool parse_compare_set_command() {
std::string key;
if (!stream.read_key(key))
return false;
std::vector<uint8_t> currentValue;
if (!stream.read_payload(currentValue))
return false;
std::vector<uint8_t> newValue;
if (!stream.read_payload(newValue))
return false;
C10D_TRACE("compareAndSet key:{} address:{}", key, this->address());
auto res = store->compareAndSet(key, currentValue, newValue);
StreamWriter sw(iptr());
sw.write_vector(res);
sw.send();
return true;
}
bool parse_get_command() {
std::string key;
if (!stream.read_key(key))
return false;
C10D_TRACE("get key:{} address:{}", key, this->address());
const auto& data = store->get(key);
StreamWriter sw(iptr());
sw.write_vector(data);
sw.send();
return true;
}
bool parse_add_command() {
std::string key;
if (!stream.read_key(key))
return false;
int64_t addVal = 0;
if (!stream.read_value(addVal))
return false;
C10D_TRACE("add key:{} val:{} address:{}", key, addVal, this->address());
addVal = store->add(key, addVal);
StreamWriter sw(iptr());
sw.write_value(addVal);
sw.send();
return true;
}
bool parse_check_command() {
uint64_t key_count = 0;
if (!stream.read_value(key_count))
return false;
TORCH_CHECK(
key_count <= MAX_KEY_COUNT,
"Too many keys being waited. ",
"keys: ",
key_count,
", max: ",
MAX_KEY_COUNT);
std::vector<std::string> keys(key_count);
for (uint64_t i = 0; i < key_count; ++i) {
if (!stream.read_key(keys[i]))
return false;
}
C10D_TRACE("check key_count:{} address:{}", key_count, this->address());
// Now we have received all the keys
StreamWriter sw(iptr());
if (store->checkKeys(keys)) {
sw.write_value(CheckResponseType::READY);
} else {
sw.write_value(CheckResponseType::NOT_READY);
}
sw.send();
return true;
}
bool parse_wait_command() {
uint64_t key_count = 0;
if (!stream.read_value(key_count)) {
return false;
}
TORCH_CHECK(
key_count <= MAX_KEY_COUNT,
"Too many keys being waited. ",
"keys: ",
key_count,
", max: ",
MAX_KEY_COUNT);
std::vector<std::string> keys(key_count);
for (uint64_t i = 0; i < key_count; ++i) {
if (!stream.read_key(keys[i]))
return false;
}
C10D_TRACE("wait key_count:{} address:{}", key_count, this->address());
if (store->waitKeys(keys, iptr())) {
StreamWriter sw(iptr());
sw.write1((uint8_t)WaitResponseType::STOP_WAITING);
sw.send();
}
return true;
}
bool parse_getnumkeys_command() {
C10D_TRACE("getnumkeys address:{}", this->address());
StreamWriter sw(iptr());
sw.write_value<int64_t>(store->size());
sw.send();
return true;
}
bool parse_delete_key_command() {
std::string key;
if (!stream.read_key(key))
return false;
C10D_TRACE("delete key:{} address:{}", key, this->address());
auto numDeleted = store->deleteKey(key);
StreamWriter sw(iptr());
sw.write_value<int64_t>(numDeleted);
sw.send();
return true;
}
bool parse_append_command() {
std::string key;
if (!stream.read_key(key)) {
return false;
}
std::vector<uint8_t> data;
if (!stream.read_payload(data)) {
return false;
}
C10D_TRACE("append key:{} address:{}", key, this->address());
store->append(key, data);
return true;
}
bool parse_multi_get_command() {
uint64_t key_count = 0;
if (!stream.read_value(key_count)) {
return false;
}
TORCH_CHECK(
key_count <= MAX_KEY_COUNT,
"Too many keys with multi_get. ",
"keys: ",
key_count,
", max: ",
MAX_KEY_COUNT);
C10D_TRACE("multi_get key_count:{} address:{}", key_count, this->address());
StreamWriter sw(iptr());
for (const auto _ : c10::irange(key_count)) {
(void)_; // Suppress unused variable warning
std::string key;
if (!stream.read_key(key)) {
return false;
}
sw.write_vector(store->get(key));
}
sw.send();
return true;
}
bool parse_multi_set_command() {
uint64_t key_count = 0;
if (!stream.read_value(key_count)) {
return false;
}
TORCH_CHECK(
key_count <= MAX_KEY_COUNT,
"Too many keys with multi_get. ",
"keys: ",
key_count,
", max: ",
MAX_KEY_COUNT);
C10D_TRACE("multi_set key_count:{} address:{}", key_count, this->address());
for (const auto _ : c10::irange(key_count)) {
(void)_; // Suppress unused variable warning
std::string key;
if (!stream.read_key(key)) {
return false;
}
std::vector<uint8_t> newData;
if (!stream.read_payload(newData))
return false;
store->set(key, newData);
}
return true;
}
bool parse_cancel_wait_command() {
store->clearClientWaitState(iptr());
C10D_TRACE("cancel_wait key_count:{} address:{}", this->address());
StreamWriter sw(iptr());
sw.write1((uint8_t)WaitResponseType::WAIT_CANCELED);
sw.send();
return true;
}
public:
explicit UvClient(uv_loop_t* loop, LibUVStoreDaemon* store)
: UvTcpSocket(loop), store(store) {}
static c10::intrusive_ptr<UvClient> make(
uv_loop_t* loop,
LibUVStoreDaemon* store) {
auto res = c10::make_intrusive<UvClient>(loop, store);
res->handleReady();
return res;
}
c10::intrusive_ptr<UvClient> iptr() {
return c10::intrusive_ptr<UvClient>::reclaim_copy(this);
}
protected:
void onClose() override {
store->unregisterClient(iptr());
}
};
void LibUVStoreDaemon::onConnect(int status) {
auto client = UvClient::make(&loop_, this);
registerClient(client);
try {
tcpServer_->accept(client);
client->startRead();
} catch (std::exception& e) {
C10D_WARNING("Failed to accept client due to {}", e.what());
client->close();
}
}
void LibUVStoreDaemon::onExitRequest() {
C10D_DEBUG("Store exit requested\n");
uv_close((uv_handle_t*)&exit_handle_, nullptr);
uv_stop(&loop_);
}
void LibUVStoreDaemon::init(const TCPStoreOptions& opts) {
if (opts.masterListenFd.has_value()) {
tcpServer_ = UvTcpServer::makeWithSocket(&loop_, *opts.masterListenFd);
} else {
try {
tcpServer_ =
UvTcpServer::makeWithPort(&loop_, opts.port, /*useIpv6=*/true);
} catch (std::exception& ex) {
C10D_INFO(
"Failed to bind to ipv6 address, trying ipv4. Error: {}", ex.what());
tcpServer_ =
UvTcpServer::makeWithPort(&loop_, opts.port, /*useIpv6=*/false);
}
}
tcpServer_->setOnConnectCallback(
[this](auto status) { this->onConnect(status); });
port_ = tcpServer_->port();
TORCH_CHECK(
port_ == opts.port || opts.port == 0, // zero means use any port
"listen fd ",
opts.masterListenFd,
" is bound to port ",
port_,
", expected to be bound to port ",
opts.port);
}
LibUVStoreDaemon::LibUVStoreDaemon(int port) : port_(port) {
TORCH_CHECK(uv_loop_init(&loop_) == 0, "Failed to init uv loop");
TORCH_CHECK(
uv_async_init(&loop_, &exit_handle_, LibUVStoreDaemon::on_exit_request) ==
0,
"Failed to init uv async event");
uv_handle_set_data((uv_handle_t*)&exit_handle_, this);
}
LibUVStoreDaemon::~LibUVStoreDaemon() {
if (!is_running()) {
uv_close((uv_handle_t*)&exit_handle_, nullptr);
uv_run(&loop_, UV_RUN_NOWAIT);
TORCH_CHECK(uv_loop_close(&loop_) == 0, "loop cleanup didn't work");
} else {
// the daemon thread cleanup libuv
dispose();
}
}
uint16_t LibUVStoreDaemon::port() const {
return port_;
}
void LibUVStoreDaemon::print_active_handles(uv_handle_t* handle, void* arg) {
C10D_DEBUG(
"UV live handle type {} active:{} is-closing:{}",
(int)handle->type,
uv_is_active(handle),
uv_is_closing(handle));
}
void LibUVStoreDaemon::run() {
c10::setThreadName("pt_tcpstore_uv");
C10D_DEBUG("Uv main loop running");
int res = uv_run(&loop_, UV_RUN_DEFAULT);
if (res) {
C10D_DEBUG("UV main loop done: res:{}", res);
}
bool debug_enabled =
c10d::detail::isLogLevelEnabled(c10d::detail::LogLevel::Debug);
if (debug_enabled) {
C10D_DEBUG("Walking live handles prior to closing clients");
uv_walk(&loop_, LibUVStoreDaemon::print_active_handles, nullptr);
}
for (const auto& client : clients_) {
client->close();
}
tcpServer_->close();
if (debug_enabled) {
C10D_DEBUG("Walking live handles after closing clients");
uv_walk(&loop_, LibUVStoreDaemon::print_active_handles, nullptr);
}
while (true) {
res = uv_loop_close(&loop_);
if (res == 0) {
break;
}
C10D_INFO(
"uv_loop_close failed with:{} errn:{} desc:{}",
res,
uv_err_name(res),
uv_strerror(res));
res = uv_run(&loop_, UV_RUN_NOWAIT);
if (res != 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
}
C10D_INFO("uv_loop cleanup finished.");
}
void LibUVStoreDaemon::stop() {
int res = uv_async_send(&exit_handle_);
if (res) {
C10D_WARNING(
"uv_async_send failed with:{} errn:{} desc:{}\n",
res,
uv_err_name(res),
uv_strerror(res));
}
}
bool LibUVStoreDaemon::isMiscellaneousClient(
const c10::intrusive_ptr<UvHandle>& client) {
if (miscellaneousClients_.find(client) != miscellaneousClients_.end()) {
miscellaneousClients_.erase(client);
return true;
}
return false;
}
void LibUVStoreDaemon::registerClient(
const c10::intrusive_ptr<UvHandle>& client) {
clients_.insert(client);
miscellaneousClients_.insert(client);
}
void LibUVStoreDaemon::unregisterClient(
const c10::intrusive_ptr<UvHandle>& client) {
clients_.erase(client);
if (miscellaneousClients_.find(client) != miscellaneousClients_.end()) {
miscellaneousClients_.erase(client);
}
clearClientWaitState(client);
}
void LibUVStoreDaemon::clearClientWaitState(
const c10::intrusive_ptr<UvHandle>& client) {
if (keysAwaited_.find(client) == keysAwaited_.end()) {
return;
}
keysAwaited_.erase(client);
for (auto it = waitingSockets_.begin(); it != waitingSockets_.end();) {
for (auto vecIt = it->second.begin(); vecIt != it->second.end();) {
if (*vecIt == client) {
vecIt = it->second.erase(vecIt);
} else {
++vecIt;
}
}
if (it->second.empty()) {
it = waitingSockets_.erase(it);
} else {
++it;
}
}
}
void LibUVStoreDaemon::set(
const std::string& key,
const std::vector<uint8_t>& value) {
tcpStore_[key] = value;
// On "set", wake up all clients that have been waiting
wakeupWaitingClients(key);
}
const std::vector<uint8_t>& LibUVStoreDaemon::compareAndSet(
const std::string& key,
const std::vector<uint8_t>& expectedValue,
const std::vector<uint8_t>& newValue) {
auto pos = tcpStore_.find(key);
if (pos == tcpStore_.end()) {
if (expectedValue.empty()) {
tcpStore_[key] = newValue;
wakeupWaitingClients(key);
// NOLINTNEXTLINE(bugprone-return-const-ref-from-parameter)
return newValue;
} else {
// TODO: This code path is not ideal as we are "lying" to the caller in
// case the key does not exist. We should come up with a working solution.
// It might make more sense to return ""
wakeupWaitingClients(key);
// NOLINTNEXTLINE(bugprone-return-const-ref-from-parameter)
return expectedValue;
}
} else {
if (pos->second == expectedValue) {
pos->second = newValue;
}
wakeupWaitingClients(key);
return pos->second;
}
}
const std::vector<uint8_t>& LibUVStoreDaemon::get(const std::string& key) {
static std::vector<uint8_t> missing_key;
return tcpStore_.count(key) ? tcpStore_.at(key) : missing_key;
}
int64_t LibUVStoreDaemon::add(const std::string& key, int64_t addVal) {
std::vector<uint8_t> oldData;
auto it = tcpStore_.find(key);
if (it != tcpStore_.end()) {
oldData = it->second;
auto buf = reinterpret_cast<const char*>(it->second.data());
auto len = it->second.size();
addVal += std::stoll(std::string(buf, len));
}
auto addValStr = std::to_string(addVal);
std::vector<uint8_t> newData =
std::vector<uint8_t>(addValStr.begin(), addValStr.end());
tcpStore_[key] = newData;
// On "add", wake up all clients that have been waiting
wakeupWaitingClients(key);
return addVal;
}
bool LibUVStoreDaemon::checkKeys(const std::vector<std::string>& keys) {
return std::all_of(keys.begin(), keys.end(), [&](const std::string& s) {
return tcpStore_.count(s) > 0;
});
}
bool LibUVStoreDaemon::waitKeys(
const std::vector<std::string>& keys,
const c10::intrusive_ptr<UvHandle>& client) {
if (checkKeys(keys)) {
return true;
}
int numKeysToAwait = 0;
for (auto& key : keys) {
// Only count keys that have not already been set
if (tcpStore_.find(key) == tcpStore_.end()) {
waitingSockets_[key].push_back(client);
numKeysToAwait++;
}
}
keysAwaited_[client] = numKeysToAwait;
return false;
}
int64_t LibUVStoreDaemon::size() {
return static_cast<int64_t>(tcpStore_.size());
}
int64_t LibUVStoreDaemon::deleteKey(const std::string& key) {
return static_cast<int64_t>(tcpStore_.erase(key));
}
void LibUVStoreDaemon::append(
const std::string& key,
const std::vector<uint8_t>& value) {
std::vector<uint8_t> oldData;
auto it = tcpStore_.find(key);
if (it != tcpStore_.end()) {
it->second.insert(it->second.end(), value.begin(), value.end());
} else {
tcpStore_[key] = value;
}
// we should not have clients waiting if we're appending, so it's all fine
wakeupWaitingClients(key);
}
void LibUVStoreDaemon::wakeupWaitingClients(const std::string& key) {
auto socketsToWait = waitingSockets_.find(key);
if (socketsToWait != waitingSockets_.end()) {
for (const auto& client : socketsToWait->second) {
if (--keysAwaited_[client] == 0) {
StreamWriter sw(client->iptr());
sw.write1((uint8_t)WaitResponseType::STOP_WAITING);
sw.send();
}
}
waitingSockets_.erase(socketsToWait);
}
}
#endif
std::unique_ptr<BackgroundThread> create_libuv_tcpstore_backend(
const TCPStoreOptions& opts) {
#ifdef TORCH_USE_LIBUV
auto res = std::make_unique<LibUVStoreDaemon>(opts.port);
res->init(opts);
return res;
#else
TORCH_CHECK(false, "LibUV TCPStore implementation missing");
#endif
}
bool is_libuv_tcpstore_backend_available() {
#ifdef TORCH_USE_LIBUV
return true;
#else
return false;
#endif
}
} // namespace c10d::detail
|