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 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
|
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// Functions related to the backend handler thread.
#include "proxy.h"
#include "proxy_tls.h"
enum proxy_be_failures {
P_BE_FAIL_TIMEOUT = 0,
P_BE_FAIL_DISCONNECTED,
P_BE_FAIL_CONNECTING,
P_BE_FAIL_CONNTIMEOUT,
P_BE_FAIL_READVALIDATE,
P_BE_FAIL_BADVALIDATE,
P_BE_FAIL_WRITING,
P_BE_FAIL_READING,
P_BE_FAIL_PARSING,
P_BE_FAIL_CLOSED,
P_BE_FAIL_UNHANDLEDRES,
P_BE_FAIL_OOM,
P_BE_FAIL_ENDSYNC,
P_BE_FAIL_TRAILINGDATA,
P_BE_FAIL_INVALIDPROTOCOL,
};
const char *proxy_be_failure_text[] = {
[P_BE_FAIL_TIMEOUT] = "timeout",
[P_BE_FAIL_DISCONNECTED] = "disconnected",
[P_BE_FAIL_CONNECTING] = "connecting",
[P_BE_FAIL_CONNTIMEOUT] = "conntimeout",
[P_BE_FAIL_READVALIDATE] = "readvalidate",
[P_BE_FAIL_BADVALIDATE] = "badvalidate",
[P_BE_FAIL_WRITING] = "writing",
[P_BE_FAIL_READING] = "reading",
[P_BE_FAIL_PARSING] = "parsing",
[P_BE_FAIL_CLOSED] = "closedsock",
[P_BE_FAIL_UNHANDLEDRES] = "unhandledres",
[P_BE_FAIL_OOM] = "outofmemory",
[P_BE_FAIL_ENDSYNC] = "missingend",
[P_BE_FAIL_TRAILINGDATA] = "trailingdata",
[P_BE_FAIL_INVALIDPROTOCOL] = "invalidprotocol",
NULL
};
static void proxy_backend_handler(const int fd, const short which, void *arg);
static void proxy_backend_tls_handler(const int fd, const short which, void *arg);
static void proxy_beconn_handler(const int fd, const short which, void *arg);
static void proxy_beconn_tls_handler(const int fd, const short which, void *arg);
static void proxy_event_handler(evutil_socket_t fd, short which, void *arg);
static void proxy_event_beconn(evutil_socket_t fd, short which, void *arg);
static int _prep_pending_write(struct mcp_backendconn_s *be, int *count, int *bytes, bool *iov_limit);
static void _post_pending_write(struct mcp_backendconn_s *be, ssize_t sent);
static int _flush_pending_write(struct mcp_backendconn_s *be);
static int _flush_pending_tls_write(struct mcp_backendconn_s *be);
static void _cleanup_backend(mcp_backend_t *be);
static void _reset_bad_backend(struct mcp_backendconn_s *be, enum proxy_be_failures err);
static void _set_main_event(struct mcp_backendconn_s *be, struct event_base *base, int flags, struct timeval *t, event_callback_fn callback);
static void _stop_main_event(struct mcp_backendconn_s *be);
static void _start_write_event(struct mcp_backendconn_s *be);
static void _stop_write_event(struct mcp_backendconn_s *be);
static void _start_timeout_event(struct mcp_backendconn_s *be);
static void _stop_timeout_event(struct mcp_backendconn_s *be);
static int proxy_backend_drive_machine(struct mcp_backendconn_s *be);
/* Helper routines common to io_uring and libevent modes */
// TODO (v3): doing an inline syscall here, not ideal for uring mode.
// leaving for now since this should be extremely uncommon.
static int _beconn_send_validate(struct mcp_backendconn_s *be) {
const char *str = "version\r\n";
const ssize_t len = strlen(str);
ssize_t res = write(mcmc_fd(be->client), str, len);
if (res == -1) {
return -1;
}
// I'm making an opinionated statement that we should be able to write
// "version\r\n" into a fresh socket without hitting EAGAIN.
if (res < len) {
return -1;
}
return 1;
}
static int _proxy_beconn_checkconnect(struct mcp_backendconn_s *be) {
int err = 0;
// We were connecting, now ensure we're properly connected.
if (mcmc_check_nonblock_connect(be->client, &err) != MCMC_OK) {
P_DEBUG("%s: backend failed to connect (%s:%s)\n", __func__, be->be_parent->name, be->be_parent->port);
// kick the bad backend, clear the queue, retry later.
// FIXME (v2): if a connect fails, anything currently in the queue
// should be safe to hold up until their timeout.
_reset_bad_backend(be, P_BE_FAIL_CONNECTING);
return -1;
}
P_DEBUG("%s: backend connected [fd: %d] (%s:%s)\n", __func__, mcmc_fd(be->client), be->be_parent->name, be->be_parent->port);
be->connecting = false;
be->state = mcp_backend_read;
// seed the failure time for the flap check.
gettimeofday(&be->last_failed, NULL);
be->validating = true;
// TODO: make validation optional.
return 0;
}
// Use a simple heuristic to choose a backend connection socket out of a list
// of sockets.
struct mcp_backendconn_s *proxy_choose_beconn(mcp_backend_t *be) {
struct mcp_backendconn_s *bec = &be->be[0];
if (be->conncount != 1) {
int depth = INT_MAX;
// TODO: to computationally limit + ensure each connection stays
// somewhat warm:
// - remember idx of last conn used.
// - if next idx has a lower depth, use that one instead
// - tick idx (and reset if necessary)
// else under low loads only the first conn will ever get used (which
// is normally good; but sometimes bad if using stateful firewalls)
for (int x = 0; x < be->conncount; x++) {
struct mcp_backendconn_s *bec_i = &be->be[x];
if (bec_i->bad) {
continue;
}
if (bec_i->depth == 0) {
bec = bec_i;
break;
} else if (bec_i->depth < depth) {
depth = bec_i->depth;
bec = bec_i;
}
}
}
return bec;
}
static void _proxy_event_handler_dequeue(proxy_event_thread_t *t) {
iop_head_t head;
STAILQ_INIT(&head);
STAILQ_INIT(&t->be_head);
// Pull the entire stack of inbound into local queue.
pthread_mutex_lock(&t->mutex);
STAILQ_CONCAT(&head, &t->iop_head_in);
pthread_mutex_unlock(&t->mutex);
while (!STAILQ_EMPTY(&head)) {
io_pending_proxy_t *p = (io_pending_proxy_t *)STAILQ_FIRST(&head);
p->flushed = false;
// _no_ mutex on backends. they are owned by the event thread.
STAILQ_REMOVE_HEAD(&head, iop_next);
// paranoia about moving items between lists.
p->iop_next.stqe_next = NULL;
mcp_backend_t *be = p->backend;
STAILQ_INSERT_TAIL(&be->iop_head, (io_pending_t *)p, iop_next);
assert(be->depth > -1);
be->depth++;
if (!be->stacked) {
be->stacked = true;
STAILQ_INSERT_TAIL(&t->be_head, be, be_next);
}
}
}
static void _cleanup_backend(mcp_backend_t *be) {
if (be->use_logging) {
if (be->logging.detail) {
free(be->logging.detail);
be->logging.detail = NULL;
}
}
for (int x = 0; x < be->conncount; x++) {
struct mcp_backendconn_s *bec = &be->be[x];
// remove any pending events.
if (!be->tunables.down) {
int pending = event_pending(&bec->main_event, EV_READ|EV_WRITE|EV_TIMEOUT, NULL);
if (pending != 0) {
event_del(&bec->main_event); // an error to call event_del() without event.
}
pending = event_pending(&bec->write_event, EV_READ|EV_WRITE|EV_TIMEOUT, NULL);
if (pending != 0) {
event_del(&bec->write_event); // an error to call event_del() without event.
}
pending = event_pending(&bec->timeout_event, EV_TIMEOUT, NULL);
if (pending != 0) {
event_del(&bec->timeout_event); // an error to call event_del() without event.
}
// - assert on empty queue
assert(STAILQ_EMPTY(&bec->iop_write));
assert(STAILQ_EMPTY(&bec->iop_read));
mcp_tls_shutdown(bec);
mcmc_disconnect(bec->client);
if (bec->bad) {
mcp_sharedvm_delta(bec->event_thread->ctx, SHAREDVM_BACKEND_IDX,
bec->be_parent->label, -1);
}
}
// - free be->client
free(bec->client);
// - free be->rbuf
free(bec->rbuf);
}
// free once parent has had all connections closed off.
free(be);
}
static void _setup_backend(mcp_backend_t *be) {
for (int x = 0; x < be->conncount; x++) {
struct mcp_backendconn_s *bec = &be->be[x];
if (be->tunables.down) {
// backend is "forced" into a bad state. never connect or
// otherwise attempt to use it.
be->be[x].bad = true;
continue;
}
// assign the initial events to the backend, so we don't have to
// constantly check if they were initialized yet elsewhere.
// note these events will not fire until event_add() is called.
int status = mcmc_connect(bec->client, be->name, be->port, bec->connect_flags);
event_callback_fn _beconn_handler = &proxy_beconn_handler;
event_callback_fn _backend_handler = &proxy_backend_handler;
if (be->tunables.use_tls) {
_beconn_handler = &proxy_beconn_tls_handler;
_backend_handler = &proxy_backend_tls_handler;
}
event_assign(&bec->main_event, bec->event_thread->base, mcmc_fd(bec->client), EV_WRITE|EV_TIMEOUT, _beconn_handler, bec);
event_assign(&bec->write_event, bec->event_thread->base, mcmc_fd(bec->client), EV_WRITE|EV_TIMEOUT, _backend_handler, bec);
event_assign(&bec->timeout_event, bec->event_thread->base, -1, EV_TIMEOUT, _backend_handler, bec);
if (status == MCMC_CONNECTING || status == MCMC_CONNECTED) {
// if we're already connected for some reason, still push it
// through the connection handler to keep the code unified. It
// will auto-wake because the socket is writeable.
bec->connecting = true;
bec->can_write = false;
// kick off the event we intialized above.
event_add(&bec->main_event, &bec->tunables.connect);
} else {
_reset_bad_backend(bec, P_BE_FAIL_CONNECTING);
}
}
}
// event handler for injecting backends for processing
// currently just for initiating connections the first time.
static void proxy_event_beconn(evutil_socket_t fd, short which, void *arg) {
proxy_event_thread_t *t = arg;
#ifdef USE_EVENTFD
uint64_t u;
if (read(fd, &u, sizeof(uint64_t)) != sizeof(uint64_t)) {
// Temporary error or wasn't actually ready to read somehow.
return;
}
#else
char buf[1];
if (read(fd, buf, 1) != 1) {
P_DEBUG("%s: pipe read failed\n", __func__);
return;
}
#endif
beconn_head_t head;
STAILQ_INIT(&head);
pthread_mutex_lock(&t->mutex);
STAILQ_CONCAT(&head, &t->beconn_head_in);
pthread_mutex_unlock(&t->mutex);
// Think we should reuse this code path for manually instructing backends
// to disable/etc but not coding for that generically. We just need to
// check the state of the backend when it reaches here or some flags at
// least.
// FIXME: another ->stacked flag?
// Either that or remove the STAILQ code and just using an array of
// ptr's.
mcp_backend_t *be = NULL;
// be can be freed by the loop, so can't use STAILQ_FOREACH.
while (!STAILQ_EMPTY(&head)) {
be = STAILQ_FIRST(&head);
STAILQ_REMOVE_HEAD(&head, beconn_next);
if (be->transferred) {
// If this object was already transferred here, we're being
// signalled to clean it up and free.
_cleanup_backend(be);
} else {
be->transferred = true;
_setup_backend(be);
}
}
}
static void _proxy_flush_backend_queue(mcp_backend_t *be) {
io_pending_proxy_t *io = NULL;
P_DEBUG("%s: fast failing request to bad backend (%s:%s) depth: %d\n", __func__, be->name, be->port, be->depth);
while (!STAILQ_EMPTY(&be->iop_head)) {
io = (io_pending_proxy_t *)STAILQ_FIRST(&be->iop_head);
STAILQ_REMOVE_HEAD(&be->iop_head, iop_next);
mcp_resp_set_elapsed(io->client_resp);
io->client_resp->status = MCMC_ERR;
io->client_resp->resp.code = MCMC_CODE_SERVER_ERROR;
be->depth--;
assert(be->depth > -1);
return_io_pending((io_pending_t *)io);
}
}
void proxy_run_backend_queue(be_head_t *head) {
mcp_backend_t *be;
STAILQ_FOREACH(be, head, be_next) {
be->stacked = false;
int flags = 0;
struct mcp_backendconn_s *bec = proxy_choose_beconn(be);
int limit = be->tunables.backend_depth_limit;
if (bec->bad) {
// TODO: another counter for fast fails?
_proxy_flush_backend_queue(be);
continue;
} else if (limit && bec->depth > limit) {
proxy_ctx_t *ctx = bec->event_thread->ctx;
STAT_INCR(ctx, request_failed_depth, be->depth);
_proxy_flush_backend_queue(be);
continue;
}
// drop new requests onto end of conn's io-head, reset the backend one.
STAILQ_CONCAT(&bec->iop_write, &be->iop_head);
bec->depth += be->depth;
be->depth = 0;
if (bec->connecting || bec->validating || !bec->can_write) {
P_DEBUG("%s: deferring IO pending connecting (%s:%s)\n", __func__, be->name, be->port);
} else {
if (!bec->ssl) {
flags = _flush_pending_write(bec);
} else {
flags = _flush_pending_tls_write(bec);
}
if (flags == -1) {
_reset_bad_backend(bec, P_BE_FAIL_WRITING);
} else if (flags & EV_WRITE) {
// only get here because we need to kick off the write handler
_start_write_event(bec);
}
if (bec->pending_read) {
_start_timeout_event(bec);
}
}
}
}
// event handler for executing backend requests
static void proxy_event_handler(evutil_socket_t fd, short which, void *arg) {
proxy_event_thread_t *t = arg;
#ifdef USE_EVENTFD
uint64_t u;
if (read(fd, &u, sizeof(uint64_t)) != sizeof(uint64_t)) {
// Temporary error or wasn't actually ready to read somehow.
return;
}
#else
char buf[1];
// TODO (v2): This is a lot more fatal than it should be. can it fail? can
// it blow up the server?
// TODO (v2): a cross-platform method of speeding this up would be nice. With
// event fds we can queue N events and wakeup once here.
// If we're pulling one byte out of the pipe at a time here it'll just
// wake us up too often.
// If the pipe is O_NONBLOCK then maybe just a larger read would work?
if (read(fd, buf, 1) != 1) {
P_DEBUG("%s: pipe read failed\n", __func__);
return;
}
#endif
_proxy_event_handler_dequeue(t);
// Re-walk each backend and check set event as required.
proxy_run_backend_queue(&t->be_head);
}
void *proxy_event_thread(void *arg) {
proxy_event_thread_t *t = arg;
logger_create(); // TODO (v2): add logger ptr to structure
event_base_loop(t->base, 0);
event_base_free(t->base);
// TODO (v2): join bt threads, free array.
return NULL;
}
static void _set_main_event(struct mcp_backendconn_s *be, struct event_base *base, int flags, struct timeval *t, event_callback_fn callback) {
int pending = event_pending(&be->main_event, EV_READ|EV_WRITE|EV_TIMEOUT, NULL);
if (pending != 0) {
event_del(&be->main_event); // replace existing event.
}
int fd = mcmc_fd(be->client);
if (fd == 0) {
fd = -1; // need to pass -1 to event assign if we're not operating on
// a connection.
}
event_assign(&be->main_event, base, fd,
flags, callback, be);
event_add(&be->main_event, t);
}
static void _stop_main_event(struct mcp_backendconn_s *be) {
event_del(&be->main_event);
}
static void _start_write_event(struct mcp_backendconn_s *be) {
int pending = event_pending(&be->write_event, EV_WRITE|EV_TIMEOUT, NULL);
if (pending != 0) {
return;
}
// FIXME: wasn't there a write timeout?
event_add(&be->write_event, &be->tunables.read);
}
static void _stop_write_event(struct mcp_backendconn_s *be) {
event_del(&be->write_event);
}
// handle the read timeouts with a side event, so we can stick with a
// persistent listener (optimization + catch disconnects faster)
static void _start_timeout_event(struct mcp_backendconn_s *be) {
int pending = event_pending(&be->timeout_event, EV_TIMEOUT, NULL);
if (pending != 0) {
return;
}
event_add(&be->timeout_event, &be->tunables.read);
}
static void _stop_timeout_event(struct mcp_backendconn_s *be) {
int pending = event_pending(&be->timeout_event, EV_TIMEOUT, NULL);
if (pending == 0) {
return;
}
event_del(&be->timeout_event);
}
static void _drive_machine_next(struct mcp_backendconn_s *be, io_pending_proxy_t *p) {
// set the head here. when we break the head will be correct.
assert(!STAILQ_EMPTY(&be->iop_read));
STAILQ_REMOVE_HEAD(&be->iop_read, iop_next);
be->depth--;
assert(be->depth > -1);
be->pending_read--;
assert(be->pending_read > -1);
mcp_resp_set_elapsed(p->client_resp);
// The moment we call return_io here we
// don't own *p anymore.
if (!be->be_parent->use_io_thread) {
conn_io_queue_return((io_pending_t *)p);
} else {
return_io_pending((io_pending_t *)p);
}
be->state = mcp_backend_read;
}
// NOTES:
// - mcp_backend_read: grab req_stack_head, do things
// read -> next, want_read -> next | read_end, etc.
static int proxy_backend_drive_machine(struct mcp_backendconn_s *be) {
bool stop = false;
io_pending_proxy_t *p = NULL;
int flags = 0;
p = (io_pending_proxy_t *)STAILQ_FIRST(&be->iop_read);
if (p == NULL) {
// got a read event, but nothing was queued.
// probably means a disconnect event.
// TODO (v2): could probably confirm this by attempting to read the
// socket, getsockopt, or something else simply for logging or
// statistical purposes.
// In this case we know it's going to be a close so error.
flags = P_BE_FAIL_CLOSED;
P_DEBUG("%s: read event but nothing in IO queue\n", __func__);
return flags;
}
while (!stop) {
mcp_resp_t *r;
switch(be->state) {
case mcp_backend_read:
assert(p != NULL);
// FIXME: remove the _read state?
be->state = mcp_backend_parse;
break;
case mcp_backend_parse:
r = p->client_resp;
r->status = mcmc_parse_buf(be->rbuf, be->rbufused, &r->resp);
// Quick check if we need more data.
if (r->resp.code == MCMC_WANT_READ) {
return 0;
}
// we actually don't care about anything but the value length
// TODO (v2): if vlen != vlen_read, pull an item and copy the data.
int extra_space = 0;
// if all goes well, move to the next request.
be->state = mcp_backend_next;
switch (r->resp.type) {
case MCMC_RESP_GET:
// We're in GET mode. we only support one key per
// GET in the proxy backends, so we need to later check
// for an END.
extra_space = ENDLEN;
be->state = mcp_backend_read_end;
break;
case MCMC_RESP_END:
// this is a MISS from a GET request
// or final handler from a STAT request.
assert(r->resp.vlen == 0);
if (p->ascii_multiget) {
// Ascii multiget hack mode; consume END's
be->rbufused -= r->resp.reslen;
if (be->rbufused > 0) {
memmove(be->rbuf, be->rbuf+r->resp.reslen, be->rbufused);
}
be->state = mcp_backend_next;
continue;
}
break;
case MCMC_RESP_META:
// we can handle meta responses easily since they're self
// contained.
break;
case MCMC_RESP_GENERIC:
case MCMC_RESP_NUMERIC:
break;
case MCMC_RESP_ERRMSG: // received an error message
if (r->resp.code != MCMC_CODE_SERVER_ERROR) {
// Non server errors are protocol errors; can't trust
// the connection anymore.
be->state = mcp_backend_next_close;
}
break;
case MCMC_RESP_FAIL:
P_DEBUG("%s: mcmc_read failed [%d]\n", __func__, r->status);
flags = P_BE_FAIL_PARSING;
stop = true;
break;
// TODO (v2): No-op response?
default:
P_DEBUG("%s: Unhandled response from backend: %d\n", __func__, r->resp.type);
// unhandled :(
flags = P_BE_FAIL_UNHANDLEDRES;
stop = true;
break;
}
// r->resp.reslen + r->resp.vlen is the total length of the response.
// TODO (v2): need to associate a buffer with this response...
// for now we simply malloc, but reusable buffers should be used
r->blen = r->resp.reslen + r->resp.vlen;
{
bool oom = proxy_bufmem_checkadd(r->thread, r->blen + extra_space);
if (oom) {
flags = P_BE_FAIL_OOM;
// need to zero out blen so we don't over-decrement later
r->blen = 0;
stop = true;
break;
}
}
r->buf = malloc(r->blen + extra_space);
if (r->buf == NULL) {
// Enforce accounting.
pthread_mutex_lock(&r->thread->proxy_limit_lock);
r->thread->proxy_buffer_memory_used -= r->blen + extra_space;
pthread_mutex_unlock(&r->thread->proxy_limit_lock);
flags = P_BE_FAIL_OOM;
r->blen = 0;
stop = true;
break;
}
P_DEBUG("%s: r->status: %d, r->bread: %d, r->vlen: %lu\n", __func__, r->status, r->bread, r->resp.vlen);
if (r->resp.vlen != r->resp.vlen_read) {
// shouldn't be possible to have excess in buffer
// if we're dealing with a partial value.
assert(be->rbufused == r->resp.reslen+r->resp.vlen_read);
P_DEBUG("%s: got a short read, moving to want_read\n", __func__);
// copy the partial and advance mcmc's buffer digestion.
memcpy(r->buf, be->rbuf, r->resp.reslen + r->resp.vlen_read);
r->bread = r->resp.reslen + r->resp.vlen_read;
be->rbufused = 0;
be->state = mcp_backend_want_read;
flags = 0;
stop = true;
break;
} else {
// mcmc's already counted the value as read if it fit in
// the original buffer...
memcpy(r->buf, be->rbuf, r->resp.reslen+r->resp.vlen_read);
}
// had a response, advance the buffer.
be->rbufused -= r->resp.reslen + r->resp.vlen_read;
if (be->rbufused > 0) {
memmove(be->rbuf, be->rbuf+r->resp.reslen+r->resp.vlen_read, be->rbufused);
}
break;
case mcp_backend_read_end:
r = p->client_resp;
// we need to ensure the next data in the stream is "END\r\n"
// if not, the stack is desynced and we lose it.
if (be->rbufused >= ENDLEN) {
if (memcmp(be->rbuf, ENDSTR, ENDLEN) != 0) {
flags = P_BE_FAIL_ENDSYNC;
stop = true;
break;
} else {
// response is good.
// FIXME (v2): copy what the server actually sent?
if (!p->ascii_multiget) {
// sigh... if part of a multiget we need to eat the END
// markers down here.
memcpy(r->buf+r->blen, ENDSTR, ENDLEN);
r->blen += 5;
} else {
r->extra = 5;
}
// advance buffer
be->rbufused -= ENDLEN;
if (be->rbufused > 0) {
memmove(be->rbuf, be->rbuf+ENDLEN, be->rbufused);
}
}
} else {
flags = 0;
stop = true;
break;
}
be->state = mcp_backend_next;
break;
case mcp_backend_want_read:
// Continuing a read from earlier
r = p->client_resp;
// take bread input and see if we're done reading the value,
// else advance, set buffers, return next.
P_DEBUG("%s: [want_read] r->bread: %d vlen: %lu\n", __func__, r->bread, r->resp.vlen);
assert(be->rbufused != 0);
size_t tocopy = be->rbufused < r->blen - r->bread ?
be->rbufused : r->blen - r->bread;
memcpy(r->buf+r->bread, be->rbuf, tocopy);
r->bread += tocopy;
if (r->bread >= r->blen) {
// all done copying data.
if (r->resp.type == MCMC_RESP_GET) {
be->state = mcp_backend_read_end;
} else {
be->state = mcp_backend_next;
}
// shuffle remaining buffer.
be->rbufused -= tocopy;
if (be->rbufused > 0) {
memmove(be->rbuf, be->rbuf+tocopy, be->rbufused);
}
} else {
assert(tocopy == be->rbufused);
// signal to caller to issue a read.
be->rbufused = 0;
flags = 0;
stop = true;
}
break;
case mcp_backend_next:
_drive_machine_next(be, p);
if (STAILQ_EMPTY(&be->iop_read)) {
stop = true;
// if there're no pending requests, the read buffer
// should also be empty.
if (be->rbufused > 0) {
flags = P_BE_FAIL_TRAILINGDATA;
}
break;
} else {
p = (io_pending_proxy_t *)STAILQ_FIRST(&be->iop_read);
}
// if leftover, keep processing IO's.
// if no more data in buffer, need to re-set stack head and re-set
// event.
P_DEBUG("%s: [next] remain: %lu\n", __func__, be->rbufused);
if (be->rbufused != 0) {
// data trailing in the buffer, for a different request.
be->state = mcp_backend_parse;
} else {
// need to read more data, buffer is empty.
stop = true;
}
break;
case mcp_backend_next_close:
// we advance and return the current IO, then kill the conn.
_drive_machine_next(be, p);
stop = true;
flags = P_BE_FAIL_INVALIDPROTOCOL;
break;
default:
// TODO (v2): at some point (after v1?) this should attempt to recover,
// though we should only get here from memory corruption and
// bailing may be the right thing to do.
fprintf(stderr, "%s: invalid backend state: %d\n", __func__, be->state);
assert(false);
} // switch
} // while
return flags;
}
static void _backend_reconnect(struct mcp_backendconn_s *be) {
int status = mcmc_connect(be->client, be->be_parent->name, be->be_parent->port, be->connect_flags);
if (status == MCMC_CONNECTED) {
// TODO (v2): unexpected but lets let it be here.
be->connecting = false;
be->can_write = true;
} else if (status == MCMC_CONNECTING) {
be->connecting = true;
be->can_write = false;
} else {
// failed to immediately re-establish the connection.
// need to put the BE into a bad/retry state.
be->connecting = false;
be->can_write = true;
}
// re-create the write handler for the new file descriptor.
// the main event will be re-assigned after this call.
event_callback_fn _backend_handler = &proxy_backend_handler;
if (be->be_parent->tunables.use_tls) {
_backend_handler = &proxy_backend_tls_handler;
}
event_assign(&be->write_event, be->event_thread->base, mcmc_fd(be->client), EV_WRITE|EV_TIMEOUT, _backend_handler, be);
// do not need to re-assign the timer event because it's not tied to fd
}
// All we need to do here is schedule the backend to attempt to connect again.
static void proxy_backend_retry_handler(const int fd, const short which, void *arg) {
struct mcp_backendconn_s *be = arg;
assert(which & EV_TIMEOUT);
struct timeval tmp_time = be->tunables.connect;
_backend_reconnect(be);
event_callback_fn _backend_handler = &proxy_beconn_handler;
if (be->be_parent->tunables.use_tls) {
_backend_handler = &proxy_beconn_tls_handler;
}
_set_main_event(be, be->event_thread->base, EV_WRITE, &tmp_time, _backend_handler);
}
// must be called after _reset_bad_backend(), so the backend is currently
// clear.
// TODO (v2): extra counter for "backend connect tries" so it's still possible
// to see dead backends exist
static void _backend_reschedule(struct mcp_backendconn_s *be) {
bool failed = false;
struct timeval tmp_time = {0};
long int retry_time = be->tunables.retry.tv_sec;
char *badtext = "markedbad";
if (be->flap_count > be->tunables.backend_failure_limit) {
// reduce retry frequency to avoid noise.
float backoff = retry_time;
for (int x = 0; x < be->flap_count; x++) {
backoff *= be->tunables.flap_backoff_ramp;
}
retry_time = (uint32_t)backoff;
if (retry_time > be->tunables.flap_backoff_max) {
retry_time = be->tunables.flap_backoff_max;
}
badtext = "markedbadflap";
failed = true;
} else if (be->failed_count > be->tunables.backend_failure_limit) {
failed = true;
}
tmp_time.tv_sec = retry_time;
if (failed) {
if (!be->bad) {
P_DEBUG("%s: marking backend as bad\n", __func__);
STAT_INCR(be->event_thread->ctx, backend_marked_bad, 1);
mcp_sharedvm_delta(be->event_thread->ctx, SHAREDVM_BACKEND_IDX,
be->be_parent->label, 1);
LOGGER_LOG(NULL, LOG_PROXYEVENTS, LOGGER_PROXY_BE_ERROR, NULL, badtext, be->be_parent->name, be->be_parent->port, be->be_parent->label, 0, NULL, 0, retry_time);
}
be->bad = true;
_set_main_event(be, be->event_thread->base, EV_TIMEOUT, &tmp_time, proxy_backend_retry_handler);
} else {
struct timeval tmp_time = be->tunables.connect;
STAT_INCR(be->event_thread->ctx, backend_failed, 1);
_backend_reconnect(be);
event_callback_fn _backend_handler = &proxy_beconn_handler;
if (be->be_parent->tunables.use_tls) {
_backend_handler = &proxy_beconn_tls_handler;
}
_set_main_event(be, be->event_thread->base, EV_WRITE, &tmp_time, _backend_handler);
}
}
static void _backend_flap_check(struct mcp_backendconn_s *be, enum proxy_be_failures err) {
struct timeval now;
struct timeval *flap = &be->tunables.flap;
switch (err) {
case P_BE_FAIL_TIMEOUT:
case P_BE_FAIL_DISCONNECTED:
case P_BE_FAIL_WRITING:
case P_BE_FAIL_READING:
if (flap->tv_sec != 0 || flap->tv_usec != 0) {
struct timeval delta = {0};
int64_t subsec = 0;
gettimeofday(&now, NULL);
delta.tv_sec = now.tv_sec - be->last_failed.tv_sec;
subsec = now.tv_usec - be->last_failed.tv_usec;
if (subsec < 0) {
// tv_usec is specced as "at least" [-1, 1000000]
// so to guarantee lower negatives we need this temp var.
delta.tv_sec--;
subsec += 1000000;
delta.tv_usec = subsec;
}
if (flap->tv_sec < delta.tv_sec ||
(flap->tv_sec == delta.tv_sec && flap->tv_usec < delta.tv_usec)) {
// delta is larger than our flap range. reset the flap counter.
be->flap_count = 0;
} else {
// seems like we flapped again.
be->flap_count++;
}
be->last_failed = now;
}
break;
default:
// only perform a flap check on network related errors.
break;
}
}
// TODO (v2): add a second argument for assigning a specific error to all pending
// IO's (ie; timeout).
// The backend has gotten into a bad state (timed out, protocol desync, or
// some other supposedly unrecoverable error: purge the queue and
// cycle the socket.
// Note that some types of errors may not require flushing the queue and
// should be fixed as they're figured out.
// _must_ be called from within the event thread.
static void _reset_bad_backend(struct mcp_backendconn_s *be, enum proxy_be_failures err) {
io_pending_proxy_t *io = NULL;
P_DEBUG("%s: resetting bad backend: [fd: %d] %s\n", __func__, mcmc_fd(be->client), proxy_be_failure_text[err]);
// Can't use STAILQ_FOREACH() since r_io_p() free's the current
// io. STAILQ_FOREACH_SAFE maybe?
int depth = be->depth;
while (!STAILQ_EMPTY(&be->iop_write)) {
io = (io_pending_proxy_t *)STAILQ_FIRST(&be->iop_write);
STAILQ_REMOVE_HEAD(&be->iop_write, iop_next);
mcp_resp_set_elapsed(io->client_resp);
io->client_resp->status = MCMC_ERR;
io->client_resp->resp.code = MCMC_CODE_SERVER_ERROR;
be->depth--;
assert(be->depth > -1);
return_io_pending((io_pending_t *)io);
}
while (!STAILQ_EMPTY(&be->iop_read)) {
io = (io_pending_proxy_t *)STAILQ_FIRST(&be->iop_read);
STAILQ_REMOVE_HEAD(&be->iop_read, iop_next);
mcp_resp_set_elapsed(io->client_resp);
io->client_resp->status = MCMC_ERR;
io->client_resp->resp.code = MCMC_CODE_SERVER_ERROR;
be->depth--;
assert(be->depth > -1);
return_io_pending((io_pending_t *)io);
}
STAILQ_INIT(&be->iop_write);
STAILQ_INIT(&be->iop_read);
// Only log if we don't already know it's messed up.
if (!be->bad) {
LOGGER_LOG(NULL, LOG_PROXYEVENTS, LOGGER_PROXY_BE_ERROR, NULL, proxy_be_failure_text[err], be->be_parent->name, be->be_parent->port, be->be_parent->label, depth, be->rbuf, be->rbufused, 0);
}
// reset buffer to blank state.
be->rbufused = 0;
be->pending_read = 0;
// clear events so the reconnect handler can re-arm them with a few fd.
_stop_write_event(be);
_stop_main_event(be);
_stop_timeout_event(be);
mcp_tls_shutdown(be);
mcmc_disconnect(be->client);
// we leave the main event alone, because be_failed() always overwrites.
// check failure counters and schedule a retry.
be->failed_count++;
_backend_flap_check(be, err);
_backend_reschedule(be);
}
static int _prep_pending_write(struct mcp_backendconn_s *be, int *count, int *bytes, bool *iov_limit) {
struct iovec *iovs = be->write_iovs;
io_pending_proxy_t *io = NULL;
int iovused = 0;
io = (io_pending_proxy_t *)STAILQ_FIRST(&be->iop_write);
assert(io != NULL);
for (; io; io = (io_pending_proxy_t *)STAILQ_NEXT(io, iop_next)) {
assert(io->flushed == false);
if (io->iovcnt + iovused > BE_IOV_MAX) {
// We will need to keep writing later.
*iov_limit = true;
break;
}
memcpy(&iovs[iovused], io->iov, sizeof(struct iovec)*io->iovcnt);
iovused += io->iovcnt;
*bytes += io->iovbytes;
(*count)++;
}
return iovused;
}
// returns true if any pending writes were fully flushed.
static void _post_pending_write(struct mcp_backendconn_s *be, ssize_t sent) {
io_pending_proxy_t *io = (io_pending_proxy_t *)STAILQ_FIRST(&be->iop_write);
while (!STAILQ_EMPTY(&be->iop_write)) {
io = (io_pending_proxy_t *)STAILQ_FIRST(&be->iop_write);
bool flushed = true;
assert(io->flushed == false);
if (sent >= io->iovbytes) {
// short circuit for common case.
sent -= io->iovbytes;
} else {
io->iovbytes -= sent;
for (int x = 0; x < io->iovcnt; x++) {
struct iovec *iov = &io->iov[x];
if (sent >= iov->iov_len) {
sent -= iov->iov_len;
iov->iov_len = 0;
} else {
iov->iov_len -= sent;
iov->iov_base = (char *)iov->iov_base + sent;
sent = 0;
flushed = false;
break;
}
}
}
io->flushed = flushed;
if (flushed) {
STAILQ_REMOVE_HEAD(&be->iop_write, iop_next);
STAILQ_INSERT_TAIL(&be->iop_read, (io_pending_t *)io, iop_next);
be->pending_read++;
}
if (sent <= 0) {
// really shouldn't be negative, though.
assert(sent >= 0);
break;
}
} // for
}
static int _flush_pending_write(struct mcp_backendconn_s *be) {
int flags = 0;
bool iov_limit = false;
// Allow us to be called with an empty stack to prevent dev errors.
if (STAILQ_EMPTY(&be->iop_write)) {
return 0;
}
int count = 0;
int bytes = 0;
int iovcnt = _prep_pending_write(be, &count, &bytes, &iov_limit);
ssize_t sent = writev(mcmc_fd(be->client), be->write_iovs, iovcnt);
if (sent > 0) {
if (bytes == sent && !iov_limit) {
// fast path if everything's sent.
be->pending_read += count;
STAILQ_CONCAT(&be->iop_read, &be->iop_write);
} else {
_post_pending_write(be, sent);
// still have unflushed pending IO's, check for write and re-loop.
if (!STAILQ_EMPTY(&be->iop_write)) {
// might still be writeable, just too many IOV's.
be->can_write = iov_limit;
flags |= EV_WRITE;
}
}
} else if (sent == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
be->can_write = false;
flags |= EV_WRITE;
} else {
flags = -1;
}
}
return flags;
}
static int _flush_pending_tls_write(struct mcp_backendconn_s *be) {
int flags = 0;
bool iov_limit = false;
// Allow us to be called with an empty stack to prevent dev errors.
if (STAILQ_EMPTY(&be->iop_write)) {
return 0;
}
int count = 0;
int bytes = 0;
int iovcnt = _prep_pending_write(be, &count, &bytes, &iov_limit);
int sent = mcp_tls_writev(be, iovcnt);
if (sent > 0) {
if (bytes == sent && !iov_limit) {
// fast path if everything's sent.
be->pending_read += count;
STAILQ_CONCAT(&be->iop_read, &be->iop_write);
} else {
_post_pending_write(be, sent);
// still have unflushed pending IO's, check for write and re-loop.
if (!STAILQ_EMPTY(&be->iop_write)) {
// might still be writeable, just too many IOV's.
be->can_write = iov_limit;
flags |= EV_WRITE;
}
}
} else if (sent == MCP_TLS_NEEDIO) {
// want io
be->can_write = false;
flags |= EV_WRITE;
} else if (sent == MCP_TLS_ERR) {
// hard error from tls
flags = -1;
}
return flags;
}
static void proxy_bevalidate_tls_handler(const int fd, const short which, void *arg) {
assert(arg != NULL);
struct mcp_backendconn_s *be = arg;
int flags = EV_TIMEOUT;
struct timeval tmp_time = be->tunables.read;
if (which & EV_TIMEOUT) {
P_DEBUG("%s: backend timed out while connecting [fd: %d]\n", __func__, mcmc_fd(be->client));
if (be->connecting) {
_reset_bad_backend(be, P_BE_FAIL_CONNTIMEOUT);
} else {
_reset_bad_backend(be, P_BE_FAIL_READVALIDATE);
}
return;
}
if (which & EV_READ) {
int read = mcp_tls_read(be);
if (read > 0) {
mcmc_resp_t r;
int status = mcmc_parse_buf(be->rbuf, be->rbufused, &r);
if (status == MCMC_ERR) {
// Needed more data for a version line, somehow. I feel like
// this should set off some alarms, but it is possible.
if (r.code == MCMC_WANT_READ) {
_set_main_event(be, be->event_thread->base, EV_READ, &tmp_time, proxy_bevalidate_tls_handler);
return;
}
_reset_bad_backend(be, P_BE_FAIL_READVALIDATE);
return;
}
if (r.code != MCMC_CODE_VERSION) {
_reset_bad_backend(be, P_BE_FAIL_BADVALIDATE);
return;
}
be->validating = false;
be->rbufused = 0;
} else if (read == 0) {
// not connected or error.
_reset_bad_backend(be, P_BE_FAIL_DISCONNECTED);
return;
} else if (read == MCP_TLS_NEEDIO) {
// try again failure.
_set_main_event(be, be->event_thread->base, EV_READ, &tmp_time, proxy_bevalidate_tls_handler);
return;
} else if (read == MCP_TLS_ERR) {
// hard failure.
_reset_bad_backend(be, P_BE_FAIL_READING);
return;
}
// Passed validation, don't need to re-read, flush any pending writes.
int res = _flush_pending_tls_write(be);
if (res == -1) {
_reset_bad_backend(be, P_BE_FAIL_WRITING);
return;
}
if (flags & EV_WRITE) {
_start_write_event(be);
}
if (be->pending_read) {
_start_timeout_event(be);
}
}
// switch to the primary persistent read event.
if (!be->validating) {
_set_main_event(be, be->event_thread->base, EV_READ|EV_PERSIST, NULL, proxy_backend_tls_handler);
// we're happily validated and switching to normal processing, so
// _now_ the backend is no longer "bad".
// If we reset the failed count earlier we then can fail the
// validation loop indefinitely without ever being marked bad.
if (be->bad) {
// was bad, need to mark as no longer bad in shared space.
mcp_sharedvm_delta(be->event_thread->ctx, SHAREDVM_BACKEND_IDX,
be->be_parent->label, -1);
}
be->bad = false;
be->failed_count = 0;
}
}
// Libevent handler when we're in TLS mode. Unfortunately the code is
// different enough to warrant its own function.
static void proxy_beconn_tls_handler(const int fd, const short which, void *arg) {
assert(arg != NULL);
struct mcp_backendconn_s *be = arg;
//int flags = EV_TIMEOUT;
struct timeval tmp_time = be->tunables.read;
if (which & EV_TIMEOUT) {
P_DEBUG("%s: backend timed out while connecting [fd: %d]\n", __func__, mcmc_fd(be->client));
if (be->connecting) {
_reset_bad_backend(be, P_BE_FAIL_CONNTIMEOUT);
} else {
_reset_bad_backend(be, P_BE_FAIL_READVALIDATE);
}
return;
}
if (which & EV_WRITE) {
be->can_write = true;
if (be->connecting) {
if (_proxy_beconn_checkconnect(be) == -1) {
return;
}
// TODO: check return code.
mcp_tls_connect(be);
// fall through to handshake attempt.
}
}
assert(be->validating);
int ret = mcp_tls_handshake(be);
if (ret == MCP_TLS_NEEDIO) {
// Need to try again.
_set_main_event(be, be->event_thread->base, EV_READ, &tmp_time, proxy_beconn_tls_handler);
return;
} else if (ret == 1) {
// handshake complete.
if (mcp_tls_send_validate(be) != MCP_TLS_OK) {
_reset_bad_backend(be, P_BE_FAIL_BADVALIDATE);
return;
}
// switch to another handler for the final stage.
_set_main_event(be, be->event_thread->base, EV_READ, &tmp_time, proxy_bevalidate_tls_handler);
} else if (ret < 0) {
// FIXME: FAIL_HANDSHAKE
_reset_bad_backend(be, P_BE_FAIL_BADVALIDATE);
return;
}
}
// Libevent handler for backends in a connecting state.
static void proxy_beconn_handler(const int fd, const short which, void *arg) {
assert(arg != NULL);
struct mcp_backendconn_s *be = arg;
int flags = EV_TIMEOUT;
struct timeval tmp_time = be->tunables.read;
if (which & EV_TIMEOUT) {
P_DEBUG("%s: backend timed out while connecting [fd: %d]\n", __func__, mcmc_fd(be->client));
if (be->connecting) {
_reset_bad_backend(be, P_BE_FAIL_CONNTIMEOUT);
} else {
_reset_bad_backend(be, P_BE_FAIL_READVALIDATE);
}
return;
}
if (which & EV_WRITE) {
be->can_write = true;
if (be->connecting) {
if (_proxy_beconn_checkconnect(be) == -1) {
return;
}
if (_beconn_send_validate(be) == -1) {
_reset_bad_backend(be, P_BE_FAIL_BADVALIDATE);
return;
}
_set_main_event(be, be->event_thread->base, EV_READ, &tmp_time, proxy_beconn_handler);
}
// TODO: currently never taken, until validation is made optional.
if (!be->validating) {
int res = _flush_pending_write(be);
if (res == -1) {
_reset_bad_backend(be, P_BE_FAIL_WRITING);
return;
}
flags |= res;
// FIXME: set write event?
}
}
if (which & EV_READ) {
assert(be->validating);
int read = recv(mcmc_fd(be->client), be->rbuf + be->rbufused, READ_BUFFER_SIZE - be->rbufused, 0);
if (read > 0) {
mcmc_resp_t r;
be->rbufused += read;
int status = mcmc_parse_buf(be->rbuf, be->rbufused, &r);
if (status == MCMC_ERR) {
// Needed more data for a version line, somehow. I feel like
// this should set off some alarms, but it is possible.
if (r.code == MCMC_WANT_READ) {
_set_main_event(be, be->event_thread->base, EV_READ, &tmp_time, proxy_beconn_handler);
return;
}
_reset_bad_backend(be, P_BE_FAIL_READVALIDATE);
return;
}
if (r.code != MCMC_CODE_VERSION) {
_reset_bad_backend(be, P_BE_FAIL_BADVALIDATE);
return;
}
be->validating = false;
be->rbufused = 0;
} else if (read == 0) {
// not connected or error.
_reset_bad_backend(be, P_BE_FAIL_DISCONNECTED);
return;
} else if (read == -1) {
// sit on epoll again.
if (errno != EAGAIN && errno != EWOULDBLOCK) {
_reset_bad_backend(be, P_BE_FAIL_READING);
return;
}
_set_main_event(be, be->event_thread->base, EV_READ, &tmp_time, proxy_beconn_handler);
return;
}
// Passed validation, don't need to re-read, flush any pending writes.
int res = _flush_pending_write(be);
if (res == -1) {
_reset_bad_backend(be, P_BE_FAIL_WRITING);
return;
}
if (res & EV_WRITE) {
_start_write_event(be);
}
if (be->pending_read) {
_start_timeout_event(be);
}
}
// switch to the primary persistent read event.
if (!be->validating) {
_set_main_event(be, be->event_thread->base, EV_READ|EV_PERSIST, NULL, proxy_backend_handler);
// we're happily validated and switching to normal processing, so
// _now_ the backend is no longer "bad".
// If we reset the failed count earlier we then can fail the
// validation loop indefinitely without ever being marked bad.
if (be->bad) {
// was bad, need to mark as no longer bad in shared space.
mcp_sharedvm_delta(be->event_thread->ctx, SHAREDVM_BACKEND_IDX,
be->be_parent->label, -1);
}
be->bad = false;
be->failed_count = 0;
}
}
static void proxy_backend_tls_handler(const int fd, const short which, void *arg) {
struct mcp_backendconn_s *be = arg;
if (which & EV_TIMEOUT) {
P_DEBUG("%s: timeout received, killing backend queue\n", __func__);
_reset_bad_backend(be, P_BE_FAIL_TIMEOUT);
return;
}
if (which & EV_WRITE) {
be->can_write = true;
int res = _flush_pending_tls_write(be);
if (res == -1) {
_reset_bad_backend(be, P_BE_FAIL_WRITING);
return;
}
if (res & EV_WRITE) {
_start_write_event(be);
}
}
if (which & EV_READ) {
// got a read event, always kill the pending read timer.
_stop_timeout_event(be);
// We do the syscall here before diving into the state machine to allow a
// common code path for io_uring/epoll/tls/etc
int read = mcp_tls_read(be);
if (read > 0) {
int res = proxy_backend_drive_machine(be);
if (res != 0) {
_reset_bad_backend(be, res);
return;
}
} else if (read == 0) {
// not connected or error.
_reset_bad_backend(be, P_BE_FAIL_DISCONNECTED);
return;
} else if (read == MCP_TLS_NEEDIO) {
// sit on epoll again.
return;
} else if (read == MCP_TLS_ERR) {
_reset_bad_backend(be, P_BE_FAIL_READING);
return;
}
#ifdef PROXY_DEBUG
if (!STAILQ_EMPTY(&be->iop_head)) {
P_DEBUG("backend has leftover IOs: %d\n", be->depth);
}
#endif
}
if (be->pending_read) {
_start_timeout_event(be);
}
}
// The libevent backend callback handler.
// If we end up resetting a backend, it will get put back into a connecting
// state.
static void proxy_backend_handler(const int fd, const short which, void *arg) {
struct mcp_backendconn_s *be = arg;
if (which & EV_TIMEOUT) {
P_DEBUG("%s: timeout received, killing backend queue\n", __func__);
_reset_bad_backend(be, P_BE_FAIL_TIMEOUT);
return;
}
if (which & EV_WRITE) {
be->can_write = true;
int res = _flush_pending_write(be);
if (res == -1) {
_reset_bad_backend(be, P_BE_FAIL_WRITING);
return;
}
if (res & EV_WRITE) {
_start_write_event(be);
}
}
if (which & EV_READ) {
// got a read event, always kill the pending read timer.
_stop_timeout_event(be);
// We do the syscall here before diving into the state machine to allow a
// common code path for io_uring/epoll
int read = recv(mcmc_fd(be->client), be->rbuf + be->rbufused,
READ_BUFFER_SIZE - be->rbufused, 0);
if (read > 0) {
be->rbufused += read;
int res = proxy_backend_drive_machine(be);
if (res != 0) {
_reset_bad_backend(be, res);
return;
}
} else if (read == 0) {
// not connected or error.
_reset_bad_backend(be, P_BE_FAIL_DISCONNECTED);
return;
} else if (read == -1) {
// sit on epoll again.
if (errno != EAGAIN && errno != EWOULDBLOCK) {
_reset_bad_backend(be, P_BE_FAIL_READING);
return;
}
}
#ifdef PROXY_DEBUG
if (!STAILQ_EMPTY(&be->iop_head)) {
P_DEBUG("backend has leftover IOs: %d\n", be->depth);
}
#endif
}
if (be->pending_read) {
_start_timeout_event(be);
}
}
void proxy_init_event_thread(proxy_event_thread_t *t, proxy_ctx_t *ctx, struct event_base *base) {
t->ctx = ctx;
#ifdef USE_EVENTFD
t->event_fd = eventfd(0, EFD_NONBLOCK);
if (t->event_fd == -1) {
perror("failed to create backend notify eventfd");
exit(1);
}
t->be_event_fd = eventfd(0, EFD_NONBLOCK);
if (t->be_event_fd == -1) {
perror("failed to create backend notify eventfd");
exit(1);
}
#else
int fds[2];
if (pipe(fds)) {
perror("can't create proxy backend notify pipe");
exit(1);
}
t->notify_receive_fd = fds[0];
t->notify_send_fd = fds[1];
if (pipe(fds)) {
perror("can't create proxy backend connection notify pipe");
exit(1);
}
t->be_notify_receive_fd = fds[0];
t->be_notify_send_fd = fds[1];
#endif
// incoming request queue.
STAILQ_INIT(&t->iop_head_in);
STAILQ_INIT(&t->beconn_head_in);
pthread_mutex_init(&t->mutex, NULL);
pthread_cond_init(&t->cond, NULL);
// initialize the event system.
#ifdef HAVE_LIBURING
if (t->ctx->use_uring) {
fprintf(stderr, "Sorry, io_uring not supported right now\n");
abort();
}
#endif
if (base == NULL) {
struct event_config *ev_config;
ev_config = event_config_new();
event_config_set_flag(ev_config, EVENT_BASE_FLAG_NOLOCK);
t->base = event_base_new_with_config(ev_config);
event_config_free(ev_config);
if (! t->base) {
fprintf(stderr, "Can't allocate event base\n");
exit(1);
}
} else {
// reusing an event base from a worker thread.
t->base = base;
}
// listen for notifications.
// NULL was thread_libevent_process
// FIXME (v2): use modern format? (event_assign)
#ifdef USE_EVENTFD
event_set(&t->notify_event, t->event_fd,
EV_READ | EV_PERSIST, proxy_event_handler, t);
event_set(&t->beconn_event, t->be_event_fd,
EV_READ | EV_PERSIST, proxy_event_beconn, t);
#else
event_set(&t->notify_event, t->notify_receive_fd,
EV_READ | EV_PERSIST, proxy_event_handler, t);
event_set(&t->beconn_event, t->be_notify_receive_fd,
EV_READ | EV_PERSIST, proxy_event_beconn, t);
#endif
event_base_set(t->base, &t->notify_event);
if (event_add(&t->notify_event, 0) == -1) {
fprintf(stderr, "Can't monitor libevent notify pipe\n");
exit(1);
}
event_base_set(t->base, &t->beconn_event);
if (event_add(&t->beconn_event, 0) == -1) {
fprintf(stderr, "Can't monitor libevent notify pipe\n");
exit(1);
}
}
|