Repository navigation
Expand file tree
/
Copy pathshard_connection.cpp
More file actions
3275 lines (3002 loc) · 141 KB
/
Copy pathshard_connection.cpp
File metadata and controls
3275 lines (3002 loc) · 141 KB
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
/*
* Copyright (C) 2011-2026 Redis Labs Ltd.
*
* This file is part of memtier_benchmark.
*
* memtier_benchmark is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 2.
*
* memtier_benchmark is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with memtier_benchmark. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <errno.h>
#include "platform_compat.h"
#include <time.h>
#ifdef HAVE_NETINET_TCP_H
#include <netinet/tcp.h>
#endif
#ifdef HAVE_LIMITS_H
#include <limits.h>
#endif
#ifdef HAVE_ASSERT_H
#include <assert.h>
#endif
#include "shard_connection.h"
#include "libevent_read_cap.h"
#include "obj_gen.h"
#include "memtier_benchmark.h"
#include "connections_manager.h"
#include "client.h"
#include "retry_policy.h"
#include "retry_backoff.h"
#include "library_versions.h"
#include "event2/bufferevent.h"
// Maximum reconnect delay enforced after every exponential-backoff
// multiplication (retry_backoff.h has the one for --retry-on-error).
// Without a cap, a factor of 2.0 and --max-reconnect-attempts=0 (unlimited)
// causes the delay to double on every attempt: after ~30 doublings the next
// scheduled reconnect fires in ~34 years. event_add() silently absorbs
// that value, making the benchmark go effectively dark instead of surfacing the
// underlying failure. 60 s is a practical upper bound: tight enough to remain
// responsive, large enough to avoid thundering-herd reconnect storms.
static const double MEMTIER_BACKOFF_CAP_SEC = 60.0;
// Minimum reconnect delay enforced after every backoff multiplication. A
// --reconnect-backoff-factor below 1 shrinks the delay on each attempt; with no
// floor it reaches 0 s after a few attempts and a dead server is reconnected in
// a tight loop (hundreds of thousands of attempts and log lines per second).
// 100 ms still reconnects quickly while bounding each connection to ~10
// attempts per second. Factor 0 does not multiply, so it keeps the constant
// 1 s delay; a tiny positive factor settles at this floor instead.
static const double MEMTIER_RECONNECT_MIN_DELAY_SEC = 0.1;
// Workload requests count toward the client's generated/processed totals and
// per-endpoint routed ops; connection-setup requests do not. A switch, so a
// new request_type must be classified here.
static bool is_workload_request(request_type type)
{
switch (type) {
case rt_get:
case rt_set:
case rt_wait:
case rt_arbitrary:
return true;
case rt_unknown:
case rt_auth:
case rt_select_db:
case rt_cluster_slots:
case rt_hello:
case rt_readonly:
case rt_discard:
case rt_asking:
break;
}
return false;
}
#ifdef USE_TLS
#include <mutex>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include "event2/bufferevent_ssl.h"
#endif
void cluster_client_timer_handler(evutil_socket_t fd, short what, void *ctx)
{
shard_connection *sc = (shard_connection *) ctx;
assert(sc != NULL);
sc->handle_timer_event();
}
void cluster_client_reconnect_timer_handler(evutil_socket_t fd, short what, void *ctx)
{
shard_connection *sc = (shard_connection *) ctx;
assert(sc != NULL);
sc->handle_reconnect_timer_event();
}
void deferred_fill_pipeline_cb(evutil_socket_t, short, void *ctx)
{
static_cast<shard_connection *>(ctx)->fill_pipeline();
}
void cluster_slots_retry_cb(evutil_socket_t, short, void *ctx)
{
static_cast<shard_connection *>(ctx)->handle_cluster_slots_retry_event();
}
void setup_rejected_check_cb(evutil_socket_t, short, void *ctx)
{
static_cast<shard_connection *>(ctx)->handle_setup_rejected_check_event();
}
void unix_connect_retry_cb(evutil_socket_t, short, void *ctx)
{
static_cast<shard_connection *>(ctx)->handle_unix_connect_retry();
}
void cluster_client_connection_timeout_handler(evutil_socket_t fd, short what, void *ctx)
{
shard_connection *sc = (shard_connection *) ctx;
assert(sc != NULL);
sc->handle_connection_timeout_event();
}
void cluster_client_request_timeout_handler(evutil_socket_t fd, short what, void *ctx)
{
shard_connection *sc = (shard_connection *) ctx;
assert(sc != NULL);
sc->handle_request_timeout_event();
}
// Retry due times use the monotonic clock, like libevent's timers, so a
// wall-clock step cannot hold queued retries back or resend them early.
static void retry_clock_now(struct timeval *tv)
{
struct timespec mono;
if (clock_gettime(CLOCK_MONOTONIC, &mono) == 0) {
tv->tv_sec = mono.tv_sec;
tv->tv_usec = mono.tv_nsec / 1000;
} else {
gettimeofday(tv, NULL);
}
}
void cluster_client_retry_drain_handler(evutil_socket_t fd, short what, void *ctx)
{
shard_connection *sc = (shard_connection *) ctx;
assert(sc != NULL);
sc->handle_retry_drain_event();
}
void cluster_client_read_handler(bufferevent *bev, void *ctx)
{
shard_connection *sc = (shard_connection *) ctx;
assert(sc != NULL);
if (sc->reads_past_libevent_cap()) read_past_libevent_cap(bufferevent_get_input(bev), bufferevent_getfd(bev));
sc->process_response();
}
void cluster_client_event_handler(bufferevent *bev, short events, void *ctx)
{
shard_connection *sc = (shard_connection *) ctx;
assert(sc != NULL);
sc->handle_event(events);
}
request::request(request_type type, unsigned int size, struct timeval *sent_time, unsigned int keys) :
m_type(type),
m_size(size),
m_keys(keys),
m_retries(0),
m_claimed_by_retry(false),
m_asking(false),
m_replies(1),
m_serialized(NULL),
m_serialized_len(0),
m_key(NULL),
m_key_len(0)
{
if (sent_time != NULL)
m_sent_time = *sent_time;
else {
gettimeofday(&m_sent_time, NULL);
}
m_first_sent_time = m_sent_time;
timerclear(&m_retry_due);
}
request::~request(void)
{
if (m_serialized) {
free(m_serialized);
m_serialized = NULL;
m_serialized_len = 0;
}
if (m_key) {
free(m_key);
m_key = NULL;
m_key_len = 0;
}
}
void request::set_serialized(const char *data, size_t len)
{
if (m_serialized) {
free(m_serialized);
m_serialized = NULL;
m_serialized_len = 0;
}
if (!data || len == 0) return;
m_serialized = (char *) malloc(len);
if (!m_serialized) return; // best-effort capture; replay just won't work
memcpy(m_serialized, data, len);
m_serialized_len = len;
}
void request::set_key_for_log(const char *key, unsigned int key_len)
{
if (m_key) {
free(m_key);
m_key = NULL;
m_key_len = 0;
}
if (!key || key_len == 0) return;
m_key = (char *) malloc(key_len);
if (!m_key) return;
memcpy(m_key, key, key_len);
m_key_len = key_len;
}
arbitrary_request::arbitrary_request(size_t request_index, request_type type, unsigned int size,
struct timeval *sent_time, const arbitrary_command *cmd_meta) :
request(type, size, sent_time,
// m_keys is the number of expected key buckets. Prefer the
// spec-resolved positions when available so per-key totals match
// what the parser will see; otherwise fall back to the user's
// __key__ placeholder count, then 1 as a conservative default.
(cmd_meta == NULL || !cmd_meta->has_keys()) ? 1
: !cmd_meta->spec_key_positions.empty() ? (unsigned int) cmd_meta->spec_key_positions.size()
: cmd_meta->keys_count),
index(request_index),
m_cmd_meta(cmd_meta)
{
}
verify_request::verify_request(request_type type, unsigned int size, struct timeval *sent_time, unsigned int keys,
const char *key, unsigned int key_len, const char *value, unsigned int value_len) :
request(type, size, sent_time, keys), m_value(NULL), m_value_len(0)
{
// base class holds the key for both verification + failed-keys logging.
set_key_for_log(key, key_len);
m_value_len = value_len;
m_value = (char *) malloc(value_len);
memcpy(m_value, value, m_value_len);
}
verify_request::~verify_request(void)
{
if (m_value != NULL) {
free((void *) m_value);
m_value = NULL;
}
}
shard_connection::shard_connection(unsigned int id, connections_manager *conns_man, benchmark_config *config,
struct event_base *event_base, abstract_protocol *abs_protocol,
unsigned int request_rate_phase_microsecond) :
m_address(NULL),
m_port(NULL),
m_unix_sockaddr(NULL),
m_unix_sockaddrlen(0),
m_bev(NULL),
m_event_timer(NULL),
m_request_per_cur_interval(0),
m_request_rate_phase_microsecond(request_rate_phase_microsecond),
m_request_rate_phase_pending(request_rate_phase_microsecond > 0),
m_pending_resp(0),
m_front_replies(0),
m_front_extra_replies(0),
m_front_bytes(0),
m_queued_replies(0),
m_last_pushed_req_type(-1),
m_connection_state(conn_disconnected),
m_role(role_primary),
m_hello(setup_done),
m_authentication(setup_done),
m_db_selection(setup_done),
m_cluster_slots(setup_done),
m_cluster_slots_value_override(false),
m_cluster_slots_previous_keep_value(false),
m_readonly_state(setup_done),
m_multi_open(false),
m_reconnect_attempts(0),
m_current_backoff_delay(1.0),
m_reconnect_timer(NULL),
m_reconnecting(false),
m_setup_rejected(false),
m_setup_rejected_replica(false),
m_setup_rejected_context(NULL),
m_thread_end_reason(NULL),
m_connect_failed(false),
m_dropped_after_run_over(false),
m_setup_failed_since_reply(false),
m_reply_since_connect(false),
m_slots_rejected(false),
m_slots_retried_after_run_over(false),
m_reconnect_deadline(),
m_fired_reconnect_deadline(),
m_connection_timeout_timer(NULL),
m_request_timeout_timer(NULL),
m_request_timeout_armed(false),
m_request_progress(false),
m_unix_connect_timer(NULL),
#ifdef _WIN32
m_deferred_connect_error(NULL),
#endif
m_retry_queue(NULL),
m_replay_queue(NULL),
m_retry_drain_timer(NULL),
m_deferred_fill_timer(NULL),
m_cluster_slots_retry_timer(NULL),
m_setup_rejected_timer(NULL),
m_bev_paused(false),
m_reads_past_libevent_cap(false),
m_in_socket_connect(false),
m_socket_connect_error(0)
{
m_id = id;
m_conns_manager = conns_man;
m_config = config;
m_event_base = event_base;
if (m_config->unix_socket) {
m_unix_sockaddr = (struct sockaddr_un *) malloc(sizeof(struct sockaddr_un));
assert(m_unix_sockaddr != NULL);
memset(m_unix_sockaddr, 0, sizeof(struct sockaddr_un));
m_unix_sockaddr->sun_family = AF_UNIX;
#ifdef __linux__
// Linux abstract names include the leading NUL, but no terminator.
// Reject oversized names rather than connecting to a truncated name.
if (m_config->unix_socket[0] == '@') {
size_t name_len = strlen(m_config->unix_socket);
if (name_len <= sizeof(m_unix_sockaddr->sun_path)) {
memcpy(m_unix_sockaddr->sun_path + 1, m_config->unix_socket + 1, name_len - 1);
m_unix_sockaddrlen = offsetof(struct sockaddr_un, sun_path) + name_len;
}
} else
#endif
{
strncpy(m_unix_sockaddr->sun_path, m_config->unix_socket, sizeof(m_unix_sockaddr->sun_path) - 1);
m_unix_sockaddrlen = sizeof(struct sockaddr_un);
}
}
m_protocol = abs_protocol->clone();
assert(m_protocol != NULL);
m_pipeline = new std::queue<request *>;
assert(m_pipeline != NULL);
if (m_config->retry_on_error) {
m_retry_queue = new std::queue<request *>;
m_replay_queue = new std::queue<request *>;
}
timerclear(&m_retry_timer_due);
}
shard_connection::~shard_connection()
{
#ifdef _WIN32
cancel_deferred_connect_error();
#endif
if (m_address != NULL) {
free(m_address);
m_address = NULL;
}
if (m_port != NULL) {
free(m_port);
m_port = NULL;
}
if (m_unix_sockaddr != NULL) {
free(m_unix_sockaddr);
m_unix_sockaddr = NULL;
}
if (m_bev != NULL) {
bufferevent_free(m_bev);
m_bev = NULL;
}
if (m_event_timer != NULL) {
event_free(m_event_timer);
m_event_timer = NULL;
}
if (m_reconnect_timer != NULL) {
event_free(m_reconnect_timer);
m_reconnect_timer = NULL;
}
if (m_connection_timeout_timer != NULL) {
event_free(m_connection_timeout_timer);
m_connection_timeout_timer = NULL;
}
if (m_request_timeout_timer != NULL) {
event_free(m_request_timeout_timer);
m_request_timeout_timer = NULL;
m_request_timeout_armed = false;
}
if (m_unix_connect_timer != NULL) {
event_free(m_unix_connect_timer);
m_unix_connect_timer = NULL;
}
if (m_protocol != NULL) {
delete m_protocol;
m_protocol = NULL;
}
if (m_pipeline != NULL) {
// Free any requests still in flight. A normally-completed run drains the
// pipeline before teardown, but an early teardown (Ctrl+C,
// --connection-stage-timeout abort, or the --test-time backstop tearing
// down a wedged connection -- e.g. replaying a monitor command that
// never gets a reply) leaves queued request objects behind. Deleting the
// queue without draining it leaks them; LeakSanitizer flags it (the
// Monitor-Input Fuzz exit=42 reports). Mirrors the retry/replay queues
// below.
while (!m_pipeline->empty()) {
delete m_pipeline->front();
m_pipeline->pop();
}
delete m_pipeline;
m_pipeline = NULL;
}
if (m_retry_drain_timer != NULL) {
event_free(m_retry_drain_timer);
m_retry_drain_timer = NULL;
}
if (m_deferred_fill_timer != NULL) {
event_free(m_deferred_fill_timer);
m_deferred_fill_timer = NULL;
}
if (m_cluster_slots_retry_timer != NULL) {
event_free(m_cluster_slots_retry_timer);
m_cluster_slots_retry_timer = NULL;
}
if (m_setup_rejected_timer != NULL) {
event_free(m_setup_rejected_timer);
m_setup_rejected_timer = NULL;
}
if (m_retry_queue != NULL) {
while (!m_retry_queue->empty()) {
delete m_retry_queue->front();
m_retry_queue->pop();
}
delete m_retry_queue;
m_retry_queue = NULL;
}
if (m_replay_queue != NULL) {
while (!m_replay_queue->empty()) {
delete m_replay_queue->front();
m_replay_queue->pop();
}
delete m_replay_queue;
m_replay_queue = NULL;
}
}
#ifdef _WIN32
void shard_connection::cancel_deferred_connect_error()
{
if (m_deferred_connect_error != NULL) {
event_free(m_deferred_connect_error);
m_deferred_connect_error = NULL;
}
}
void shard_connection::deferred_connect_error_handler(evutil_socket_t, short, void *ctx)
{
shard_connection *connection = static_cast<shard_connection *>(ctx);
connection->cancel_deferred_connect_error();
// Teardown and unrelated Winsock calls can replace the thread's error.
// Restore the original refused result immediately before its callback.
WSASetLastError(WSAECONNREFUSED);
cluster_client_event_handler(connection->m_bev, BEV_EVENT_ERROR, connection);
}
#endif
bool shard_connection::setup_event(evutil_socket_t sockfd)
{
#ifdef _WIN32
cancel_deferred_connect_error();
#endif
if (m_bev) {
bufferevent_free(m_bev);
m_bev = NULL;
}
// Until a new bufferevent exists the protocol has no buffers, rather than
// the freed ones (also after disconnect()), should creation fail below.
if (m_protocol != NULL) m_protocol->set_buffers(NULL, NULL);
// Fresh bufferevent below starts enabled by default (after we call
// bufferevent_enable in handle_event on BEV_EVENT_CONNECTED); reset the
// pause flag so we don't carry stale state from a prior socket.
m_bev_paused = false;
m_reads_past_libevent_cap = false;
// On failure the caller fails this connect attempt like a socket setup
// failure; its connect/reconnect error handling applies unchanged.
// No BEV_OPT_DEFER_CALLBACKS on either bufferevent: socket_connect()
// relies on libevent before 2.1.9 calling the error callback from inside
// a failing bufferevent_socket_connect(), not later from the loop.
#ifdef USE_TLS
if (m_config->openssl_ctx) {
SSL *ctx = SSL_new(m_config->openssl_ctx);
if (ctx == NULL) {
benchmark_error_log("error: SSL_new() failed; cannot create the TLS connection.\n");
evutil_closesocket(sockfd);
return false;
}
if (m_config->tls_sni) {
SSL_set_tlsext_host_name(ctx, m_config->tls_sni);
}
m_bev = bufferevent_openssl_socket_new(m_event_base, sockfd, ctx, BUFFEREVENT_SSL_CONNECTING,
BEV_OPT_CLOSE_ON_FREE);
if (m_bev == NULL) {
// Do not free the SSL: libevent >= 2.1.9 already has
// (BEV_OPT_CLOSE_ON_FREE). Who owns the SSL and the socket on
// older libevent: see libevent_ssl_failure_socket_is_ours().
benchmark_error_log("error: bufferevent_openssl_socket_new() failed; cannot create the TLS "
"connection.\n");
// The loaded library does the cleanup, so ask its (runtime)
// version, not LIBEVENT_VERSION_NUMBER from the headers.
if (libevent_ssl_failure_socket_is_ours(event_get_version_number())) {
evutil_closesocket(sockfd);
} else {
benchmark_error_log("error: socket %d left open on purpose: libevent %s may already have closed it.\n",
(int) sockfd, event_get_version());
}
return false;
}
} else {
#endif
m_bev = bufferevent_socket_new(m_event_base, sockfd, BEV_OPT_CLOSE_ON_FREE);
if (m_bev == NULL) {
benchmark_error_log("error: bufferevent_socket_new() failed; cannot create the connection.\n");
evutil_closesocket(sockfd);
return false;
}
m_reads_past_libevent_cap = libevent_caps_reads();
#ifdef USE_TLS
}
#endif
bufferevent_setcb(m_bev, cluster_client_read_handler, NULL, cluster_client_event_handler, (void *) this);
m_protocol->set_buffers(bufferevent_get_input(m_bev), bufferevent_get_output(m_bev));
return true;
}
evutil_socket_t shard_connection::setup_socket(struct connect_info *addr)
{
evutil_socket_t sockfd;
if (m_unix_sockaddr != NULL) {
if (m_unix_sockaddrlen == 0) {
benchmark_error_log("error: abstract UNIX socket name is too long.\n");
errno = ENAMETOOLONG;
return -1;
}
sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sockfd < 0) {
return -1;
}
} else {
// initialize socket
sockfd = socket(addr->ci_family, addr->ci_socktype, addr->ci_protocol);
if (sockfd < 0) {
return -1;
}
const int enabled = 1;
int error = setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, (const char *) &enabled, sizeof(enabled));
assert(error == 0);
/*
* Configure socket behavior:
* If l_onoff is non-zero and l_linger is zero:
* The socket will discard any unsent data and the close() call will return immediately.
*/
struct linger ling;
ling.l_onoff = 1; // Enable SO_LINGER
ling.l_linger = 0; // Discard any unsent data and close immediately
error = setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char *) &ling, sizeof(ling));
assert(error == 0);
error = setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (const char *) &enabled, sizeof(enabled));
assert(error == 0);
}
// set non-blocking behavior
if (evutil_make_socket_nonblocking(sockfd) < 0) {
evutil_closesocket(sockfd);
return -1;
}
return sockfd;
}
#ifdef _WIN32
// bufferevent_socket_connect() with an address calls connect() and, on the
// expected WSAEWOULDBLOCK, getsockopt(SO_ERROR) to look for an immediate error.
// While a connect is in flight that getsockopt() blocks for 10-15 ms (even on
// loopback), and since all connections are opened one after another before the
// benchmark starts, setup time grows with threads * clients. Issue the
// non-blocking connect() here and give libevent the in-flight socket (NULL
// address), which then waits for the socket to become writable exactly as it
// does after its own WSAEWOULDBLOCK; failures are reported through the event
// callback as before. Refusal is deferred separately below. For any other
// immediate hard error, return
// -1 without calling connect() a second time (as bufferevent_socket_connect()
// with an address would); the caller reports the Winsock error, which is left
// in place for it to read.
static int bufferevent_connect_nonblocking(struct bufferevent *bev, evutil_socket_t sockfd, const struct sockaddr *sa,
int socklen)
{
// The unit fixture injects synchronous Winsock outcomes into this call.
#ifndef MEMTIER_TEST_CONNECT
int result = ::connect(sockfd, sa, socklen);
#else
int result = MEMTIER_TEST_CONNECT(sockfd, sa, socklen);
#endif
if (result == 0) {
return bufferevent_socket_connect(bev, NULL, 0);
}
// The errors libevent treats as "connect in progress" on Windows.
int err = WSAGetLastError();
// libevent defers a synchronous refusal to its error callback, returning
// success to the caller. Preserve that distinction from other hard errors.
if (err == WSAECONNREFUSED) return 1;
if (err == WSAEWOULDBLOCK || err == WSAEINTR || err == WSAEINPROGRESS || err == WSAEINVAL) {
return bufferevent_socket_connect(bev, NULL, 0);
}
return -1;
}
#endif
// bufferevent_socket_connect() on m_bev. A failure that libevent before
// 2.1.9 reports through handle_event() from inside the call is kept in
// m_socket_connect_error for the caller instead (see handle_event()).
int shard_connection::socket_connect(struct sockaddr *sa, int socklen)
{
m_in_socket_connect = true;
m_socket_connect_error = 0;
int ret = bufferevent_socket_connect(m_bev, sa, socklen);
m_in_socket_connect = false;
return ret;
}
int shard_connection::connect(struct connect_info *addr)
{
// Belt-and-suspenders: disconnect() already calls reset_state(), but if
// this object was constructed and never went through a disconnect (very
// first connect on a fresh shard_connection) we still want a clean
// parser cursor. Cheap and idempotent.
if (m_protocol != NULL) {
m_protocol->reset_state();
}
// set required setup commands
m_authentication = m_config->authenticate ? setup_none : setup_done;
m_db_selection = m_config->select_db ? setup_none : setup_done;
m_hello = (m_config->protocol == PROTOCOL_RESP2 || m_config->protocol == PROTOCOL_RESP3) ? setup_none : setup_done;
// Replica connections need READONLY before they will serve user reads;
// cluster mode only (standalone replicas need a different ladder per P2
// design brief). Re-armed on every reconnect because the flag is
// connection-scoped on the server.
m_readonly_state = (m_role == role_replica && m_config->cluster_mode && is_redis_protocol(m_config->protocol))
? setup_none
: setup_done;
m_multi_open = false;
m_queued_replies = 0;
// setup socket
evutil_socket_t sockfd = setup_socket(addr);
if (sockfd < 0) {
fprintf(stderr, "Failed to setup socket: %s\n", evutil_socket_error_to_string(EVUTIL_SOCKET_ERROR()));
return -1;
}
// set up bufferevent (on failure it has reported the error and released
// the socket)
if (!setup_event(sockfd)) return -1;
// set readable id
set_readable_id();
// call connect
m_connection_state = conn_in_progress;
struct sockaddr *sa = m_unix_sockaddr ? (struct sockaddr *) m_unix_sockaddr : addr->ci_addr;
int socklen = m_unix_sockaddr ? m_unix_sockaddrlen : addr->ci_addrlen;
#ifdef _WIN32
// bufferevent_connect_nonblocking() connects the socket itself and passes
// libevent no address, so libevent cannot fail the connect synchronously.
m_socket_connect_error = 0;
int ret = bufferevent_connect_nonblocking(m_bev, sockfd, sa, socklen);
if (ret == 1) {
// Do not enter the error callback during client preparation. This
// connection owns the queued event so disconnect/destruction cancels
// it, including the TLS bufferevent and its SSL ownership. event_new /
// event_active work with the libevent 2.0 APIs.
bufferevent_disable(m_bev, EV_READ | EV_WRITE);
m_deferred_connect_error = event_new(m_event_base, -1, 0, deferred_connect_error_handler, this);
if (m_deferred_connect_error == NULL) {
WSASetLastError(WSAENOBUFS);
ret = -1;
} else {
event_active(m_deferred_connect_error, EV_TIMEOUT, 0);
ret = 0;
}
}
#else
int ret = socket_connect(sa, socklen);
#endif
if (ret == -1) {
const int error = m_socket_connect_error != 0 ? m_socket_connect_error : EVUTIL_SOCKET_ERROR();
// A full Unix listener backlog returns EAGAIN without starting a
// connection. Wait between attempts so the worker and supervisor can
// still run. TCP EINPROGRESS is already handled by libevent.
#ifndef _WIN32
if (m_unix_sockaddr != NULL && (error == EAGAIN || error == EWOULDBLOCK)) {
// In particular, the SSL bufferevent must not try its handshake
// on an unconnected, writable socket while the backlog is full.
bufferevent_disable(m_bev, EV_READ | EV_WRITE);
// This is still one pending connect, not a failed reconnect
// attempt: EAGAIN must not consume --max-reconnect-attempts.
benchmark_debug_log("Unix socket listen queue full, waiting to connect\n");
struct timeval delay = {0, 10000};
m_unix_connect_timer = event_new(m_event_base, -1, EV_PERSIST, unix_connect_retry_cb, this);
if (m_unix_connect_timer == NULL || event_add(m_unix_connect_timer, &delay) != 0) {
disconnect();
benchmark_error_log("error: failed to schedule Unix socket connect retry\n");
return -1;
}
} else
#endif
{
disconnect();
benchmark_error_log("connect failed, error = %s\n", evutil_socket_error_to_string(error));
return -1;
}
}
// A pending reconnect is moot once something else (e.g. a shard's
// reconnect() reconnecting the main connection) connects this
// connection; left armed, it would keep m_reconnecting set and ignore
// errors on the live connection. Cancel it only now, so a socket setup
// failure above still leaves it to retry. A failed
// bufferevent_socket_connect() already cancelled it in disconnect(); its
// caller has to schedule the retry.
if (m_reconnect_timer != NULL) {
event_free(m_reconnect_timer);
m_reconnect_timer = NULL;
m_reconnect_deadline.tv_sec = m_reconnect_deadline.tv_usec = 0;
}
m_reconnecting = false;
m_setup_rejected = false;
// Start connection timeout timer (only if enabled)
if (m_config->connection_timeout > 0) {
struct timeval timeout;
timeout.tv_sec = m_config->connection_timeout;
timeout.tv_usec = 0;
m_connection_timeout_timer =
event_new(m_event_base, -1, 0, cluster_client_connection_timeout_handler, (void *) this);
event_add(m_connection_timeout_timer, &timeout);
}
return 0;
}
// Continue the same connect attempt: do not rearm its connection timeout.
void shard_connection::handle_unix_connect_retry()
{
// Apply the same timed-run policy as a failed asynchronous connect.
if (stops_at_deadline() && run_deadline_passed()) {
event_free(m_unix_connect_timer);
m_unix_connect_timer = NULL;
attempt_reconnect("Unix socket listen queue still full at run deadline");
return;
}
if (socket_connect((struct sockaddr *) m_unix_sockaddr, m_unix_sockaddrlen) == 0) {
event_free(m_unix_connect_timer);
m_unix_connect_timer = NULL;
bufferevent_enable(m_bev, EV_READ | EV_WRITE);
return;
}
const int error = m_socket_connect_error != 0 ? m_socket_connect_error : errno;
if (error == EAGAIN || error == EWOULDBLOCK) return;
event_free(m_unix_connect_timer);
m_unix_connect_timer = NULL;
benchmark_error_log("connect failed, error = %s\n", strerror(error));
attempt_reconnect("Unix socket connect failed");
}
// Log a request memtier gives up on, without a reply, to --failed-keys-file.
static void log_abandoned_request(const request *req, const char *reason)
{
struct timeval now;
gettimeofday(&now, NULL);
global_failed_keys_logger().log_failure(now, "REPLAY", req->m_key, req->m_key_len, reason, req->m_retries);
}
// A request that will get no reply on this connection (see disconnect()).
// With --retry-on-error, outside --transaction, it is queued to be resent after
// a reconnect, or abandoned if it has no captured bytes to resend. Otherwise it
// is dropped (abandoned under --retry-on-error --transaction). Setup commands
// are dropped and not counted.
void shard_connection::drop_unanswered_request(request *req, unsigned long long *dropped, unsigned long long *abandoned)
{
if (!is_workload_request(req->m_type)) {
delete req;
return;
}
if (m_config->retry_on_error && m_replay_queue != NULL && !m_config->transaction) {
if (req->m_serialized && req->m_serialized_len > 0) {
m_replay_queue->push(req);
return;
}
log_abandoned_request(req, "not-replayable");
(*abandoned)++;
} else if (m_config->retry_on_error && m_config->transaction) {
log_abandoned_request(req, "transaction-not-replayed");
(*abandoned)++;
} else {
(*dropped)++;
}
delete req;
}
void shard_connection::disconnect()
{
restore_cluster_slots_value_policy();
#ifdef _WIN32
cancel_deferred_connect_error();
#endif
if (m_bev) {
bufferevent_free(m_bev);
m_bev = NULL;
if (m_protocol != NULL) m_protocol->set_buffers(NULL, NULL);
}
// After free, any future bufferevent starts in the default (enabled) state.
m_bev_paused = false;
if (m_event_timer != NULL) {
event_free(m_event_timer);
m_event_timer = NULL;
}
if (m_reconnect_timer != NULL) {
event_free(m_reconnect_timer);
m_reconnect_timer = NULL;
m_reconnect_deadline.tv_sec = m_reconnect_deadline.tv_usec = 0;
}
if (m_connection_timeout_timer != NULL) {
event_free(m_connection_timeout_timer);
m_connection_timeout_timer = NULL;
}
if (m_unix_connect_timer != NULL) {
event_free(m_unix_connect_timer);
m_unix_connect_timer = NULL;
}
disarm_request_timeout();
// Drain pipeline. With --retry-on-error, move in-flight requests into the
// replay queue so they get resent after reconnect. Otherwise, discard them.
// Discarded workload requests will never be processed, so uncount them
// from the client's generated total; leaving them counted holds the
// pipeline (--reconnect-interval, cluster in-flight budget) and stalls
// --requests runs once the connection comes back. Requests held for retry
// are not counted as processed until their final outcome, so every
// workload request dropped here is uncounted the same way.
//
// --transaction requests are dropped too: the server discards the MULTI
// with the socket, so replaying the rest of a block would run its
// commands outside any transaction and its EXEC would fail.
//
// Under --retry-on-error a dropped request is one memtier gave up on, so
// it also counts as an error, like every other request that is never
// resent (abandoned); without it, dropping in-flight requests on a
// disconnect is the expected behaviour.
unsigned long long dropped = 0;
unsigned long long abandoned = 0;
while (m_pending_resp) {
drop_unanswered_request(pop_req(), &dropped, &abandoned);
}
if (m_config->retry_on_error && m_replay_queue != NULL && !m_config->transaction) {
// Also rescue requests sitting in the per-connection retry queue
// (waiting for a backoff timer to fire). Without this, the backoff
// timer's connection check (handle_retry_drain_event) would silently
// leave them stranded after reconnect.
if (m_retry_queue != NULL) {
while (!m_retry_queue->empty()) {
request *req = m_retry_queue->front();
m_retry_queue->pop();
if (req->m_serialized && req->m_serialized_len > 0) {
m_replay_queue->push(req);
} else {
// Not expected: enqueue_retry() only accepts requests
// with captured bytes. It cannot be resent: abandon it.
log_abandoned_request(req, "not-replayable");
abandoned++;
delete req;
}
}
}
// Cancel any pending drain timer — it has nothing to drain now and
// will be re-armed after reconnect by drain_replay_queue_after_reconnect.
if (m_retry_drain_timer != NULL && evtimer_pending(m_retry_drain_timer, NULL)) {
evtimer_del(m_retry_drain_timer);
}
}
if (dropped) m_conns_manager->dec_reqs_generated(dropped);
if (abandoned) m_conns_manager->abandon_requests(abandoned);
if (m_deferred_fill_timer != NULL && evtimer_pending(m_deferred_fill_timer, NULL)) {
evtimer_del(m_deferred_fill_timer);
}
if (m_cluster_slots_retry_timer != NULL && evtimer_pending(m_cluster_slots_retry_timer, NULL)) {
evtimer_del(m_cluster_slots_retry_timer);
}
if (m_setup_rejected_timer != NULL && evtimer_pending(m_setup_rejected_timer, NULL)) {
evtimer_del(m_setup_rejected_timer);
}
m_setup_rejected_context = NULL;
m_connection_state = conn_disconnected;
m_disconnect_count++;
// Reset rate limiting state during disconnection
m_request_per_cur_interval = 0;
// Clear the reconnect-in-progress flag. If a teardown races a pending
// reconnect timer (the timer was freed above), leaving m_reconnecting
// true would make every future attempt_reconnect call no-op silently.
m_reconnecting = false;
m_setup_rejected = false;
m_reply_since_connect = false;
// by default no need to send any setup request
m_authentication = setup_done;
m_db_selection = setup_done;
m_cluster_slots = setup_done;
m_hello = setup_done;
m_readonly_state = setup_done;
m_multi_open = false;
m_queued_replies = 0;