Repository navigation
Expand file tree
/
Copy pathclient.cpp
More file actions
2047 lines (1827 loc) · 82.9 KB
/
Copy pathclient.cpp
File metadata and controls
2047 lines (1827 loc) · 82.9 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
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.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 <math.h>
#include <algorithm>
#include <sstream>
#include "platform_compat.h"
#include "client.h"
#include "cluster_client.h"
#include "config_types.h"
#include "rate_limiter.h"
#include "retry_policy.h"
void client::apply_arbitrary_tracking_flags(abstract_protocol *protocol)
{
// Mirror the per-element miss-tracking decision made in setup_client onto a
// single protocol. In cluster mode shard connections are *re-created* (not
// reconnected in place) on topology reset -- cluster_client::disconnect()
// deletes the non-main connections and the next cluster-slots discovery
// rebuilds them via create_shard_connection(). Each rebuild clone()s a fresh
// protocol with runtime flags reset to defaults, so the flag must be
// re-applied here or miss tracking silently never engages for them. (An
// in-place reconnect keeps the same protocol object; reset_state() preserves
// the flag, so that path needs nothing.) See issue #476.
if (protocol == NULL) return;
if (m_arbitrary_needs_elem_tracking) {
protocol->set_track_elem_misses(true);
}
}
bool client::setup_client(benchmark_config *config, abstract_protocol *protocol, object_generator *objgen)
{
m_config = config;
assert(m_config != NULL);
unsigned long long total_num_of_clients = static_cast<unsigned long long>(config->clients) * config->threads;
m_request_rate_phase_microsecond =
calculate_rate_limit_phase(config->request_interval_microsecond, config->next_client_idx, total_num_of_clients);
// create main connection
shard_connection *conn = new shard_connection(m_connections.size(), this, m_config, m_event_base, protocol,
m_request_rate_phase_microsecond);
m_connections.push_back(conn);
m_obj_gen = objgen->clone();
assert(m_obj_gen != NULL);
if (config->distinct_client_seed && config->randomize)
m_obj_gen->set_random_seed(config->randomize + config->next_client_idx);
else if (config->randomize)
m_obj_gen->set_random_seed(config->randomize);
else if (config->distinct_client_seed)
m_obj_gen->set_random_seed(config->next_client_idx);
m_obj_gen->fill_value_buffer();
// Setup first arbitrary command
if (config->arbitrary_commands->is_defined()) advance_arbitrary_command_index();
// Enable value keeping for SCAN incremental iteration (needed to extract cursor from response)
if (config->scan_incremental_iteration) {
// The copied commands have matching argument indices; bound both consumers
// of the generated-argument cache even in release builds.
m_scan_args.resize(std::max(config->arbitrary_commands->at(0).command_args.size(),
config->scan_continuation_command->command_args.size()));
MAIN_CONNECTION->get_protocol()->set_keep_value(true);
}
// Enable per-element miss tracking only when a configured command needs
// per-position reply inspection. Only ArrayPerElementNulls
// (HMGET/MGET/ZMSCORE/GEOPOS/...) attributes hits/misses per position; the
// parser records a per-top-level-element hit bitmap directly
// (set_track_elem_misses), with zero reply materialization -- no malloc /
// memcpy of element values, no mbulk tree. EmptyCollection
// (HGETALL/SMEMBERS/LRANGE) only needs the top-level array length
// (response->get_top_array_len()); SingleNullBulk and IntegerMembership use
// the parser's scalar counters / status line. None of them keep values.
if (config->arbitrary_commands->is_defined()) {
for (size_t i = 0; i < config->arbitrary_commands->size(); ++i) {
const arbitrary_command &cmd = config->arbitrary_commands->at(i);
if (!cmd.miss_tracking_enabled || cmd.spec == NULL) continue;
using memtier::command_meta::ReplyShape;
if (cmd.spec->reply_shape == ReplyShape::ArrayPerElementNulls) {
m_arbitrary_needs_elem_tracking = true;
break;
}
}
// Apply to the connections that exist now. Connections created later --
// notably the per-shard connections that cluster_client builds during
// cluster-slots discovery -- pick the flag up via
// apply_arbitrary_tracking_flags() at creation time (see issue #476).
for (size_t i = 0; i < m_connections.size(); ++i) {
apply_arbitrary_tracking_flags(m_connections[i]->get_protocol());
}
}
// Parallel key-pattern determined according to the first command
if ((config->arbitrary_commands->is_defined() && config->arbitrary_commands->at(0).key_pattern == 'P') ||
(config->key_pattern[key_pattern_set] == 'P')) {
unsigned long long client_index = config->next_client_idx % total_num_of_clients;
unsigned long long range = (config->key_maximum - config->key_minimum) / total_num_of_clients + 1;
unsigned long long min = config->key_minimum + (range * client_index);
unsigned long long max = min + range - 1;
if (client_index == (total_num_of_clients - 1)) {
max = config->key_maximum; // the last clients takes the leftover
}
m_obj_gen->set_key_range(min, max);
}
config->next_client_idx++;
m_keylist = new keylist(m_config->multi_key_get + 1);
assert(m_keylist != NULL);
return true;
}
client::client(client_group *group) :
m_event_base(NULL),
m_initialized(false),
m_end_set(false),
m_run_failed(false),
m_end_waits_for_siblings(false),
m_config(NULL),
m_obj_gen(NULL),
m_stats(group->get_config()),
m_reqs_processed(0),
m_reqs_answered(0),
m_reqs_generated(0),
m_set_ratio_count(0),
m_get_ratio_count(0),
m_arbitrary_command_ratio_count(0),
m_executed_command_index(0),
m_arbitrary_command_rotation_seq(0),
m_txn_rotation_key_index(0),
m_txn_rotation_key_valid(false),
m_txn_rotation_key_seq(0),
m_txn_multi_sent(false),
m_txn_reconnect_reqs_base(0),
m_tot_set_ops(0),
m_tot_wait_ops(0),
m_scan_cursor("0"),
m_scan_iteration_count(0),
m_mget_defer(false),
m_arbitrary_needs_elem_tracking(false),
m_request_rate_phase_microsecond(0)
{
m_event_base = group->get_event_base();
if (!setup_client(group->get_config(), group->get_protocol(), group->get_obj_gen())) {
return;
}
benchmark_debug_log("new client %p successfully set up.\n", this);
m_initialized = true;
}
client::client(struct event_base *event_base, benchmark_config *config, abstract_protocol *protocol,
object_generator *obj_gen) :
m_event_base(NULL),
m_initialized(false),
m_end_set(false),
m_run_failed(false),
m_end_waits_for_siblings(false),
m_config(NULL),
m_obj_gen(NULL),
m_stats(config),
m_reqs_processed(0),
m_reqs_answered(0),
m_reqs_generated(0),
m_set_ratio_count(0),
m_get_ratio_count(0),
m_arbitrary_command_ratio_count(0),
m_executed_command_index(0),
m_arbitrary_command_rotation_seq(0),
m_txn_rotation_key_index(0),
m_txn_rotation_key_valid(false),
m_txn_rotation_key_seq(0),
m_txn_multi_sent(false),
m_txn_reconnect_reqs_base(0),
m_tot_set_ops(0),
m_tot_wait_ops(0),
m_scan_cursor("0"),
m_scan_iteration_count(0),
m_keylist(NULL),
m_mget_defer(false),
m_arbitrary_needs_elem_tracking(false),
m_request_rate_phase_microsecond(0)
{
m_event_base = event_base;
if (!setup_client(config, protocol, obj_gen)) {
return;
}
benchmark_debug_log("new client %p successfully set up.\n", this);
m_initialized = true;
}
client::~client()
{
for (unsigned int i = 0; i < m_connections.size(); i++) {
shard_connection *sc = m_connections[i];
delete sc;
}
m_connections.clear();
if (m_obj_gen != NULL) {
delete m_obj_gen;
m_obj_gen = NULL;
}
if (m_keylist != NULL) {
delete m_keylist;
m_keylist = NULL;
}
}
bool client::initialized(void)
{
return m_initialized;
}
void client::disconnect(void)
{
shard_connection *sc = MAIN_CONNECTION;
assert(sc != NULL);
sc->disconnect();
}
void client::disconnect_all(void)
{
unsigned long long abandoned = disconnect_and_abandon_held();
if (abandoned) {
benchmark_error_log("warning: %llu request(s) held for retry when the run ended were not resent; "
"counted as errors.\n",
abandoned);
}
}
unsigned long long client::disconnect_and_abandon_held(void)
{
// This ends the run, once it is finished and no replies are pending. A
// request still held for resend (waiting in a retry queue for its
// backoff, or in a replay queue for a reconnect) is not pending, so it
// is never resent: e.g. a --test-time run whose last replies all
// arrive, after the deadline, as retryable errors. disconnect() moves
// the retry queue into the replay queue; account every request left
// there instead of dropping it silently with the connection. It counts
// as an error but, unlike a refused retry, not as an op: it never got a
// final reply.
unsigned long long abandoned = 0;
for (unsigned int i = 0; i < m_connections.size(); i++) {
shard_connection *sc = m_connections[i];
if (sc != NULL) {
sc->disconnect();
abandoned += sc->abandon_replay_requests("run-ended-before-resend");
}
}
return abandoned;
}
int client::connect(void)
{
struct connect_info addr;
// get primary connection
shard_connection *sc = MAIN_CONNECTION;
assert(sc != NULL);
// get address information
if (m_config->unix_socket == NULL) {
if (m_config->server_addr->get_connect_info(&addr) != 0) {
benchmark_error_log("connect: resolve error: %s\n", m_config->server_addr->get_last_error());
return -1;
}
// Just in case we got domain name and not ip, we convert it
char address[INET6_ADDRSTRLEN];
if (addr.ci_family == PF_INET) {
struct sockaddr_in *ipv4 = (struct sockaddr_in *) addr.ci_addr;
inet_ntop(AF_INET, &(ipv4->sin_addr), address, INET_ADDRSTRLEN);
} else {
struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *) addr.ci_addr;
inet_ntop(AF_INET6, &(ipv6->sin6_addr), address, INET6_ADDRSTRLEN);
}
char port_str[20];
snprintf(port_str, sizeof(port_str) - 1, "%u", m_config->port);
// save address and port
sc->set_address_port(address, port_str);
}
// call connect
int ret = sc->connect(&addr);
if (ret) return ret;
return 0;
}
bool client::finished(void)
{
if (m_config->requests > 0 && m_reqs_processed >= m_config->requests) return true;
if (m_config->test_time > 0) {
if (m_config->clients_start > 0) {
// Staircase mode: use global deadline so all clients stop together
// Compare full timevals: whole seconds alone would end the run
// up to 1 s early when it started late in a second.
struct timeval now, elapsed;
gettimeofday(&now, NULL);
evutil_timersub(&now, &m_config->benchmark_start_time, &elapsed);
if (elapsed.tv_sec >= (time_t) m_config->test_time) return true;
} else {
if (m_stats.get_duration() >= m_config->test_time) return true;
}
}
return false;
}
bool client::deadline_passed_by(const struct timeval &now)
{
// Staircase mode's finished() already reads the wall clock.
return m_config->test_time > 0 && m_config->clients_start == 0 && m_stats.has_started() &&
ts_diff(m_stats.get_start_time(), now) >= (long long) m_config->test_time * 1000000;
}
bool client::holds_retries(void)
{
for (unsigned int i = 0; i < m_connections.size(); i++) {
if (m_connections[i] != NULL && m_connections[i]->holds_retries()) return true;
}
return false;
}
bool client::idle_connection_waits_for_connect(void)
{
bool idle = false, connecting = false;
for (unsigned int i = 0; i < m_connections.size(); i++) {
shard_connection *sc = m_connections[i];
if (sc == NULL) continue;
if (sc->get_connection_state() == conn_in_progress) {
connecting = true;
} else if (sc->get_connection_state() == conn_connected && !sc->may_send_again()) {
idle = true;
}
}
return idle && connecting;
}
bool client::test_time_end(const struct timeval &now, struct timeval *end)
{
if (m_config->test_time == 0 || !m_stats.has_started()) return false;
*end = m_stats.get_start_time();
// Only construct a deadline that lies before now, so a large test time
// cannot overflow Winsock's 32-bit timeval seconds.
if (ts_diff(*end, now) <= (long long) m_config->test_time * 1000000) return false;
end->tv_sec = (long long) end->tv_sec + m_config->test_time;
if (m_reqs_answered && timercmp(&m_last_reply_time, end, >)) *end = m_last_reply_time;
if (timercmp(end, &now, >)) *end = now;
return true;
}
bool client::all_connections_idle(void)
{
for (unsigned int i = 0; i < m_connections.size(); i++) {
shard_connection *sc = m_connections[i];
if (sc != NULL && sc->get_pending_resp() > 0) {
return false;
}
}
return true;
}
void client::set_start_time()
{
// In staircase mode, all clients use the global benchmark start time
// so per-second stats are aligned to the same absolute time origin.
if (m_config->clients_start > 0) {
m_stats.set_start_time(&m_config->benchmark_start_time);
} else {
struct timeval now;
gettimeofday(&now, NULL);
m_stats.set_start_time(&now);
}
}
void client::set_end_time()
{
// update only once
if (!m_end_set) {
benchmark_debug_log("nothing else to do, test is finished.\n");
// A --test-time client that sent workload ends as test_time_end()
// says (#867, #870). One that never had a reply takes part in the
// duration average (#819) and ends at its deadline.
struct timeval now, end;
gettimeofday(&now, NULL);
set_end_time_at(has_submitted_workload() && test_time_end(now, &end) ? &end : &now);
}
}
void client::set_end_time_interrupted(struct timeval *end_time)
{
if (m_end_set) return;
// A client whose connection completed in the loop iteration that the
// interrupt ended may have started after the interrupt time.
struct timeval start_time = m_stats.get_start_time();
if (m_stats.has_started() && timercmp(end_time, &start_time, <)) end_time = &start_time;
// Interrupting the drain after a timed run ends it as set_end_time()
// does: the idle time after the last reply is not in its duration.
struct timeval end;
if (test_time_end(*end_time, &end)) end_time = &end;
m_stats.set_end_time(end_time);
m_end_set = true;
}
bool client::abandon_unanswered_requests(unsigned long long *unanswered, unsigned long long *held)
{
if (m_end_set || m_config->test_time == 0) return false;
if (m_stats.get_duration_usec() < (unsigned long long) (m_config->test_time + TEST_TIME_DRAIN_GRACE_SECS) * 1000000)
return false;
// Only a client that is waiting for replies, or that keeps resending
// --retry-on-error retries that never succeed (#715): one with nothing
// in flight ends by itself, or is waiting for a reconnect. A retry held
// for its backoff is not pending. Also one that waits for a sibling that
// may still send: a connection already tried to end it once the run was
// over (shard_connection::end_client_after_run()), or one is up and idle
// past the deadline while another is connecting
// (idle_connection_waits_for_connect()). Without
// --connection-timeout, a redial whose SYN is dropped would keep it
// waiting for the kernel's connect timeout (about 2 minutes).
if (all_connections_idle() && !holds_retries() && !m_end_waits_for_siblings && !idle_connection_waits_for_connect())
return false;
// Drop them before disconnecting, so --retry-on-error does not hold them
// for a resend that will never come (they would then be counted a
// second time). Workload requests that never got a reply are errors,
// not ops (drop_pending_requests() counts them through
// abandon_requests()); setup commands are not counted.
unsigned int abandoned = 0;
for (unsigned int i = 0; i < m_connections.size(); i++) {
if (m_connections[i] != NULL) abandoned += m_connections[i]->drop_pending_requests();
}
m_stats.add_unanswered_requests(abandoned);
*unanswered += abandoned;
// The run measured --test-time and the replies drained after it, not
// the grace period spent waiting.
struct timeval now, end;
gettimeofday(&now, NULL);
set_end_time_at(test_time_end(now, &end) ? &end : &now);
// The caller reports the requests held for retry with the others.
*held += disconnect_and_abandon_held();
return true;
}
void client::set_end_time_at(struct timeval *end_time)
{
if (!m_end_set) {
m_stats.set_end_time(end_time);
m_end_set = true;
// A connection whose setup the server rejected since its last reply
// (a required replica, say) and that never recovered fails the run
// (#630), also when another connection ends the client first. Apply
// this at a normal end and when a failed connect or drain-grace expiry
// caps the stats at the deadline: which connection ends first is only
// timing.
for (unsigned int i = 0; i < m_connections.size(); i++) {
shard_connection *sc = m_connections[i];
if (sc != NULL && sc->stops_at_deadline() && sc->setup_failed_since_reply()) m_run_failed = true;
}
}
}
bool client::transaction_reconnect_due() const
{
if (!m_config->reconnect_interval || m_reqs_generated < m_txn_reconnect_reqs_base ||
m_reqs_generated - m_txn_reconnect_reqs_base < m_config->reconnect_interval)
return false;
// The next command must be the first executable entry at the start of
// its ratio. Checking only MULTI state would split a WATCH prefix, while
// checking only the command index would split a weighted first entry.
for (unsigned int i = 0; i < m_config->arbitrary_commands->size(); i++) {
const arbitrary_command &cmd = m_config->arbitrary_commands->at(i);
if (!cmd.stats_only && cmd.ratio > 0)
return m_executed_command_index == i && m_arbitrary_command_ratio_count == 1;
}
return false;
}
bool client::prepare_transaction_reconnect()
{
if (!transaction_reconnect_due()) return false;
// No new work is generated until the replies for this rotation drain.
// Advance the baseline rather than testing a modulus: the boundary can
// be beyond the requested interval, including after an unplanned loss.
m_txn_reconnect_reqs_base = m_reqs_processed;
return true;
}
bool client::hold_pipeline(unsigned int conn_id)
{
// don't exceed requests
if (m_config->requests) {
if (m_reqs_generated >= m_config->requests) return true;
}
// if we have reconnect_interval stop enlarging the pipeline on time
if (m_config->reconnect_interval) {
if (m_config->transaction) return transaction_reconnect_due();
if ((m_reqs_processed % m_config->reconnect_interval) + (m_reqs_generated - m_reqs_processed) >=
m_config->reconnect_interval)
return true;
}
return false;
}
get_key_response client::get_key_for_conn(unsigned int command_index, unsigned int conn_id,
unsigned long long *key_index)
{
int iter;
if (m_config->arbitrary_commands->is_defined())
iter = arbitrary_obj_iter_type(command_index);
else
iter = obj_iter_type(m_config, command_index);
*key_index = m_obj_gen->get_key_index(iter);
if (!m_config->data_import || m_config->generate_keys) {
m_obj_gen->generate_key(*key_index);
} else {
/* For SET command we already read a completes item (see create_set_request()) */
if (command_index == GET_CMD_IDX) dynamic_cast<import_object_generator *>(m_obj_gen)->read_next_key(*key_index);
}
return available_for_conn;
}
// --monitor-input "__monitor_line@__": replace the first __key__ in an
// argument with a generated key, keeping the text around it (e.g.
// {tag}__key__ or user:__key__; like the --command path, any later __key__
// in the same argument stays literal). Call it after split_command_to_args()
// and before format_arbitrary_command(). Resolved arguments are marked
// `resolved`, so format_arbitrary_command() frames them as constants without
// scanning the generated text for placeholders again, and cluster mode can
// route by the key that is actually sent. Argument 1 after resolution (a
// literal or a generated key) is kept in cmd.resolved_key for the request's
// log key: it is what cluster mode hashes to pick the shard, so
// --failed-keys-file and --retry-on-error see the same key the router used.
// A bare __data__ (other than as the first argument) is left for
// format_arbitrary_command() to mark data_type: write_monitor_command_args()
// writes the value at send time, without copying it into the command.
// Each __data__ is sized under --data-size-pattern=S by the most recent
// __key__ before it, as in create_arbitrary_request().
void client::resolve_monitor_placeholders(arbitrary_command &cmd, unsigned int command_index, unsigned int conn_id)
{
// 0 until the first __key__: get_value() clamps it to --key-minimum.
unsigned long long last_key_index = 0;
// Argument 0 is the command name.
for (size_t i = 1; i < cmd.command_args.size(); i++) {
command_arg &arg = cmd.command_args[i];
size_t pos = arg.data.find(KEY_PLACEHOLDER);
if (pos == std::string::npos) {
arg.data_key_index = last_key_index;
// The first argument is what cluster mode routes by, so a bare
// __data__ there is filled in now rather than at send time. No
// __key__ precedes it, so it gets the minimum size under
// --data-size-pattern=S (the index 0 is clamped to --key-minimum).
if (i == 1 && arg.data == DATA_PLACEHOLDER) {
unsigned int value_len;
const char *value = m_obj_gen->get_value(last_key_index, &value_len);
assert(value != NULL);
assert(value_len > 0);
arg.data.assign(value, value_len);
arg.resolved = true;
}
continue;
}
unsigned long long key_index;
// Base-class lookup: cluster_client routes by the resolved key
// afterwards, so its per-shard key pool must not be used here.
get_key_response res = client::get_key_for_conn(command_index, conn_id, &key_index);
assert(res == available_for_conn);
(void) res;
last_key_index = key_index;
arg.data.replace(pos, strlen(KEY_PLACEHOLDER), m_obj_gen->get_key(), m_obj_gen->get_key_len());
arg.resolved = true;
}
if (cmd.command_args.size() >= 2) cmd.resolved_key = cmd.command_args[1].data;
}
// Write a formatted __monitor_line@__ command (see
// resolve_monitor_placeholders()) to conn_id: constant arguments as they are,
// a __data__ argument with a value generated now. Returns the bytes written.
int client::write_monitor_command_args(const arbitrary_command &cmd, unsigned int conn_id)
{
int cmd_size = 0;
for (unsigned int i = 0; i < cmd.command_args.size(); i++) {
const command_arg *arg = &cmd.command_args[i];
if (arg->type == const_type) {
cmd_size += m_connections[conn_id]->send_arbitrary_command(arg);
} else if (arg->type == data_type) {
unsigned int value_len;
const char *value = m_obj_gen->get_value(arg->data_key_index, &value_len);
assert(value != NULL);
assert(value_len > 0);
cmd_size += m_connections[conn_id]->send_arbitrary_command(arg, value, value_len);
}
}
// Attach the key only to a command that is going out, so it cannot leak
// onto the next request when nothing was written.
if (cmd_size > 0) {
m_connections[conn_id]->set_arbitrary_command_key(cmd.resolved_key.data(),
(unsigned int) cmd.resolved_key.size());
}
return cmd_size;
}
bool client::create_arbitrary_request(unsigned int command_index, struct timeval ×tamp, unsigned int conn_id)
{
int cmd_size = 0;
const arbitrary_command &cmd = get_arbitrary_command(command_index);
benchmark_debug_log("%s: %s:\n", m_connections[conn_id]->get_readable_id(), cmd.command.c_str());
// Check if this is a monitor command placeholder - handle it specially
if (cmd.command_args.size() == 1 && cmd.command_args[0].type == monitor_random_type) {
// Select a command from the monitor file at runtime based on the monitor pattern
size_t selected_index = 0;
const std::string *monitor_cmd_ptr = NULL;
if (m_config->monitor_pattern == 'R') {
monitor_cmd_ptr = &m_config->monitor_commands->get_random_command(m_obj_gen, &selected_index);
benchmark_debug_log("%s: random monitor command selected (q%zu): %s\n",
m_connections[conn_id]->get_readable_id(),
selected_index + 1, // 1-based index for user display
monitor_cmd_ptr->c_str());
} else {
monitor_cmd_ptr = &m_config->monitor_commands->get_next_sequential_command(&selected_index);
benchmark_debug_log("%s: sequential monitor command selected (q%zu): %s\n",
m_connections[conn_id]->get_readable_id(),
selected_index + 1, // 1-based index for user display
monitor_cmd_ptr->c_str());
}
const std::string &monitor_cmd = *monitor_cmd_ptr;
// Parse and format the monitor command into a temporary arbitrary_command
arbitrary_command temp_cmd(monitor_cmd.c_str());
if (!temp_cmd.split_command_to_args()) {
fprintf(stderr, "warning: skipping malformed monitor command at line %zu: %s\n", selected_index + 1,
monitor_cmd.c_str());
return true; // Skip this command but continue processing
}
resolve_monitor_placeholders(temp_cmd, command_index, conn_id);
// Format the command for the protocol (adds RESP headers)
if (!m_connections[conn_id]->get_protocol()->format_arbitrary_command(temp_cmd)) {
fprintf(stderr, "warning: skipping unformattable monitor command at line %zu: %s\n", selected_index + 1,
monitor_cmd.c_str());
return true; // Skip this command but continue processing
}
// Send the randomly selected command
cmd_size = write_monitor_command_args(temp_cmd, conn_id);
// Get the stats index for the actual command type (e.g., SET, GET)
// instead of using the placeholder's index
size_t stats_index = m_config->monitor_commands->get_stats_index(selected_index);
m_connections[conn_id]->send_arbitrary_command_end(stats_index, ×tamp, cmd_size, temp_cmd.replies);
return true;
}
// Normal arbitrary command handling
const bool scan_incremental_iteration = m_config->scan_incremental_iteration;
// Key index of the last __key__ sent, which sizes a following __data__
// under --data-size-pattern=S the way create_set_request() does. With no
// preceding __key__, get_value() clamps 0 to --key-minimum.
unsigned long long data_key_index = 0;
for (unsigned int i = 0; i < cmd.command_args.size(); i++) {
const command_arg *arg = &cmd.command_args[i];
if (arg->type == const_type) {
cmd_size += m_connections[conn_id]->send_arbitrary_command(arg);
} else if (arg->type == key_type) {
// --transaction: reuse one key for every __key__ in the rotation so
// the whole WATCH/MULTI/EXEC unit resolves to a single key/slot.
// Non-cluster path only: in --cluster-mode, cluster_client drives the
// reuse by pushing the rotation key onto m_key_index_pools and relies
// on this method draining it via get_key_for_conn, so the fast path
// here would leave the pool un-drained. Also skip the data-import
// path, which streams a distinct key per command.
const bool txn_reuse =
m_config->transaction && !m_config->cluster_mode && (!m_config->data_import || m_config->generate_keys);
if (txn_reuse && m_txn_rotation_key_valid && m_txn_rotation_key_seq == m_arbitrary_command_rotation_seq) {
// Same rotation as the cached key: regenerate the identical key
// string without advancing the per-iter key cursor.
m_obj_gen->generate_key(m_txn_rotation_key_index);
data_key_index = m_txn_rotation_key_index;
} else {
unsigned long long key_index;
get_key_response res = get_key_for_conn(command_index, conn_id, &key_index);
/* If key not available for this connection, we have a bug of sending partial request */
assert(res == available_for_conn);
data_key_index = key_index;
if (txn_reuse) {
// First keyed command of the rotation: adopt this key for
// the rest of the rotation.
m_txn_rotation_key_index = key_index;
m_txn_rotation_key_valid = true;
m_txn_rotation_key_seq = m_arbitrary_command_rotation_seq;
}
}
if (scan_incremental_iteration) {
assert(i < m_scan_args.size());
m_scan_args[i] = arg->data_prefix;
m_scan_args[i].append(m_obj_gen->get_key(), m_obj_gen->get_key_len());
m_scan_args[i].append(arg->data_suffix);
cmd_size +=
m_connections[conn_id]->send_arbitrary_command(arg, m_scan_args[i].data(), m_scan_args[i].size());
} else if (arg->has_key_affixes) {
// Static data mixed with the key placeholder.
// Pre-calculate total length to avoid reallocations
const char *key = m_obj_gen->get_key();
unsigned int key_len = m_obj_gen->get_key_len();
size_t prefix_len = arg->data_prefix.length();
size_t suffix_len = arg->data_suffix.length();
size_t total_len = prefix_len + key_len + suffix_len;
// Optimization: use stack buffer for small keys to avoid heap allocation
if (total_len < KEY_BUFFER_STACK_SIZE) {
char stack_buffer[KEY_BUFFER_STACK_SIZE];
char *pos = stack_buffer;
// Manual copy for better performance
if (prefix_len > 0) {
memcpy(pos, arg->data_prefix.data(), prefix_len);
pos += prefix_len;
}
memcpy(pos, key, key_len);
pos += key_len;
if (suffix_len > 0) {
memcpy(pos, arg->data_suffix.data(), suffix_len);
}
cmd_size += m_connections[conn_id]->send_arbitrary_command(arg, stack_buffer, total_len);
} else {
// Fallback to string for large keys
std::string combined_key;
combined_key.reserve(total_len);
combined_key.append(arg->data_prefix);
combined_key.append(key, key_len);
combined_key.append(arg->data_suffix);
cmd_size += m_connections[conn_id]->send_arbitrary_command(arg, combined_key.c_str(),
combined_key.length());
}
} else {
cmd_size +=
m_connections[conn_id]->send_arbitrary_command(arg, m_obj_gen->get_key(), m_obj_gen->get_key_len());
}
} else if (arg->type == data_type) {
unsigned int value_len;
const char *value = m_obj_gen->get_value(data_key_index, &value_len);
assert(value != NULL);
assert(value_len > 0);
if (scan_incremental_iteration) {
assert(i < m_scan_args.size());
m_scan_args[i].assign(value, value_len);
}
cmd_size += m_connections[conn_id]->send_arbitrary_command(arg, value, value_len);
}
}
m_connections[conn_id]->send_arbitrary_command_end(command_index, ×tamp, cmd_size, cmd.replies);
return true;
}
bool client::create_scan_continuation_request(struct timeval ×tamp, unsigned int conn_id, unsigned int stats_index)
{
int cmd_size = 0;
arbitrary_command *cmd = m_config->scan_continuation_command;
benchmark_debug_log("%s: SCAN continuation cursor=%s\n", m_connections[conn_id]->get_readable_id(),
m_scan_cursor.c_str());
for (unsigned int i = 0; i < cmd->command_args.size(); i++) {
const command_arg *arg = &cmd->command_args[i];
if (arg->type == const_type) {
cmd_size += m_connections[conn_id]->send_arbitrary_command(arg);
} else if (arg->type == scan_cursor_type) {
cmd_size +=
m_connections[conn_id]->send_arbitrary_command(arg, m_scan_cursor.c_str(), m_scan_cursor.length());
} else if (arg->type == key_type || arg->type == data_type) {
assert(i < m_scan_args.size());
const std::string &value = m_scan_args[i];
cmd_size += m_connections[conn_id]->send_arbitrary_command(arg, value.data(), value.size());
}
}
m_connections[conn_id]->send_arbitrary_command_end(stats_index, ×tamp, cmd_size);
return true;
}
bool client::create_wait_request(struct timeval ×tamp, unsigned int conn_id)
{
unsigned int num_slaves = m_obj_gen->random_range(m_config->num_slaves.min, m_config->num_slaves.max);
unsigned int timeout = m_obj_gen->normal_distribution(
m_config->wait_timeout.min, m_config->wait_timeout.max, 0,
((m_config->wait_timeout.max - m_config->wait_timeout.min) / 2.0) + m_config->wait_timeout.min);
m_connections[conn_id]->send_wait_command(×tamp, num_slaves, timeout);
return true;
}
bool client::create_set_request(struct timeval ×tamp, unsigned int conn_id)
{
unsigned long long key_index;
get_key_response res = get_key_for_conn(SET_CMD_IDX, conn_id, &key_index);
if (res == not_available) return false;
if (res == available_for_conn) {
unsigned int value_len;
const char *value = m_obj_gen->get_value(key_index, &value_len);
m_connections[conn_id]->send_set_command(×tamp, m_obj_gen->get_key(), m_obj_gen->get_key_len(), value,
value_len, m_obj_gen->get_expiry(), m_config->data_offset);
}
return true;
}
bool client::create_get_request(struct timeval ×tamp, unsigned int conn_id)
{
unsigned long long key_index;
get_key_response res = get_key_for_conn(GET_CMD_IDX, conn_id, &key_index);
if (res == not_available) return false;
if (res == available_for_conn) {
m_connections[conn_id]->send_get_command(×tamp, m_obj_gen->get_key(), m_obj_gen->get_key_len(),
m_config->data_offset);
}
return true;
}
bool client::create_mget_request(struct timeval ×tamp, unsigned int conn_id)
{
unsigned long long key_index;
unsigned int keys_count = m_config->ratio.b - m_get_ratio_count;
if ((int) keys_count > m_config->multi_key_get) keys_count = m_config->multi_key_get;
m_keylist->clear();
for (unsigned int i = 0; i < keys_count; i++) {
get_key_response res = get_key_for_conn(GET_CMD_IDX, conn_id, &key_index);
if (res != available_for_conn) continue;
m_keylist->add_key(m_obj_gen->get_key(), m_obj_gen->get_key_len());
}
if (m_keylist->get_keys_count() == 0) return false;
m_connections[conn_id]->send_mget_command(×tamp, m_keylist);
return true;
}
// This function could use some urgent TLC -- but we need to do it without altering the behavior
void client::create_request(struct timeval timestamp, unsigned int conn_id)
{
// are we using arbitrary command?
if (m_config->arbitrary_commands->is_defined()) {
// SCAN incremental iteration mode: cursor state drives command selection
if (m_config->scan_incremental_iteration) {
if (m_scan_cursor != "0") {
// Send continuation SCAN with current cursor, stats to index 1
if (create_scan_continuation_request(timestamp, conn_id, 1)) {
m_reqs_generated++;
}
} else {
// Send initial SCAN 0, stats to index 0
// Release the transaction key pin before selecting the next scan key.
m_txn_rotation_key_valid = false;
if (create_arbitrary_request(0, timestamp, conn_id)) {
m_reqs_generated++;
}
}
return;
}
const arbitrary_command &cmd = get_arbitrary_command(m_executed_command_index);
/* Cluster mode can fall through to here (an empty key pool), but
* there the MULTI may sit on another connection than conn_id; its
* own check is in cluster_client::create_arbitrary_request(). */
if (m_config->transaction && !m_config->cluster_mode) {
/* The connection lost this rotation's MULTI when it reconnected.
* Sent now, the rest of the block would run outside any
* transaction and its EXEC would fail with "EXEC without MULTI".
* Skip it up to and including the EXEC/DISCARD; the server already
* discarded the commands queued before. */
if (m_txn_multi_sent && cmd.multi_effect != multi_effect_opens &&
!m_connections[conn_id]->is_multi_open()) {
benchmark_debug_log("--transaction: MULTI lost on reconnect; skipping command %u\n",
m_executed_command_index);
if (cmd.multi_effect == multi_effect_closes) m_txn_multi_sent = false;
advance_arbitrary_command_index();
return;
}
}
if (create_arbitrary_request(m_executed_command_index, timestamp, conn_id)) {
if (cmd.multi_effect == multi_effect_opens) {
m_txn_multi_sent = true;
} else if (cmd.multi_effect == multi_effect_closes) {
m_txn_multi_sent = false;
}
advance_arbitrary_command_index();
m_reqs_generated++;
}
return;
}
// If the Set:Wait ratio is not 0, start off with WAITs
if (m_config->wait_ratio.b &&
(m_tot_wait_ops == 0 || (m_tot_set_ops / m_tot_wait_ops > m_config->wait_ratio.a / m_config->wait_ratio.b))) {
if (!create_wait_request(timestamp, conn_id)) return;
m_reqs_generated++;
m_tot_wait_ops++;
}
// are we set or get? this depends on the ratio
else if (m_set_ratio_count < m_config->ratio.a) {
/* Before we can create a SET request, we need to read the next imported item */
if (m_config->data_import) {
dynamic_cast<import_object_generator *>(m_obj_gen)->read_next_item();
}
if (!create_set_request(timestamp, conn_id)) return;
m_set_ratio_count++;
m_reqs_generated++;
m_tot_set_ops++;
} else if (m_get_ratio_count < m_config->ratio.b) {
// GET command
if (!m_config->multi_key_get) {
if (!create_get_request(timestamp, conn_id)) return;
m_get_ratio_count++;
m_reqs_generated++;
return;