-
Notifications
You must be signed in to change notification settings - Fork 246
Expand file tree
/
Copy pathmemtier_benchmark.cpp
More file actions
5246 lines (4848 loc) · 234 KB
/
Copy pathmemtier_benchmark.cpp
File metadata and controls
5246 lines (4848 loc) · 234 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/>.
*/
// Define _XOPEN_SOURCE before including system headers for ucontext.h on macOS
#ifndef _XOPEN_SOURCE
#define _XOPEN_SOURCE 600
#endif
// _GNU_SOURCE exposes getrusage(RUSAGE_THREAD) on glibc (per-thread CPU
// accounting). Harmless on musl/Alpine, where RUSAGE_THREAD is unconditional.
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "version.h"
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h> // For strcasecmp() on POSIX systems
#include <stdarg.h>
#include <limits.h>
#include <getopt.h>
#include <assert.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <signal.h>
#include <fcntl.h>
#ifdef HAVE_EXECINFO_H
#include <execinfo.h>
#endif
#include <ucontext.h>
#include <time.h>
#include <ctype.h>
#include <sys/utsname.h>
#include <dirent.h>
#include <arpa/inet.h> // inet_pton, ntohl/ntohs for prometheus-bind-addr parsing
#include <netinet/in.h> // struct in_addr / in6_addr / IN6_IS_ADDR_LOOPBACK
#include <event2/event.h>
#include <event2/thread.h>
#ifdef USE_TLS
#include <openssl/crypto.h>
#include <openssl/conf.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#define REDIS_TLS_PROTO_TLSv1 (1 << 0)
#define REDIS_TLS_PROTO_TLSv1_1 (1 << 1)
#define REDIS_TLS_PROTO_TLSv1_2 (1 << 2)
#define REDIS_TLS_PROTO_TLSv1_3 (1 << 3)
/* Use safe defaults */
#ifdef TLS1_3_VERSION
#define REDIS_TLS_PROTO_DEFAULT (REDIS_TLS_PROTO_TLSv1_2 | REDIS_TLS_PROTO_TLSv1_3)
#else
#define REDIS_TLS_PROTO_DEFAULT (REDIS_TLS_PROTO_TLSv1_2)
#endif
#endif
#include <cmath>
#include <cstring>
#include <set>
#include <stdexcept>
#include <atomic>
#include <algorithm>
#ifdef __APPLE__
#include <mach/mach.h>
#endif
#include "client.h"
#include "cluster_client.h"
#include "JSON_handler.h"
#include "obj_gen.h"
#include "memtier_benchmark.h"
#include "run_stats_types.h"
#include "retry_policy.h"
#include "statsd.h"
#include "prometheus_metrics.h"
#include "prometheus_exporter.h"
int log_level = 0;
// Return the basename of a file path (everything after the last '/' or '\').
// Used to redact directory layout from JSON output (e.g. cert/key paths).
static std::string basename_only(const char *p)
{
if (!p || !*p) return "";
std::string s(p);
size_t i = s.find_last_of("/\\");
return (i == std::string::npos) ? s : s.substr(i + 1);
}
// Upper bound for --run-count. main() allocates several per-run vectors
// (run_stats, cmd_stats histograms, HDR histograms) that grow linearly with
// run_count; values in the tens of thousands push tens of MiB of metadata
// before a single op has been sent, and INT_MAX trivially OOMs the allocator
// (issue #426). 1024 covers every realistic benchmarking use case (the
// default is 1) while keeping pre-run allocations comfortably under 100 MiB
// even on memory-constrained hosts.
#define MAX_RUN_COUNT 1024
// Global flag for signal handling
static volatile sig_atomic_t g_interrupted = 0;
// Set when run_benchmark() aborts because --connection-stage-timeout
// elapsed without any thread reaching steady state. main() reads it after
// the run loop to decide between exit(0) and exit(2).
static std::atomic<bool> g_connection_stage_aborted{false};
// Forward declarations
struct cg_thread;
static void print_client_list(FILE *fp, int pid, const char *timestr);
static void print_all_threads_stack_trace(FILE *fp, int pid, const char *timestr);
// Global pointer to threads for crash handler access
static std::vector<cg_thread *> *g_threads = NULL;
#ifdef HAVE_EVHTTP
// Ownership handle for the Prometheus exporter (PLAN.md section 3.1, Decisions
// #2). Lives next to g_threads; cfg.prometheus aliases it. Keeping the global
// reachable means an exporter deliberately leaked on an exit(1) path stays
// LSan-reachable (no suppressions). NULL when the exporter is disabled.
static prometheus_exporter *g_prom_exporter = NULL;
#endif
// ---------------------------------------------------------------------------
// Connection-stage supervisor state (declarations in memtier_benchmark.h)
// ---------------------------------------------------------------------------
//
// Worker threads call report_connection_stage_failure/success() lock-free
// (except for the last-error string update, which uses a tiny mutex). The
// main thread polls connection_stage_should_abort() once per second from
// run_benchmark() while waiting for active_threads to drain.
//
// Lifetimes:
// - reset by connection_stage_supervisor_reset() at the start of every
// run_benchmark() invocation; --run-count > 1 must restart the policy
// because a previous run's success latch is meaningless for the next.
// - g_conn_stage_run_start tracks the time of that reset; we measure
// "elapsed in setup phase" from there, NOT from each individual
// failure, so a single late failure can still trigger the timeout.
static std::atomic<bool> g_conn_stage_steady_state{false};
static std::atomic<long> g_conn_stage_streak_start_sec{0}; // 0 = no failure yet
static std::atomic<long> g_conn_stage_run_start_sec{0};
static pthread_mutex_t g_conn_stage_err_mutex = PTHREAD_MUTEX_INITIALIZER;
static std::string g_conn_stage_last_err; // guarded by g_conn_stage_err_mutex
void connection_stage_supervisor_reset(void)
{
g_conn_stage_steady_state.store(false, std::memory_order_release);
g_conn_stage_streak_start_sec.store(0, std::memory_order_release);
// Must reset g_connection_stage_aborted as well: with --run-count > 1, a
// run-1 abort would otherwise leave the flag latched into run 2,
// suppressing legitimate thread restarts in cg_thread_start() and
// forcing main() to exit with code 2 even after subsequent runs succeed.
g_connection_stage_aborted.store(false, std::memory_order_release);
struct timeval now;
gettimeofday(&now, NULL);
g_conn_stage_run_start_sec.store(now.tv_sec, std::memory_order_release);
pthread_mutex_lock(&g_conn_stage_err_mutex);
g_conn_stage_last_err.clear();
pthread_mutex_unlock(&g_conn_stage_err_mutex);
}
void report_connection_stage_failure(const char *err)
{
// Once any thread has reached steady state we stop policing setup; a
// late "auth failed" log line during a normal --reconnect-on-error
// cycle must not bring the run down.
if (g_conn_stage_steady_state.load(std::memory_order_acquire)) return;
struct timeval now;
gettimeofday(&now, NULL);
// First failure in a streak: stamp the wall-clock start. Subsequent
// failures only update the last-error string. CAS on 0 keeps this
// race-free without a mutex.
long zero = 0;
g_conn_stage_streak_start_sec.compare_exchange_strong(zero, now.tv_sec, std::memory_order_acq_rel);
if (err != NULL && *err != '\0') {
pthread_mutex_lock(&g_conn_stage_err_mutex);
g_conn_stage_last_err.assign(err);
pthread_mutex_unlock(&g_conn_stage_err_mutex);
}
}
void report_connection_stage_success(void)
{
// First call wins; subsequent calls are no-ops. We don't reset
// last_err — it's only read by the supervisor (which is now disarmed)
// and can be useful for post-mortem diagnostics.
bool expected = false;
if (g_conn_stage_steady_state.compare_exchange_strong(expected, true, std::memory_order_acq_rel)) {
g_conn_stage_streak_start_sec.store(0, std::memory_order_release);
}
}
bool connection_stage_should_abort(unsigned int timeout_secs, std::string *out_last_err, unsigned int *out_elapsed)
{
if (timeout_secs == 0) return false; // operator opt-out
if (g_conn_stage_steady_state.load(std::memory_order_acquire)) return false;
struct timeval now;
gettimeofday(&now, NULL);
long streak_start = g_conn_stage_streak_start_sec.load(std::memory_order_acquire);
long run_start = g_conn_stage_run_start_sec.load(std::memory_order_acquire);
// Two trip conditions:
// (a) a failure streak has been live for >= timeout_secs (covers
// AUTH-fail / SELECT-fail / CLUSTER-SLOTS-fail / -ERR reconnect
// loops),
// (b) no failure has ever been observed but the run has been alive
// for >= timeout_secs without anyone reaching steady state
// (covers --wait-ratio 0:1 with no slaves — the connection
// handshakes but the very first WAIT command never returns).
long elapsed_streak = (streak_start > 0) ? (now.tv_sec - streak_start) : 0;
long elapsed_run = (run_start > 0) ? (now.tv_sec - run_start) : 0;
bool trip_streak = (streak_start > 0 && elapsed_streak >= (long) timeout_secs);
bool trip_run = (run_start > 0 && elapsed_run >= (long) timeout_secs);
if (!trip_streak && !trip_run) return false;
if (out_elapsed != NULL) {
*out_elapsed = (unsigned int) (trip_streak ? elapsed_streak : elapsed_run);
}
if (out_last_err != NULL) {
pthread_mutex_lock(&g_conn_stage_err_mutex);
if (!g_conn_stage_last_err.empty()) {
*out_last_err = g_conn_stage_last_err;
} else {
out_last_err->assign("no response from server during setup");
}
pthread_mutex_unlock(&g_conn_stage_err_mutex);
}
return true;
}
// Per-thread alternate signal stack. Without this, SA_ONSTACK is a no-op
// and a SIGSEGV caused by stack-overflow is unrecoverable (the handler
// re-faults on the exhausted stack and produces no report at all).
// 64 KiB is comfortably above SIGSTKSZ on every supported platform.
//
// The buffer lives in TLS (a static __thread array) rather than malloc so
// LeakSanitizer doesn't flag it at clean exit and so the install path is
// allocation-free — workers can call this from cg_thread_start without
// allocating from the main heap. We also skip installation when something
// upstream (e.g. ASan/LSan/UBSan's own runtime) has already registered an
// alt stack for us; replacing theirs would break their crash reporting.
#define MEMTIER_ALT_STACK_SIZE (64 * 1024)
static __thread char tls_altstack_buf[MEMTIER_ALT_STACK_SIZE];
static __thread bool tls_altstack_installed = false;
static void install_alt_signal_stack(void)
{
if (tls_altstack_installed) return;
stack_t existing;
// If a previous installer (sanitizer runtime, parent process, etc.)
// already registered a usable alt stack, leave it alone. Overwriting
// it discards the sanitizer's crash plumbing -- briefly tried gating
// on MEMTIER_ALT_STACK_SIZE here to enforce a larger floor, but that
// tripped every ASAN cell in CI because ASAN's own alt stack is below
// 64 KiB. Adopting an undersized stack risks our handler having less
// room (already a documented trade-off in #412 follow-ups); breaking
// the sanitizer is worse.
if (sigaltstack(NULL, &existing) == 0 && (existing.ss_flags & SS_DISABLE) == 0 && existing.ss_sp != NULL &&
existing.ss_size >= (size_t) MINSIGSTKSZ) {
tls_altstack_installed = true;
return;
}
stack_t ss;
ss.ss_sp = tls_altstack_buf;
ss.ss_flags = 0;
ss.ss_size = sizeof(tls_altstack_buf);
if (sigaltstack(&ss, NULL) == 0) {
tls_altstack_installed = true;
}
}
// Signal handler for Ctrl+C
static void sigint_handler(int signum)
{
(void) signum; // unused parameter
g_interrupted = 1;
}
// Crash handler - prints stack trace and other debugging information
static void crash_handler(int sig, siginfo_t *info, void *secret)
{
(void) secret; // unused parameter
struct tm *tm;
time_t now;
char timestr[64];
// Watchdog: if the handler itself hangs (e.g. mid-print_client_list while
// iterating a torn vector under heap corruption), the process is killed
// after 5 s instead of leaving a half-written report indefinitely. The
// original signal will be re-raised on a fresh sigaction below, but if
// we never get there, SIGALRM provides the floor.
alarm(5);
// Get current time
now = time(NULL);
tm = localtime(&now);
strftime(timestr, sizeof(timestr), "%d %b %Y %H:%M:%S", tm);
// Print crash header
fprintf(stderr, "\n\n=== MEMTIER_BENCHMARK BUG REPORT START: Cut & paste starting from here ===\n");
fprintf(stderr, "[%d] %s # memtier_benchmark crashed by signal: %d\n", getpid(), timestr, sig);
// Print signal information
const char *signal_name = "UNKNOWN";
switch (sig) {
case SIGSEGV:
signal_name = "SIGSEGV";
break;
case SIGBUS:
signal_name = "SIGBUS";
break;
case SIGFPE:
signal_name = "SIGFPE";
break;
case SIGILL:
signal_name = "SIGILL";
break;
case SIGABRT:
signal_name = "SIGABRT";
break;
}
fprintf(stderr, "[%d] %s # Crashed running signal <%s>\n", getpid(), timestr, signal_name);
if (info) {
fprintf(stderr, "[%d] %s # Signal code: %d\n", getpid(), timestr, info->si_code);
fprintf(stderr, "[%d] %s # Fault address: %p\n", getpid(), timestr, info->si_addr);
}
// Print stack trace for all threads
print_all_threads_stack_trace(stderr, getpid(), timestr);
// Print system information
fprintf(stderr, "\n[%d] %s # --- INFO OUTPUT\n", getpid(), timestr);
struct utsname name;
if (uname(&name) == 0) {
fprintf(stderr, "[%d] %s # os:%s %s %s\n", getpid(), timestr, name.sysname, name.release, name.machine);
}
fprintf(stderr, "[%d] %s # memtier_version:%s\n", getpid(), timestr, PACKAGE_VERSION);
fprintf(stderr, "[%d] %s # memtier_git_sha1:%s\n", getpid(), timestr, MEMTIER_GIT_SHA1);
fprintf(stderr, "[%d] %s # memtier_git_dirty:%s\n", getpid(), timestr, MEMTIER_GIT_DIRTY);
#if defined(__x86_64__) || defined(_M_X64)
fprintf(stderr, "[%d] %s # arch_bits:64\n", getpid(), timestr);
#elif defined(__i386__) || defined(_M_IX86)
fprintf(stderr, "[%d] %s # arch_bits:32\n", getpid(), timestr);
#elif defined(__aarch64__)
fprintf(stderr, "[%d] %s # arch_bits:64\n", getpid(), timestr);
#elif defined(__arm__)
fprintf(stderr, "[%d] %s # arch_bits:32\n", getpid(), timestr);
#else
fprintf(stderr, "[%d] %s # arch_bits:unknown\n", getpid(), timestr);
#endif
#ifdef __GNUC__
fprintf(stderr, "[%d] %s # gcc_version:%d.%d.%d\n", getpid(), timestr, __GNUC__, __GNUC_MINOR__,
__GNUC_PATCHLEVEL__);
#endif
fprintf(stderr, "[%d] %s # libevent_version:%s\n", getpid(), timestr, event_get_version());
#ifdef USE_TLS
fprintf(stderr, "[%d] %s # openssl_version:%s\n", getpid(), timestr, OPENSSL_VERSION_TEXT);
#endif
// Print client connection information
print_client_list(stderr, getpid(), timestr);
fprintf(stderr, "[%d] %s # For more information, please check the core dump if available.\n", getpid(), timestr);
fprintf(stderr, "[%d] %s # To enable core dumps: ulimit -c unlimited\n", getpid(), timestr);
fprintf(stderr, "[%d] %s # Core pattern: /proc/sys/kernel/core_pattern\n", getpid(), timestr);
fprintf(stderr, "\n=== MEMTIER_BENCHMARK BUG REPORT END. Make sure to include from START to END. ===\n\n");
fprintf(stderr, " Please report this bug by opening an issue on github.com/redis/memtier_benchmark\n\n");
// Remove the handler and re-raise the signal to generate core dump
struct sigaction act;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
act.sa_handler = SIG_DFL;
sigaction(sig, &act, NULL);
raise(sig);
}
// Pre-warm the symbols the crash handler will need so the dynamic linker
// has already done a lazy-bind (_dl_fixup) on them by the time a signal
// fires. _dl_fixup is NOT async-signal-safe; calling an unresolved symbol
// for the first time from inside the handler triggers it and frequently
// re-crashes mid-report (this is what truncated the bug report attached
// to issue #404). Cost: a few µs at startup.
static void prewarm_crash_handler(void)
{
#ifdef HAVE_EXECINFO_H
void *trace[4];
int n = backtrace(trace, 4);
// /dev/null discards; we only care about resolving the symbol.
int devnull = open("/dev/null", O_WRONLY);
if (devnull >= 0) {
if (n > 0) backtrace_symbols_fd(trace, n, devnull);
close(devnull);
}
#endif
// Force glibc stdio's first-use init + symbol bind for fprintf/vfprintf.
fprintf(stderr, "%s", "");
fflush(stderr);
// Resolve event_get_version too — used in the INFO section.
(void) event_get_version();
}
// Setup crash handlers
static void setup_crash_handlers(void)
{
// Install the per-thread alternate signal stack BEFORE registering the
// handler. Without sigaltstack(2) the SA_ONSTACK flag is silently inert
// and a stack-overflow SIGSEGV re-faults on the exhausted stack —
// producing no report at all. (Workers install their own alt stack on
// entry in cg_thread_start.)
install_alt_signal_stack();
// Pre-warm before we register the handler so the symbols we'll need
// are already bound when the signal lands.
prewarm_crash_handler();
struct sigaction act;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
act.sa_sigaction = crash_handler;
sigaction(SIGSEGV, &act, NULL);
sigaction(SIGBUS, &act, NULL);
sigaction(SIGFPE, &act, NULL);
sigaction(SIGILL, &act, NULL);
sigaction(SIGABRT, &act, NULL);
// SIGALRM is the handler's own watchdog; if alarm(5) fires we want the
// default action (terminate the process) rather than re-entering the
// handler. Explicitly request SIG_DFL so the user can't have overridden
// it inadvertently.
struct sigaction alarm_act;
sigemptyset(&alarm_act.sa_mask);
alarm_act.sa_flags = 0;
alarm_act.sa_handler = SIG_DFL;
sigaction(SIGALRM, &alarm_act, NULL);
}
void benchmark_log_file_line(int level, const char *filename, unsigned int line, const char *fmt, ...)
{
if (level > log_level) return;
va_list args;
char fmtbuf[1024];
// Bound the concatenation so a future refactor that lets `fmt` reach this
// function from a user-controlled source can't overflow `fmtbuf`. Today
// every caller passes a literal, but the previous strcat() relied on that
// invariant silently.
int n = snprintf(fmtbuf, sizeof(fmtbuf), "%s:%u: ", filename, line);
if (n < 0) n = 0;
if ((size_t) n >= sizeof(fmtbuf)) n = (int) sizeof(fmtbuf) - 1;
snprintf(fmtbuf + n, sizeof(fmtbuf) - (size_t) n, "%s", fmt);
va_start(args, fmt);
vfprintf(stderr, fmtbuf, args);
va_end(args);
}
void benchmark_log(int level, const char *fmt, ...)
{
if (level > log_level) return;
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
}
bool is_redis_protocol(enum PROTOCOL_TYPE type)
{
return (type == PROTOCOL_REDIS_DEFAULT || type == PROTOCOL_RESP2 || type == PROTOCOL_RESP3);
}
static const char *get_protocol_name(enum PROTOCOL_TYPE type)
{
if (type == PROTOCOL_REDIS_DEFAULT)
return "redis";
else if (type == PROTOCOL_RESP2)
return "resp2";
else if (type == PROTOCOL_RESP3)
return "resp3";
else if (type == PROTOCOL_MEMCACHE_TEXT)
return "memcache_text";
else if (type == PROTOCOL_MEMCACHE_BINARY)
return "memcache_binary";
else
return "none";
}
#ifdef HAVE_EVHTTP
// Comma-joined "key=value" run labels in insertion order (PLAN.md section 5).
// With json_escape, applies JSON string escaping (\, ", and control chars as
// \u00XX) because json_handler::write_obj is a raw vfprintf passthrough.
static std::string prometheus_run_labels_str(struct benchmark_config *cfg, bool json_escape)
{
std::string s;
for (size_t i = 0; i < cfg->prometheus_run_labels.size(); i++) {
if (i > 0) s += ",";
const std::string &k = cfg->prometheus_run_labels[i].first;
const std::string &v = cfg->prometheus_run_labels[i].second;
std::string kv = k + "=" + v;
if (json_escape) {
for (size_t j = 0; j < kv.size(); j++) {
unsigned char c = (unsigned char) kv[j];
if (c == '\\') {
s += "\\\\";
} else if (c == '"') {
s += "\\\"";
} else if (c < 0x20) {
char buf[8];
snprintf(buf, sizeof(buf), "\\u%04x", (unsigned int) c);
s += buf;
} else {
s += (char) c;
}
}
} else {
s += kv;
}
}
return s;
}
// "default" when no custom buckets were given, else %.12g comma-joined seconds
// (same precision as format_le so parsed-float round-trips). PLAN.md section 5.
static std::string prometheus_buckets_str(struct benchmark_config *cfg)
{
if (cfg->prometheus_latency_buckets.empty()) return "default";
std::string s;
char buf[64];
for (size_t i = 0; i < cfg->prometheus_latency_buckets.size(); i++) {
if (i > 0) s += ",";
snprintf(buf, sizeof(buf), "%.12g", cfg->prometheus_latency_buckets[i]);
s += buf;
}
return s;
}
#endif // HAVE_EVHTTP
static void config_print(FILE *file, struct benchmark_config *cfg)
{
char tmpbuf[512];
fprintf(file,
"server = %s\n"
"port = %u\n"
"uri = %s\n"
"unix socket = %s\n"
"address family = %s\n"
"protocol = %s\n"
#ifdef USE_TLS
"tls = %s\n"
"cert = %s\n"
"key = %s\n"
"cacert = %s\n"
"tls_skip_verify = %s\n"
"sni = %s\n"
#endif
"out_file = %s\n"
"client_stats = %s\n"
"run_count = %u\n"
"debug = %u\n"
"requests = %llu\n"
"rate_limit = %u\n"
"clients = %u\n"
"threads = %u\n"
"test_time = %u\n"
"ratio = %u:%u\n"
"pipeline = %u\n"
"transaction = %s\n"
"data_size = %u\n"
"data_offset = %u\n"
"random_data = %s\n"
"data_size_range = %u-%u\n"
"data_size_list = %s\n"
"data_size_pattern = %s\n"
"expiry_range = %u-%u\n"
"data_import = %s\n"
"data_verify = %s\n"
"verify_only = %s\n"
"generate_keys = %s\n"
"key_prefix = %s\n"
"key_minimum = %llu\n"
"key_maximum = %llu\n"
"key_pattern = %s\n"
"key_stddev = %f\n"
"key_median = %f\n"
"reconnect_interval = %u\n"
"retry_on_error = %s\n"
"max_retries = %d\n"
"retry_backoff_ms = %u\n"
"retry_backoff_factor = %f\n"
"retry_on = %s\n"
"max_retry_queue = %u\n"
"failed_keys_file = %s\n"
"connection_timeout = %u\n"
"connection_stage_timeout = %u\n"
"thread_conn_start_min_jitter_micros = %u\n"
"thread_conn_start_max_jitter_micros = %u\n"
"multi_key_get = %u\n"
"authenticate = %s\n"
"select-db = %d\n"
"no-expiry = %s\n"
"wait-ratio = %u:%u\n"
"num-slaves = %u-%u\n"
"wait-timeout = %u-%u\n"
"json-out-file = %s\n"
"print-all-runs = %s\n"
#ifdef HAVE_EVHTTP
"prometheus-port = %d\n"
"prometheus-bind-addr = %s\n"
"prometheus-run-labels = %s\n"
"prometheus-latency-buckets = %s\n"
#endif
,
cfg->server, cfg->port, cfg->uri ? cfg->uri : "", cfg->unix_socket,
cfg->resolution == AF_UNSPEC ? "Unspecified"
: cfg->resolution == AF_INET ? "AF_INET"
: "AF_INET6",
get_protocol_name(cfg->protocol),
#ifdef USE_TLS
cfg->tls ? "yes" : "no", cfg->tls_cert, cfg->tls_key, cfg->tls_cacert, cfg->tls_skip_verify ? "yes" : "no",
cfg->tls_sni,
#endif
cfg->out_file, cfg->client_stats, cfg->run_count, cfg->debug, cfg->requests, cfg->request_rate,
cfg->clients, cfg->threads, cfg->test_time, cfg->ratio.a, cfg->ratio.b, cfg->pipeline,
cfg->transaction ? "yes" : "no", cfg->data_size, cfg->data_offset, cfg->random_data ? "yes" : "no",
cfg->data_size_range.min, cfg->data_size_range.max, cfg->data_size_list.print(tmpbuf, sizeof(tmpbuf) - 1),
cfg->data_size_pattern, cfg->expiry_range.min, cfg->expiry_range.max, cfg->data_import,
cfg->data_verify ? "yes" : "no", cfg->verify_only ? "yes" : "no", cfg->generate_keys ? "yes" : "no",
cfg->key_prefix, cfg->key_minimum, cfg->key_maximum, cfg->key_pattern, cfg->key_stddev, cfg->key_median,
cfg->reconnect_interval, cfg->retry_on_error ? "yes" : "no", cfg->max_retries, cfg->retry_backoff_ms,
cfg->retry_backoff_factor, cfg->retry_on_filter ? cfg->retry_on_filter : "", cfg->max_retry_queue,
cfg->failed_keys_file ? cfg->failed_keys_file : "", cfg->connection_timeout, cfg->connection_stage_timeout,
cfg->thread_conn_start_min_jitter_micros, cfg->thread_conn_start_max_jitter_micros, cfg->multi_key_get,
cfg->authenticate ? cfg->authenticate : "", cfg->select_db, cfg->no_expiry ? "yes" : "no",
cfg->wait_ratio.a, cfg->wait_ratio.b, cfg->num_slaves.min, cfg->num_slaves.max, cfg->wait_timeout.min,
cfg->wait_timeout.max, cfg->json_out_file, cfg->print_all_runs ? "yes" : "no"
#ifdef HAVE_EVHTTP
,
cfg->prometheus_port, cfg->prometheus_bind_addr ? cfg->prometheus_bind_addr : "127.0.0.1",
prometheus_run_labels_str(cfg, false).c_str(), prometheus_buckets_str(cfg).c_str()
#endif
);
}
static void config_print_to_json(json_handler *jsonhandler, struct benchmark_config *cfg)
{
char tmpbuf[512];
jsonhandler->open_nesting("configuration");
jsonhandler->write_obj("server", "\"%s\"", cfg->server);
jsonhandler->write_obj("port", "%u", cfg->port);
jsonhandler->write_obj("uri", "\"%s\"", cfg->uri ? cfg->uri : "");
jsonhandler->write_obj("unix socket", "\"%s\"", cfg->unix_socket);
jsonhandler->write_obj("address family", "\"%s\"",
cfg->resolution == AF_UNSPEC ? "Unspecified"
: cfg->resolution == AF_INET ? "AF_INET"
: "AF_INET6");
jsonhandler->write_obj("protocol", "\"%s\"", get_protocol_name(cfg->protocol));
jsonhandler->write_obj("out_file", "\"%s\"", cfg->out_file);
#ifdef USE_TLS
jsonhandler->write_obj("tls", "\"%s\"", cfg->tls ? "true" : "false");
jsonhandler->write_obj("cert", "\"%s\"", basename_only(cfg->tls_cert).c_str());
jsonhandler->write_obj("key", "\"%s\"", basename_only(cfg->tls_key).c_str());
jsonhandler->write_obj("cacert", "\"%s\"", basename_only(cfg->tls_cacert).c_str());
jsonhandler->write_obj("tls_skip_verify", "\"%s\"", cfg->tls_skip_verify ? "true" : "false");
jsonhandler->write_obj("sni", "\"%s\"", cfg->tls_sni);
#endif
jsonhandler->write_obj("client_stats", "\"%s\"", cfg->client_stats);
jsonhandler->write_obj("run_count", "%u", cfg->run_count);
jsonhandler->write_obj("debug", "%u", cfg->debug);
jsonhandler->write_obj("requests", "%llu", cfg->requests);
jsonhandler->write_obj("rate_limit", "%u", cfg->request_rate);
jsonhandler->write_obj("clients", "%u", cfg->clients);
jsonhandler->write_obj("threads", "%u", cfg->threads);
jsonhandler->write_obj("test_time", "%u", cfg->test_time);
jsonhandler->write_obj("ratio", "\"%u:%u\"", cfg->ratio.a, cfg->ratio.b);
jsonhandler->write_obj("pipeline", "%u", cfg->pipeline);
jsonhandler->write_obj("transaction", "\"%s\"", cfg->transaction ? "true" : "false");
jsonhandler->write_obj("data_size", "%u", cfg->data_size);
jsonhandler->write_obj("data_offset", "%u", cfg->data_offset);
jsonhandler->write_obj("random_data", "\"%s\"", cfg->random_data ? "true" : "false");
jsonhandler->write_obj("data_size_range", "\"%u:%u\"", cfg->data_size_range.min, cfg->data_size_range.max);
jsonhandler->write_obj("data_size_list", "\"%s\"", cfg->data_size_list.print(tmpbuf, sizeof(tmpbuf) - 1));
jsonhandler->write_obj("data_size_pattern", "\"%s\"", cfg->data_size_pattern);
jsonhandler->write_obj("expiry_range", "\"%u:%u\"", cfg->expiry_range.min, cfg->expiry_range.max);
jsonhandler->write_obj("data_import", "\"%s\"", cfg->data_import);
jsonhandler->write_obj("data_verify", "\"%s\"", cfg->data_verify ? "true" : "false");
jsonhandler->write_obj("verify_only", "\"%s\"", cfg->verify_only ? "true" : "false");
jsonhandler->write_obj("generate_keys", "\"%s\"", cfg->generate_keys ? "true" : "false");
jsonhandler->write_obj("key_prefix", "\"%s\"", cfg->key_prefix);
jsonhandler->write_obj("key_minimum", "%11u", cfg->key_minimum);
jsonhandler->write_obj("key_maximum", "%11u", cfg->key_maximum);
jsonhandler->write_obj("key_pattern", "\"%s\"", cfg->key_pattern);
jsonhandler->write_obj("key_stddev", "%f", cfg->key_stddev);
jsonhandler->write_obj("key_median", "%f", cfg->key_median);
jsonhandler->write_obj("key_zipf_exp", "%f", cfg->key_zipf_exp);
jsonhandler->write_obj("reconnect_interval", "%u", cfg->reconnect_interval);
jsonhandler->write_obj("retry_on_error", "\"%s\"", cfg->retry_on_error ? "true" : "false");
jsonhandler->write_obj("max_retries", "%d", cfg->max_retries);
jsonhandler->write_obj("retry_backoff_ms", "%u", cfg->retry_backoff_ms);
jsonhandler->write_obj("retry_backoff_factor", "%f", cfg->retry_backoff_factor);
jsonhandler->write_obj("retry_on", "\"%s\"", cfg->retry_on_filter ? cfg->retry_on_filter : "");
jsonhandler->write_obj("max_retry_queue", "%u", cfg->max_retry_queue);
jsonhandler->write_obj("failed_keys_file", "\"%s\"", cfg->failed_keys_file ? cfg->failed_keys_file : "");
jsonhandler->write_obj("connection_timeout", "%u", cfg->connection_timeout);
jsonhandler->write_obj("connection_stage_timeout", "%u", cfg->connection_stage_timeout);
jsonhandler->write_obj("thread_conn_start_min_jitter_micros", "%u", cfg->thread_conn_start_min_jitter_micros);
jsonhandler->write_obj("thread_conn_start_max_jitter_micros", "%u", cfg->thread_conn_start_max_jitter_micros);
jsonhandler->write_obj("multi_key_get", "%u", cfg->multi_key_get);
jsonhandler->write_obj("authenticate", "\"%s\"", cfg->authenticate ? cfg->authenticate : "");
jsonhandler->write_obj("select-db", "%d", cfg->select_db);
jsonhandler->write_obj("no-expiry", "\"%s\"", cfg->no_expiry ? "true" : "false");
jsonhandler->write_obj("wait-ratio", "\"%u:%u\"", cfg->wait_ratio.a, cfg->wait_ratio.b);
jsonhandler->write_obj("num-slaves", "\"%u:%u\"", cfg->num_slaves.min, cfg->num_slaves.max);
jsonhandler->write_obj("wait-timeout", "\"%u-%u\"", cfg->wait_timeout.min, cfg->wait_timeout.max);
jsonhandler->write_obj("print-all-runs", "\"%s\"", cfg->print_all_runs ? "true" : "false");
if (cfg->clients_start > 0) {
jsonhandler->write_obj("clients_start", "%u", cfg->clients_start);
jsonhandler->write_obj("clients_step", "%u", cfg->clients_step);
jsonhandler->write_obj("step_duration", "%u", cfg->step_duration);
}
// Read-preference configuration
{
const char *rp_str = "primary";
switch (cfg->read_preference) {
case rp_secondary:
rp_str = "secondary";
break;
case rp_secondary_preferred:
rp_str = "secondaryPreferred";
break;
case rp_nearest:
rp_str = "nearest";
break;
default:
rp_str = "primary";
break;
}
jsonhandler->write_obj("read_preference", "\"%s\"", rp_str);
const char *rpf_str = "error";
switch (cfg->read_preference_fallback) {
case rpf_queue:
rpf_str = "queue";
break;
case rpf_primary:
rpf_str = "primary";
break;
default:
rpf_str = "error";
break;
}
jsonhandler->write_obj("read_preference_fallback", "\"%s\"", rpf_str);
jsonhandler->write_obj("replica_clients", "%u", cfg->replica_clients);
jsonhandler->write_obj("replicas_per_shard", "%u", cfg->replicas_per_shard);
// --read-server entries as a comma-separated "host:port,host:port,..."
// string. Matches the surrounding key=value style used for
// data_size_list / wait-ratio / etc. Empty when no replica endpoints
// were given.
std::string read_servers_str;
for (size_t i = 0; i < cfg->read_servers.size(); i++) {
if (i > 0) read_servers_str += ",";
char endpoint[256];
snprintf(endpoint, sizeof(endpoint), "%s:%u", cfg->read_servers[i].host.c_str(),
(unsigned int) cfg->read_servers[i].port);
read_servers_str += endpoint;
}
jsonhandler->write_obj("read_servers", "\"%s\"", read_servers_str.c_str());
}
#ifdef HAVE_EVHTTP
// Prometheus configuration (PLAN.md section 5). None of these are secrets.
// Run labels are JSON-escaped because write_obj is a raw vfprintf passthrough.
jsonhandler->write_obj("prometheus-port", "%d", cfg->prometheus_port);
jsonhandler->write_obj("prometheus-bind-addr", "\"%s\"",
cfg->prometheus_bind_addr ? cfg->prometheus_bind_addr : "127.0.0.1");
jsonhandler->write_obj("prometheus-run-labels", "\"%s\"", prometheus_run_labels_str(cfg, true).c_str());
jsonhandler->write_obj("prometheus-latency-buckets", "\"%s\"", prometheus_buckets_str(cfg).c_str());
#endif
jsonhandler->close_nesting();
}
// Parse URI and populate config fields
// Returns 0 on success, -1 on error
static int parse_uri(const char *uri, struct benchmark_config *cfg)
{
if (!uri || strlen(uri) == 0) {
fprintf(stderr, "error: empty URI provided.\n");
return -1;
}
// Make a copy to work with
char *uri_copy = strdup(uri);
if (!uri_copy) {
fprintf(stderr, "error: memory allocation failed.\n");
return -1;
}
char *ptr = uri_copy;
// Parse scheme
char *scheme_end = strstr(ptr, "://");
if (!scheme_end) {
fprintf(stderr, "error: invalid URI format, missing scheme.\n");
free(uri_copy);
return -1;
}
*scheme_end = '\0';
if (strcmp(ptr, "redis") == 0) {
// Regular Redis connection
} else if (strcmp(ptr, "rediss") == 0) {
#ifdef USE_TLS
cfg->tls = true;
#else
fprintf(stderr, "error: TLS not supported in this build.\n");
free(uri_copy);
return -1;
#endif
} else {
fprintf(stderr, "error: unsupported URI scheme '%s'. Use 'redis' or 'rediss'.\n", ptr);
free(uri_copy);
return -1;
}
ptr = scheme_end + 3; // Skip "://"
// Parse user:password@host:port/db
char *auth_end = strchr(ptr, '@');
char *host_start = ptr;
if (auth_end) {
// Authentication present
*auth_end = '\0';
char *colon = strchr(ptr, ':');
if (colon) {
// user:password format
*colon = '\0';
char *user = ptr;
char *password = colon + 1;
// Combine as user:password for authenticate field
int auth_len = strlen(user) + strlen(password) + 2;
char *auth_str = (char *) malloc(auth_len);
if (!auth_str) {
fprintf(stderr, "error: memory allocation failed.\n");
free(uri_copy);
return -1;
}
snprintf(auth_str, auth_len, "%s:%s", user, password);
cfg->authenticate = auth_str;
} else {
// Just password (default user)
cfg->authenticate = strdup(ptr);
}
host_start = auth_end + 1;
}
// Parse host:port/db
char *db_start = strchr(host_start, '/');
if (db_start) {
*db_start = '\0';
db_start++;
if (strlen(db_start) > 0) {
char *endptr;
int db = (int) strtol(db_start, &endptr, 10);
if (*endptr != '\0' || db < 0) {
fprintf(stderr, "error: invalid database number '%s'.\n", db_start);
free(uri_copy);
return -1;
}
cfg->select_db = db;
}
}
// Parse host:port
char *port_start = strchr(host_start, ':');
if (port_start) {
*port_start = '\0';
port_start++;
char *endptr;
unsigned long port = strtoul(port_start, &endptr, 10);
if (*endptr != '\0' || port == 0 || port > 65535) {
fprintf(stderr, "error: invalid port number '%s'.\n", port_start);
free(uri_copy);
return -1;
}
cfg->port = (unsigned short) port;
}
// Set host
if (strlen(host_start) > 0) {
cfg->server = strdup(host_start);
}
free(uri_copy);
return 0;
}
static void config_init_defaults(struct benchmark_config *cfg)
{
cfg->mget_cache = NULL;
if (!cfg->server && !cfg->unix_socket) cfg->server = "localhost";
if (!cfg->port && !cfg->unix_socket) cfg->port = 6379;
if (!cfg->resolution) cfg->resolution = AF_UNSPEC;
if (!cfg->run_count) cfg->run_count = 1;
if (!cfg->clients) cfg->clients = 50;
if (!cfg->threads) cfg->threads = 4;
if (!cfg->ratio.is_defined()) cfg->ratio = config_ratio("1:10");
if (!cfg->pipeline) cfg->pipeline = 1;
if (!cfg->data_size && !cfg->data_size_list.is_defined() && !cfg->data_size_range.is_defined() && !cfg->data_import)
cfg->data_size = 32;
if (cfg->generate_keys || !cfg->data_import) {
if (!cfg->key_prefix) cfg->key_prefix = "memtier-";
if (!cfg->key_maximum) cfg->key_maximum = 10000000;
}
if (!cfg->key_pattern) cfg->key_pattern = "R:R";
if (!cfg->data_size_pattern) cfg->data_size_pattern = "R";
if (cfg->requests == (unsigned long long) -1) {
cfg->requests = cfg->key_maximum - cfg->key_minimum;
if (strcmp(cfg->key_pattern, "P:P") == 0) cfg->requests = cfg->requests / (cfg->clients * cfg->threads) + 1;
printf("setting requests to %llu\n", cfg->requests);
}
if (!cfg->requests && !cfg->test_time) cfg->requests = 10000;
if (!cfg->hdr_prefix) cfg->hdr_prefix = "";
if (!cfg->print_percentiles.is_defined()) cfg->print_percentiles = config_quantiles("50,99,99.9");
if (!cfg->monitor_pattern) cfg->monitor_pattern = 'S';
if (cfg->miss_rate_threshold < 0.0) cfg->miss_rate_threshold = 0.01; // Default: warn above 1%
if (cfg->cpu_warn_threshold < 0.0) cfg->cpu_warn_threshold = 0.95; // Default: warn above 95% of a core
// Default --connection-stage-timeout to 30 s; 0 means "operator disabled".
if (cfg->connection_stage_timeout == UINT_MAX) cfg->connection_stage_timeout = 30;
// StatsD defaults - port only matters if host is set
if (!cfg->statsd_port) cfg->statsd_port = 8125;
if (!cfg->statsd_prefix) cfg->statsd_prefix = "memtier";
if (!cfg->statsd_run_label) cfg->statsd_run_label = "default";
if (!cfg->graphite_port) cfg->graphite_port = 8080;
// Prometheus defaults - bind-addr only matters if --prometheus-port is set.
// NULL at parse time means "user didn't pass it" (so the W1 non-loopback
// warning never fires on the default); the loopback default is applied here,
// after parsing. PLAN.md section 5.
#ifdef HAVE_EVHTTP
if (!cfg->prometheus_bind_addr) cfg->prometheus_bind_addr = "127.0.0.1";
#endif
#ifdef USE_TLS
if (!cfg->tls_protocols) cfg->tls_protocols = REDIS_TLS_PROTO_DEFAULT;