Repository navigation
Expand file tree
/
Copy pathmemtier_benchmark.cpp
More file actions
6876 lines (6411 loc) · 316 KB
/
Copy pathmemtier_benchmark.cpp
File metadata and controls
6876 lines (6411 loc) · 316 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 <chrono>
#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>
#ifndef _WIN32
#include <sys/resource.h>
#endif
#include <signal.h>
#include <fcntl.h>
#include <sys/stat.h>
#ifdef HAVE_EXECINFO_H
#include <execinfo.h>
#endif
#ifndef _WIN32
#include <ucontext.h>
#endif
#include <time.h>
#include <ctype.h>
#ifndef _WIN32
#include <sys/utsname.h>
#endif
#include <dirent.h>
#include "platform_compat.h"
#include "library_versions.h"
#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
#if OPENSSL_VERSION_NUMBER >= 0x40000000L
static bool bitmask_is_contiguous(unsigned int mask);
#endif
// The OpenSSL library actually loaded; OPENSSL_VERSION_* are the headers'.
static const char *openssl_runtime_version_text(void)
{
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
return OpenSSL_version(OPENSSL_VERSION);
#else
return SSLeay_version(SSLEAY_VERSION);
#endif
}
static unsigned long openssl_runtime_version_number(void)
{
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
return OpenSSL_version_num();
#else
return SSLeay();
#endif
}
#endif
// Warn (stderr only) when the libevent or OpenSSL library loaded at run time
// is from another release series than the headers memtier was compiled
// with, e.g. headers of one installation and the library of another.
static void warn_on_library_version_mismatch(void)
{
if (libevent_series_differs(LIBEVENT_VERSION_NUMBER, event_get_version_number())) {
fprintf(stderr,
"warning: memtier_benchmark was built with libevent %s headers but is running with libevent %s; "
"rebuild it against the libevent it runs with.\n",
LIBEVENT_VERSION, event_get_version());
}
#ifdef USE_TLS
if (openssl_series_differs(OPENSSL_VERSION_NUMBER, openssl_runtime_version_number())) {
fprintf(stderr,
"warning: memtier_benchmark was built with %s headers but is running with %s; "
"rebuild it against the OpenSSL it runs with.\n",
OPENSSL_VERSION_TEXT, openssl_runtime_version_text());
}
#endif
}
#include <cfloat>
#include <cmath>
#include <cstring>
#include <set>
#include <stdexcept>
#include <atomic>
#include <algorithm>
#ifdef __APPLE__
#include <mach/mach.h>
#endif
#ifdef _WIN32
// Windows has no getrusage(). Emulate the one call this file makes,
// getrusage(RUSAGE_THREAD), with GetThreadTimes(). The values are scheduler
// accounted, so they advance in clock ticks (~15.6 ms), not continuously.
#define RUSAGE_THREAD 1
struct rusage
{
struct timeval ru_utime;
struct timeval ru_stime;
};
// FILETIME durations are in 100 ns units.
static unsigned long long filetime_to_usec(const FILETIME &ft)
{
return (((unsigned long long) ft.dwHighDateTime << 32) | ft.dwLowDateTime) / 10;
}
static int getrusage(int who, struct rusage *ru)
{
if (who != RUSAGE_THREAD) {
errno = EINVAL;
return -1;
}
FILETIME creation_time, exit_time, kernel_time, user_time;
if (!GetThreadTimes(GetCurrentThread(), &creation_time, &exit_time, &kernel_time, &user_time)) {
errno = EINVAL;
return -1;
}
unsigned long long user_usec = filetime_to_usec(user_time);
unsigned long long kernel_usec = filetime_to_usec(kernel_time);
ru->ru_utime.tv_sec = (long) (user_usec / 1000000);
ru->ru_utime.tv_usec = (long) (user_usec % 1000000);
ru->ru_stime.tv_sec = (long) (kernel_usec / 1000000);
ru->ru_stime.tv_usec = (long) (kernel_usec % 1000000);
return 0;
}
#endif
#include "client.h"
#include "cluster_client.h"
#include "JSON_handler.h"
#include "utf8.h"
#include "file_io.h"
#include "obj_gen.h"
#include "memtier_benchmark.h"
#include "connection_stage_clock.h"
#include "run_stats_types.h"
#include "latency_percentiles.h"
#include "retry_policy.h"
#include "statsd.h"
#include "crash_report.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);
}
// Cluster hash tag that every key generated for a monitor-line argument
// containing __key__ shares: prefix + --key-prefix + <number> + suffix, with
// only the first __key__ replaced. Same rule as Redis: the text between the
// first '{' and the first '}' after it, if not empty. Returns false when the
// tag would include the generated number, or there is none, so the slot
// varies from key to key.
static bool monitor_key_arg_fixed_tag(const std::string &arg, const char *key_prefix, std::string *tag)
{
size_t pos = arg.find(KEY_PLACEHOLDER);
std::string before = arg.substr(0, pos) + (key_prefix ? key_prefix : "");
std::string after = arg.substr(pos + strlen(KEY_PLACEHOLDER));
// A '{' before the number: its '}' must come before the number too.
// No '{' before it: the number has no braces, so look in the suffix.
const std::string &part = before.find('{') != std::string::npos ? before : after;
size_t open = part.find('{');
if (open == std::string::npos) return false;
size_t close = part.find('}', open + 1);
if (close == std::string::npos || close == open + 1) return false;
tag->assign(part, open + 1, close - open - 1);
return true;
}
// --cluster-mode supports only single-key commands (see the --command check
// in main()). A __monitor_line@__ line is resolved per request and routed by
// its first key, so a line with several __key__ arguments is accepted only
// when every generated key shares one {hash tag}, which keeps them in one
// slot. Otherwise Redis would answer CROSSSLOT for every such request.
static bool check_cluster_monitor_lines(const struct monitor_command_list *monitor_commands, const char *key_prefix)
{
for (size_t line = 0; line < monitor_commands->size(); line++) {
arbitrary_command cmd(monitor_commands->get_command(line).c_str());
if (!cmd.split_command_to_args()) continue; // skipped with a warning at run time
unsigned int keys = 0;
bool same_slot = true;
std::string first_tag;
for (size_t i = 1; i < cmd.command_args.size(); i++) {
const std::string &data = cmd.command_args[i].data;
if (data.find(KEY_PLACEHOLDER) == std::string::npos) continue;
std::string tag;
if (!monitor_key_arg_fixed_tag(data, key_prefix, &tag)) {
same_slot = false;
} else if (keys == 0) {
first_tag = tag;
} else if (tag != first_tag) {
same_slot = false;
}
keys++;
}
if (keys > 1 && !same_slot) {
benchmark_error_log("error: Cluster mode supports only single-key commands: monitor line %zu has %u "
"__key__ arguments that can hash to different slots (give them one {hash tag}, "
"e.g. {t}__key__): %s\n",
line + 1, keys, cmd.command.c_str());
return false;
}
}
return true;
}
// 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: 0, or the number of the signal
// (SIGINT / SIGTERM) that interrupted the run. Atomic, not a volatile
// sig_atomic_t: the kernel may run the handler on a worker thread while the
// main thread reads the flag.
static std::atomic<int> g_interrupted(0);
// Set when run_benchmark() aborts because --connection-stage-timeout
// elapsed without any thread reaching steady state. Reset at the start of
// every run (connection_stage_supervisor_reset()), so it describes the
// current run only.
static std::atomic<bool> g_connection_stage_aborted{false};
// Set by run_benchmark() (main thread) together with
// g_connection_stage_aborted, but never reset: with --run-count > 1, an abort
// in any run, not only the last one, makes memtier exit 2. Atomic because
// worker threads read it through failure_exit_code().
static std::atomic<bool> g_any_run_connection_stage_aborted{false};
// Set by run_benchmark() (main thread, after joining the workers) when any
// worker thread ended on connection failures it could not recover from (or an
// exception) instead of on the run's own stop condition (--test-time /
// --requests). Such a run did not measure what was asked for; main() then
// exits 1.
static bool g_worker_failed = false;
// Set (main thread only) when a requested output could not be opened or
// written: --out-file, --json-out-file, stdout, the --hdr-file-prefix files,
// the --client-stats CSVs or --failed-keys-file (e.g. a full disk). The
// error has been printed; main() then exits 1.
static bool g_output_failed = false;
// main owns the JSON writer. Workers never write JSON, and main writes results
// after joining them, so the exit callback sees a quiescent writer. Retain
// content already emitted, without assuming which output stage was reached.
static json_handler *g_json_out_file = NULL;
// main owns the object generator and the imported keylist. Option checks
// after they are created exit through usage() or exit(); file-scope roots
// keep them (and the buffers they own) reachable for LeakSanitizer then,
// whatever registers main used.
static object_generator *g_obj_gen = NULL;
static imported_keylist *g_keylist = NULL;
static void close_json_out_file_at_exit(void)
{
if (g_json_out_file != NULL) {
g_json_out_file->write_error("Benchmark terminated before normal finalization");
g_json_out_file->close();
}
}
// 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_usec 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};
// Wall-clock microseconds (see connection_stage_timed_out()).
static std::atomic<long long> g_conn_stage_streak_start_usec{0}; // 0 = no failure yet
static std::atomic<long long> g_conn_stage_run_start_usec{0};
static long long conn_stage_now_usec(void)
{
struct timeval now;
gettimeofday(&now, NULL);
return (long long) now.tv_sec * 1000000 + now.tv_usec;
}
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_usec.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 the worker-failure report in cg_thread_start(). The exit
// code uses g_any_run_connection_stage_aborted, which is not reset.
g_connection_stage_aborted.store(false, std::memory_order_release);
g_conn_stage_run_start_usec.store(conn_stage_now_usec(), 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;
// 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 long zero = 0;
g_conn_stage_streak_start_usec.compare_exchange_strong(zero, conn_stage_now_usec(), 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_usec.store(0, std::memory_order_release);
}
}
int failure_exit_code(void)
{
return g_any_run_connection_stage_aborted.load(std::memory_order_acquire) ? 2 : 1;
}
bool connection_stage_steady_state_reached(void)
{
return g_conn_stage_steady_state.load(std::memory_order_acquire);
}
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;
long long now = conn_stage_now_usec();
long long streak_start = g_conn_stage_streak_start_usec.load(std::memory_order_acquire);
long long run_start = g_conn_stage_run_start_usec.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).
unsigned int elapsed_streak = 0, elapsed_run = 0;
bool trip_streak = connection_stage_timed_out(streak_start, now, timeout_secs, &elapsed_streak);
bool trip_run = connection_stage_timed_out(run_start, now, timeout_secs, &elapsed_run);
if (!trip_streak && !trip_run) return false;
if (out_elapsed != NULL) {
*out_elapsed = 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.
#ifndef _WIN32
#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;
}
}
#else
static void install_alt_signal_stack(void) {}
#endif
// CLOCK_MONOTONIC time of the first SIGINT/SIGTERM, in ms modulo 2^32, and
// never 0: 0 means no signal yet. Differences are taken modulo 2^32 too, so
// the wrap every ~49.7 days does not matter.
static std::atomic<unsigned int> g_first_interrupt_ms(0);
// The handler uses only int-sized atomics; that is async-signal-safe only
// when they are lock-free.
static_assert(ATOMIC_INT_LOCK_FREE == 2, "sigint_handler needs lock-free int atomics");
// Signal handler for Ctrl+C (SIGINT) and SIGTERM. The first signal stops
// the run gracefully. A signal at least 1 s later terminates at once, as a
// way out of a stuck shutdown. Signals within that second are duplicates of
// the same action and are ignored: Ctrl+C under `timeout` delivers SIGINT
// twice (terminal and timeout), and a process-group kill does the same.
static void sigint_handler(int signum)
{
int saved_errno = errno;
struct timespec ts;
// clock_gettime() is async-signal-safe (POSIX.1-2008).
clock_gettime(CLOCK_MONOTONIC, &ts);
unsigned int now = (unsigned int) ts.tv_sec * 1000u + (unsigned int) (ts.tv_nsec / 1000000);
if (now == 0) now = 1;
unsigned int first = 0;
if (g_first_interrupt_ms.compare_exchange_strong(first, now)) {
g_interrupted = signum;
} else if (now - first >= 1000u) {
signal(signum, SIG_DFL);
raise(signum);
}
errno = saved_errno;
}
// Report tail shared by the POSIX signal handler and the Windows exception
// filter: system and version information, the client list and the closing
// banner.
static void print_crash_report_tail(const char *timestr)
{
// Print system information
fprintf(stderr, "\n[%d] %s # --- INFO OUTPUT\n", getpid(), timestr);
#ifdef _WIN32
// RtlGetVersion, unlike GetVersionEx, is not subject to manifest-based
// version lying.
typedef LONG(WINAPI * rtl_get_version_fn)(PRTL_OSVERSIONINFOW);
HMODULE ntdll = GetModuleHandleA("ntdll.dll");
rtl_get_version_fn rtl_get_version = ntdll ? (rtl_get_version_fn) GetProcAddress(ntdll, "RtlGetVersion") : NULL;
RTL_OSVERSIONINFOW os_version;
memset(&os_version, 0, sizeof(os_version));
os_version.dwOSVersionInfoSize = sizeof(os_version);
if (rtl_get_version != NULL && rtl_get_version(&os_version) == 0) {
fprintf(stderr, "[%d] %s # os:Windows %lu.%lu.%lu\n", getpid(), timestr, os_version.dwMajorVersion,
os_version.dwMinorVersion, os_version.dwBuildNumber);
}
#else
struct utsname name;
if (uname(&name) == 0) {
fprintf(stderr, "[%d] %s # os:%s %s %s\n", getpid(), timestr, name.sysname, name.release, name.machine);
}
#endif
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());
fprintf(stderr, "[%d] %s # libevent_build_version:%s\n", getpid(), timestr, LIBEVENT_VERSION);
#ifdef USE_TLS
fprintf(stderr, "[%d] %s # openssl_version:%s\n", getpid(), timestr, OPENSSL_VERSION_TEXT);
fprintf(stderr, "[%d] %s # openssl_runtime_version:%s\n", getpid(), timestr, openssl_runtime_version_text());
#endif
// Print client connection information
print_client_list(stderr, getpid(), timestr);
#ifdef _WIN32
fprintf(stderr, "[%d] %s # For more information, please check the crash dump if available.\n", getpid(), timestr);
fprintf(stderr, "[%d] %s # To enable crash dumps, configure Windows Error Reporting LocalDumps:\n", getpid(),
timestr);
fprintf(stderr, "[%d] %s # HKLM\\SOFTWARE\\Microsoft\\Windows\\Windows Error Reporting\\LocalDumps\n", getpid(),
timestr);
#else
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);
#endif
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");
}
static const char *interrupt_source(void)
{
return g_interrupted == SIGTERM ? "SIGTERM" : "user (Ctrl+C)";
}
// Offset of local time from UTC, in seconds, taken once at startup by
// crash-handler setup with crash_utc_offset(). The crash handlers cannot
// call localtime(); see crash_report.h (#681).
static long g_crash_utc_offset = 0;
#ifndef _WIN32
// Begin a report line: "[pid] timestr # ".
static void crash_line_prefix(crash_line &l, int pid, const char *timestr)
{
l.str("[");
l.num((long long) pid);
l.str("] ");
l.str(timestr);
l.str(" # ");
}
// ThreadSanitizer runs a handler for an asynchronous signal only when the
// receiving thread is in, or leaves, an intercepted call. A thread stuck on
// a futex or in a blocked write never does, so the watchdog handler would
// never run and the process would hang. TSan builds keep SIG_DFL for
// SIGALRM, which the kernel applies directly, and have no INCOMPLETE line.
#if defined(__SANITIZE_THREAD__)
#define MEMTIER_THREAD_SANITIZER 1
#elif defined(__has_feature)
#if __has_feature(thread_sanitizer)
#define MEMTIER_THREAD_SANITIZER 1
#endif
#endif
#ifndef MEMTIER_THREAD_SANITIZER
// SIGALRM handler armed by crash_handler(): say why the report stops, then
// end the process with the default SIGALRM action as before. The write can
// block too (stderr is a full pipe or a stopped tty), so first re-arm the
// alarm: SA_RESETHAND already restored SIG_DFL, and SA_NODEFER leaves
// SIGALRM unblocked, so the second alarm kills the process 1 s later.
static void crash_watchdog_handler(int sig)
{
alarm(1);
crash_line l;
l.str("\n=== MEMTIER_BENCHMARK BUG REPORT INCOMPLETE: crash handler timed out ===\n");
l.write_out();
// SA_RESETHAND already restored SIG_DFL, so this ends the process now.
raise(sig);
}
#endif
// Crash handler - prints stack trace and other debugging information
static void crash_handler(int sig, siginfo_t *info, void *secret)
{
(void) secret; // unused parameter
char timestr[64];
int pid = getpid();
// 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. The watchdog first
// writes a line saying the report is incomplete. A second crash with the
// same signal takes the default action (SA_RESETHAND). A crash by a
// different signal re-enters this handler and re-arms alarm(5), so death
// can take up to about 11 s in that case, which is still bounded.
#ifndef MEMTIER_THREAD_SANITIZER
struct sigaction alarm_act;
sigemptyset(&alarm_act.sa_mask);
alarm_act.sa_flags = SA_ONSTACK | SA_NODEFER | SA_RESETHAND;
alarm_act.sa_handler = crash_watchdog_handler;
// SIGALRM may land on any thread, not only this one. That is fine: the
// watchdog only calls alarm, write and raise, which are safe on any
// thread, and SA_RESETHAND resets the disposition for the whole process.
sigaction(SIGALRM, &alarm_act, NULL);
#endif
alarm(5);
// The header and signal details use only async-signal-safe calls
// (time, getpid, write), so they reach stderr even when the crash
// interrupted a thread holding the malloc, stdio or time zone lock.
crash_format_time(timestr, sizeof(timestr), (long long) time(NULL), g_crash_utc_offset);
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;
}
crash_line l;
l.str("\n\n=== MEMTIER_BENCHMARK BUG REPORT START: Cut & paste starting from here ===\n");
l.write_out();
crash_line_prefix(l, pid, timestr);
l.str("memtier_benchmark crashed by signal: ");
l.num((long long) sig);
l.str("\n");
l.write_out();
crash_line_prefix(l, pid, timestr);
l.str("Crashed running signal <");
l.str(signal_name);
l.str(">\n");
l.write_out();
if (info) {
crash_line_prefix(l, pid, timestr);
l.str("Signal code: ");
l.num((long long) info->si_code);
l.str("\n");
l.write_out();
crash_line_prefix(l, pid, timestr);
l.str("Fault address: ");
if (info->si_addr == NULL) {
l.str("(nil)");
} else {
l.str("0x");
l.num((unsigned long long) (uintptr_t) info->si_addr, 16, 1);
}
l.str("\n");
l.write_out();
}
// Everything below is best effort and is NOT async-signal-safe; it comes
// after the essential lines above so a hang here still leaves them, and
// the watchdog ends a hang after 5 s:
// - backtrace() can take the loader lock (dl_iterate_phdr) while
// unwinding; its first-use malloc/dlopen is done by prewarm.
// - fprintf(stderr) takes the stderr FILE lock. It is recursive, so it
// only blocks while another thread is inside a stderr call.
// - print_client_list() reads the worker's client and connection
// vectors without synchronization; a torn vector can fault or hang.
// uname(), getpid(), sigaction() and raise() are async-signal-safe, and
// event_get_version() and OpenSSL_version() only return constant strings.
// Print stack trace for all threads
print_all_threads_stack_trace(stderr, getpid(), timestr);
print_crash_report_tail(timestr);
// 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();
#ifdef USE_TLS
(void) openssl_runtime_version_text();
#endif
// The handler formats its timestamp by hand from this offset, and this
// first localtime_r() call also loads the time zone data.
g_crash_utc_offset = crash_utc_offset(time(NULL));
}
// 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 crash handler's watchdog. SIG_DFL (terminate) is the
// baseline; crash_handler() installs crash_watchdog_handler, which
// prints an INCOMPLETE marker and falls back to SIG_DFL, before it calls
// alarm(5). Explicitly request SIG_DFL here so an inherited disposition
// cannot turn the watchdog off.
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);
}
#else
// Best-effort crash report for unhandled SEH exceptions (access violation,
// illegal instruction, ...). abort() and assert() failures do not reach it.
static LONG WINAPI crash_exception_filter(EXCEPTION_POINTERS *info)
{
// One report per process: a fault inside this filter, or a second
// crashing thread, must not re-enter it.
static volatile LONG reporting = 0;
if (InterlockedExchange(&reporting, 1) != 0) return EXCEPTION_CONTINUE_SEARCH;
char timestr[64];
crash_format_time(timestr, sizeof(timestr), (long long) time(NULL), g_crash_utc_offset);
const EXCEPTION_RECORD *rec = info->ExceptionRecord;
fprintf(stderr, "\n\n=== MEMTIER_BENCHMARK BUG REPORT START: Cut & paste starting from here ===\n");
fprintf(stderr, "[%d] %s # memtier_benchmark crashed by unhandled exception\n", getpid(), timestr);
fprintf(stderr, "[%d] %s # Crashed running exception <0x%08lx>\n", getpid(), timestr, rec->ExceptionCode);
fprintf(stderr, "[%d] %s # Fault address: %p\n", getpid(), timestr, rec->ExceptionAddress);
if (rec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && rec->NumberParameters >= 2) {
fprintf(stderr, "[%d] %s # Access violation: %s address %p\n", getpid(), timestr,
rec->ExceptionInformation[0] == 0 ? "reading" : "writing", (void *) rec->ExceptionInformation[1]);
}
print_all_threads_stack_trace(stderr, getpid(), timestr);
print_crash_report_tail(timestr);
return EXCEPTION_CONTINUE_SEARCH;
}
static void setup_crash_handlers(void)
{
g_crash_utc_offset = crash_utc_offset(time(NULL));
SetUnhandledExceptionFilter(crash_exception_filter);
}
#endif
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 if (type == PROTOCOL_MEMCACHE_META)
return "memcache_meta";
else
return "none";
}
#ifdef HAVE_EVHTTP
// Comma-joined "key=value" run labels in insertion order (PLAN.md section 5).
// Unescaped: json_handler::write_obj escapes string values itself.
static std::string prometheus_run_labels_str(struct benchmark_config *cfg)
{
std::string s;
for (size_t i = 0; i < cfg->prometheus_run_labels.size(); i++) {
if (i > 0) s += ",";
s += cfg->prometheus_run_labels[i].first + "=" + cfg->prometheus_run_labels[i].second;
}
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
// Secrets must not reach --show-config or --json-out-file (result files are
// shared as CI artifacts). Keep the user name, which the redis and
// memcache_binary authenticate() split off at the first ':', and replace the
// password with "***": "user:pw" -> "user:***", "pw" -> "***".
static std::string redact_credentials(const char *credentials)
{
if (!credentials || !*credentials) return "";
const char *colon = strchr(credentials, ':');
if (!colon) return "***";
return std::string(credentials, colon - credentials + 1) + "***";
}
// End of the userinfo in a URI authority+path (the text after "scheme://"),
// or NULL when there is none. The authority ends at a '/', '?' or '#'
// (RFC 3986), so once credentials are present the search for '@' stops at
// the first of those after the first '@': a later '@' in the db path, query
// or fragment does not end the credentials, which would send them to another
// host. It is the LAST '@' before that point, so a raw '@' in the password
// works and no tail of it is taken for the host and echoed by --show-config
// or a host/port error.
// Ambiguous forms, kept as before for compatibility; parse_uri() warns about
// them (a raw '/', '?' or '#' in the userinfo) and %2F, %3F, %23 and %40
// spell them unambiguously (#732):
// - A raw '/', '?' or '#' in the password works only when no '@' comes
// before it in the password: "u:a@b/c@host" is split as host "b".