/
mako.cpp
2773 lines (2556 loc) · 89.9 KB
/
mako.cpp
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
/*
* mako.cpp
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2022 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <array>
#include <cassert>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <map>
#include <new>
#include <numeric>
#include <optional>
#if defined(__linux__)
#include <pthread.h>
#endif
#include <string>
#include <string_view>
#include <thread>
#include <fcntl.h>
#include <getopt.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <boost/asio.hpp>
#include <fmt/format.h>
#include <fmt/printf.h>
#include <fdb_api.hpp>
#include <unordered_map>
#include "fdbclient/zipf.h"
#include "admin_server.hpp"
#include "async.hpp"
#include "future.hpp"
#include "logger.hpp"
#include "mako.hpp"
#include "operations.hpp"
#include "process.hpp"
#include "utils.hpp"
#include "shm.hpp"
#include "stats.hpp"
#include "tenant.hpp"
#include "time.hpp"
#include "rapidjson/document.h"
#include "rapidjson/error/en.h"
namespace mako {
/* args for threads */
struct alignas(64) ThreadArgs {
int process_idx;
int thread_idx;
int active_tenants;
int total_tenants;
pid_t parent_id;
Arguments const* args;
shared_memory::Access shm;
fdb::Database database; // database to work with
};
} // namespace mako
using namespace fdb;
using namespace mako;
thread_local Logger logr = Logger(MainProcess{}, VERBOSE_DEFAULT);
std::pair<Transaction, std::optional<std::string> /*token*/>
createNewTransaction(Database db, Arguments const& args, int id, std::optional<std::vector<Tenant>>& tenants) {
// No tenants specified
if (args.active_tenants <= 0) {
return { db.createTransaction(), {} };
}
// Create Tenant Transaction
int tenant_id = (id == -1) ? urand(0, args.active_tenants - 1) : id;
Transaction tr;
std::string tenant_name;
// If provided tenants array, use it
if (tenants) {
tr = (*tenants)[tenant_id].createTransaction();
} else {
tenant_name = getTenantNameByIndex(tenant_id);
Tenant t = db.openTenant(toBytesRef(tenant_name));
tr = t.createTransaction();
}
if (args.enable_token_based_authorization) {
assert(!args.authorization_tokens.empty());
// lookup token based on tenant name and, if found, set authz token to transaction
if (tenant_name.empty())
tenant_name = getTenantNameByIndex(tenant_id);
auto token_map_iter = args.authorization_tokens.find(tenant_name);
if (token_map_iter != args.authorization_tokens.end()) {
tr.setOption(FDB_TR_OPTION_AUTHORIZATION_TOKEN, token_map_iter->second);
return { tr, { token_map_iter->second } };
} else {
logr.error("could not find token for tenant '{}'", tenant_name);
_exit(1);
}
} else {
return { tr, {} };
}
}
int cleanupTenants(ipc::AdminServer& server, Arguments const& args, int db_id) {
for (auto tenant_id = 0; tenant_id < args.total_tenants;) {
const auto tenant_id_end = tenant_id + std::min(args.tenant_batch_size, args.total_tenants - tenant_id);
auto res = server.send(ipc::BatchDeleteTenantRequest{ args.cluster_files[db_id], tenant_id, tenant_id_end });
if (res.error_message) {
logr.error("{}", *res.error_message);
return -1;
} else {
logr.debug("deleted tenant [{}:{})", tenant_id, tenant_id_end);
tenant_id = tenant_id_end;
}
}
return 0;
}
/* cleanup database (no tenant-awareness) */
int cleanupNormalKeyspace(Database db, Arguments const& args) {
assert(args.total_tenants == 0 && args.active_tenants == 0);
const auto prefix_len = args.prefixpadding ? args.key_length - args.row_digits : intSize(KEY_PREFIX);
auto genprefix = [&args](ByteString& s) {
const auto padding_len = args.key_length - intSize(KEY_PREFIX) - args.row_digits;
auto pos = 0;
if (args.prefixpadding) {
memset(s.data(), 'x', padding_len);
pos += padding_len;
}
const auto key_prefix_len = intSize(KEY_PREFIX);
memcpy(&s[pos], KEY_PREFIX.data(), key_prefix_len);
};
auto beginstr = ByteString(prefix_len + 1, '\0');
genprefix(beginstr);
auto endstr = ByteString(prefix_len + 1, '\xff');
genprefix(endstr);
auto watch = Stopwatch(StartAtCtor{});
Transaction tx = db.createTransaction();
while (true) {
tx.clearRange(beginstr, endstr);
auto future_commit = tx.commit();
const auto rc = waitAndHandleError(tx, future_commit, "COMMIT_CLEANUP");
if (rc == FutureRC::OK) {
break;
} else if (rc == FutureRC::RETRY) {
// tx already reset
continue;
} else {
return -1;
}
}
logr.info("Clear range: {:6.3f} sec", toDoubleSeconds(watch.stop().diff()));
return 0;
}
/* populate database */
int populate(Database db, const ThreadArgs& thread_args, int thread_tps, WorkflowStatistics& stats) {
Arguments const& args = *thread_args.args;
const auto process_idx = thread_args.process_idx;
const auto thread_idx = thread_args.thread_idx;
auto xacts = 0;
auto keystr = ByteString{};
auto valstr = ByteString{};
keystr.resize(args.key_length);
valstr.resize(args.value_length);
const auto num_commit_every = args.txnspec.ops[OP_INSERT][OP_COUNT];
const auto num_seconds_trace_every = args.txntrace;
auto watch_total = Stopwatch(StartAtCtor{});
auto watch_throttle = Stopwatch(watch_total.getStart());
auto watch_tx = Stopwatch(watch_total.getStart());
auto watch_trace = Stopwatch(watch_total.getStart());
// tenants are assumed to have been generated by populateTenants() at main process, pre-fork
std::optional<std::vector<Tenant>> tenants = args.prepareTenants(db);
int populate_iters = args.active_tenants > 0 ? args.active_tenants : 1;
// Each tenant should have the same range populated
for (auto t_id = 0; t_id < populate_iters; ++t_id) {
auto [tx, token] = createNewTransaction(db, args, t_id, tenants);
const auto key_begin = insertBegin(args.rows, process_idx, thread_idx, args.num_processes, args.num_threads);
const auto key_end = insertEnd(args.rows, process_idx, thread_idx, args.num_processes, args.num_threads);
auto key_checkpoint = key_begin; // in case of commit failure, restart from this key
double required_keys = (key_end - key_begin + 1) * args.load_factor;
for (auto i = key_begin; i <= key_end; i++) {
// Choose required_keys out of (key_end -i + 1) randomly, so the probability is required_keys / (key_end - i
// + 1). Generate a random number in range [0, 1), if the generated number is smaller or equal to
// required_keys / (key_end - i + 1), then choose this key.
double r = rand() / (1.0 + RAND_MAX);
if (r > required_keys / (key_end - i + 1)) {
continue;
}
--required_keys;
/* sequential keys */
genKey(keystr.data(), KEY_PREFIX, args, i);
/* random values */
randomString(valstr.data(), args.value_length);
while (thread_tps > 0 && xacts >= thread_tps /* throttle */) {
if (toIntegerSeconds(watch_throttle.stop().diff()) >= 1) {
xacts = 0;
watch_throttle.startFromStop();
} else {
usleep(1000);
}
}
if (num_seconds_trace_every) {
if (toIntegerSeconds(watch_trace.stop().diff()) >= num_seconds_trace_every) {
watch_trace.startFromStop();
logr.debug("txn tracing {}", toCharsRef(keystr));
auto err = Error{};
err = tx.setOptionNothrow(FDB_TR_OPTION_DEBUG_TRANSACTION_IDENTIFIER, keystr);
if (err) {
logr.error("setOption(TR_OPTION_DEBUG_TRANSACTION_IDENTIFIER): {}", err.what());
}
err = tx.setOptionNothrow(FDB_TR_OPTION_LOG_TRANSACTION, BytesRef());
if (err) {
logr.error("setOption(TR_OPTION_LOG_TRANSACTION): {}", err.what());
}
}
}
/* insert (SET) */
tx.set(keystr, valstr);
stats.incrOpCount(OP_INSERT);
/* commit every 100 inserts (default) or if this is the last key */
if ((i % num_commit_every == 0) || i == key_end) {
const auto do_sample = (stats.getOpCount(OP_TRANSACTION) % args.sampling) == 0;
auto watch_commit = Stopwatch(StartAtCtor{});
auto future_commit = tx.commit();
const auto rc = waitAndHandleError(tx, future_commit, "COMMIT_POPULATE_INSERT");
watch_commit.stop();
watch_tx.setStop(watch_commit.getStop());
auto tx_restarter = ExitGuard([&watch_tx]() { watch_tx.startFromStop(); });
if (rc == FutureRC::OK) {
key_checkpoint = i + 1; // restart on failures from next key
std::tie(tx, token) = createNewTransaction(db, args, t_id, tenants);
} else if (rc == FutureRC::ABORT) {
return -1;
} else {
i = key_checkpoint - 1; // restart from last committed
continue;
}
/* xact latency stats */
if (do_sample) {
const auto commit_latency = watch_commit.diff();
const auto tx_duration = watch_tx.diff();
stats.addLatency(OP_COMMIT, commit_latency);
stats.addLatency(OP_TRANSACTION, tx_duration);
}
stats.incrOpCount(OP_COMMIT);
stats.incrOpCount(OP_TRANSACTION);
xacts++; /* for throttling */
}
}
logr.debug("Populated {} rows [{}, {}]: {:6.3f} sec",
key_end - key_begin + 1,
key_begin,
key_end,
toDoubleSeconds(watch_total.stop().diff()));
}
return 0;
}
void updateErrorStatsRunMode(WorkflowStatistics& stats, fdb::Error err, int op) {
if (err) {
if (err.is(1020 /*not_committed*/)) {
stats.incrConflictCount();
} else if (err.is(1031 /*timeout*/)) {
stats.incrTimeoutCount(op);
} else {
stats.incrErrorCount(op);
}
}
}
/* run one iteration of configured transaction */
int runOneTransaction(Transaction& tx,
std::optional<std::string> const& token,
Arguments const& args,
WorkflowStatistics& stats,
ByteString& key1,
ByteString& key2,
ByteString& val) {
const auto do_sample = (stats.getOpCount(OP_TRANSACTION) % args.sampling) == 0;
auto watch_tx = Stopwatch(StartAtCtor{});
auto watch_op = Stopwatch{};
auto op_iter = getOpBegin(args);
auto needs_commit = false;
transaction_begin:
while (op_iter != OpEnd) {
const auto& [op, count, step] = op_iter;
const auto step_kind = opTable[op].stepKind(step);
if (step == 0 /* first step */)
prepareKeys(op, key1, key2, args);
auto watch_step = Stopwatch(StartAtCtor{});
if (step == 0)
watch_op = Stopwatch(watch_step.getStart());
auto f = opTable[op].stepFunction(step)(tx, args, key1, key2, val);
auto future_rc = FutureRC::OK;
if (f) {
if (step_kind != StepKind::ON_ERROR) {
future_rc = waitAndHandleError(tx, f, opTable[op].name(), args.isAnyTimeoutEnabled());
} else {
future_rc = waitAndHandleForOnError(tx, f, opTable[op].name(), args.isAnyTimeoutEnabled());
}
updateErrorStatsRunMode(stats, f.error(), op);
}
if (auto postStepFn = opTable[op].postStepFunction(step))
postStepFn(f, tx, args, key1, key2, val);
watch_step.stop();
if (future_rc != FutureRC::OK) {
if (future_rc == FutureRC::ABORT) {
return -1;
}
// retry from first op
op_iter = getOpBegin(args);
needs_commit = false;
continue;
}
// step successful
if (step_kind == StepKind::COMMIT) {
// reset transaction boundary
if (do_sample) {
const auto step_latency = watch_step.diff();
stats.addLatency(OP_COMMIT, step_latency);
}
tx.reset();
if (token)
tx.setOption(FDB_TR_OPTION_AUTHORIZATION_TOKEN, *token);
stats.incrOpCount(OP_COMMIT);
needs_commit = false;
}
// op completed successfully
if (step + 1 == opTable[op].steps() /* last step */) {
if (opTable[op].needsCommit())
needs_commit = true;
watch_op.setStop(watch_step.getStop());
if (do_sample) {
const auto op_latency = watch_op.diff();
stats.addLatency(op, op_latency);
}
stats.incrOpCount(op);
}
// move to next op
op_iter = getOpNext(args, op_iter);
}
// reached the end?
if (needs_commit || args.commit_get) {
auto watch_commit = Stopwatch(StartAtCtor{});
auto f = tx.commit();
const auto rc = waitAndHandleError(tx, f, "COMMIT_AT_TX_END", args.isAnyTimeoutEnabled());
updateErrorStatsRunMode(stats, f.error(), OP_COMMIT);
watch_commit.stop();
auto tx_resetter = ExitGuard([&tx, &token]() {
tx.reset();
if (token)
tx.setOption(FDB_TR_OPTION_AUTHORIZATION_TOKEN, *token);
});
if (rc == FutureRC::OK) {
if (do_sample) {
const auto commit_latency = watch_commit.diff();
stats.addLatency(OP_COMMIT, commit_latency);
}
stats.incrOpCount(OP_COMMIT);
} else {
if (rc == FutureRC::ABORT) {
return -1;
}
// restart from beginning
op_iter = getOpBegin(args);
goto transaction_begin;
}
}
// one transaction has completed successfully
if (do_sample) {
const auto tx_duration = watch_tx.stop().diff();
stats.addLatency(OP_TRANSACTION, tx_duration);
}
stats.incrOpCount(OP_TRANSACTION);
return 0;
}
int runWorkload(Database db,
Arguments const& args,
int const thread_tps,
std::atomic<double> const& throttle_factor,
int const thread_iters,
std::atomic<int> const& signal,
WorkflowStatistics& workflow_stats,
int const dotrace,
int const dotagging) {
auto traceid = std::string{};
auto tagstr = std::string{};
if (thread_tps < 0)
return 0;
if (dotrace)
traceid.reserve(32);
if (dotagging)
tagstr.reserve(16);
auto current_tps = static_cast<int>(thread_tps * throttle_factor.load());
auto time_prev = steady_clock::now();
auto time_last_trace = time_prev;
auto rc = 0;
auto xacts = 0;
auto total_xacts = int64_t{};
// reuse memory for keys to avoid realloc overhead
auto key1 = ByteString{};
key1.resize(args.key_length);
auto key2 = ByteString{};
key2.resize(args.key_length);
auto val = ByteString{};
val.resize(args.value_length);
std::optional<std::vector<fdb::Tenant>> tenants = args.prepareTenants(db);
/* main transaction loop */
while (1) {
if ((thread_tps > 0 /* iff throttling on */) && (xacts >= current_tps)) {
/* throttle on */
auto time_now = steady_clock::now();
while (toDoubleSeconds(time_now - time_prev) < 1.0) {
usleep(1000);
time_now = steady_clock::now();
}
/* more than 1 second passed*/
xacts = 0;
time_prev = time_now;
/* update throttle rate */
current_tps = static_cast<int>(thread_tps * throttle_factor.load());
}
if (current_tps > 0 || thread_tps == 0 /* throttling off */) {
auto [tx, token] = createNewTransaction(db, args, -1, tenants);
setTransactionTimeoutIfEnabled(args, tx);
/* enable transaction trace */
if (dotrace) {
const auto time_now = steady_clock::now();
if (toIntegerSeconds(time_now - time_last_trace) >= 1) {
time_last_trace = time_now;
traceid.clear();
fmt::format_to(std::back_inserter(traceid), "makotrace{:0>19d}", total_xacts);
logr.debug("txn tracing {}", traceid);
auto err = Error{};
err = tx.setOptionNothrow(FDB_TR_OPTION_DEBUG_TRANSACTION_IDENTIFIER, toBytesRef(traceid));
if (err) {
logr.error("TR_OPTION_DEBUG_TRANSACTION_IDENTIFIER: {}", err.what());
}
err = tx.setOptionNothrow(FDB_TR_OPTION_LOG_TRANSACTION, BytesRef());
if (err) {
logr.error("TR_OPTION_LOG_TRANSACTION: {}", err.what());
}
}
}
/* enable transaction tagging */
if (dotagging > 0) {
tagstr.clear();
fmt::format_to(std::back_inserter(tagstr),
"{}{}{:0>3d}",
KEY_PREFIX,
args.txntagging_prefix,
urand(0, args.txntagging - 1));
auto err = tx.setOptionNothrow(FDB_TR_OPTION_AUTO_THROTTLE_TAG, toBytesRef(tagstr));
if (err) {
logr.error("TR_OPTION_DEBUG_TRANSACTION_IDENTIFIER: {}", err.what());
}
}
rc = runOneTransaction(tx, token, args, workflow_stats, key1, key2, val);
if (rc) {
logr.warn("runOneTransaction failed ({})", rc);
}
xacts++;
total_xacts++;
}
if (thread_iters != -1) {
if (total_xacts >= thread_iters) {
/* xact limit reached */
break;
}
} else if (signal.load() == SIGNAL_RED) {
/* signal turned red, target duration reached */
break;
}
}
return rc;
}
std::string getStatsFilename(std::string_view dirname, int process_idx, int thread_id, int op) {
return fmt::format("{}/{}_{}_{}", dirname, process_idx + 1, thread_id + 1, opTable[op].name());
}
std::string getStatsFilename(std::string_view dirname, int process_idx, int thread_id) {
return fmt::format("{}/{}_{}", dirname, process_idx + 1, thread_id + 1);
}
void dumpThreadSamples(Arguments const& args,
pid_t parent_id,
int process_idx,
int thread_id,
const WorkflowStatistics& stats,
bool overwrite = true) {
const auto dirname = fmt::format("{}{}", TEMP_DATA_STORE, parent_id);
const auto rc = mkdir(dirname.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if (rc < 0 && errno != EEXIST) {
logr.error("mkdir {}: {}", dirname, strerror(errno));
return;
}
for (auto op = 0; op < MAX_OP; op++) {
if (args.txnspec.ops[op][OP_COUNT] > 0 || isAbstractOp(op)) {
stats.writeToFile(getStatsFilename(dirname, process_idx, thread_id, op), op);
}
}
}
void runAsyncWorkload(Arguments const& args,
pid_t pid_main,
int process_idx,
shared_memory::Access shm,
boost::asio::io_context& io_context,
std::vector<Database>& databases) {
auto dump_samples = [&args, pid_main, process_idx](auto&& states) {
auto overwrite = true; /* overwrite or append */
for (const auto& state : states) {
dumpThreadSamples(args, pid_main, process_idx, 0 /*thread_id*/, state->stats, overwrite);
overwrite = false;
}
};
auto stopcount = std::atomic<int>{};
if (args.mode == MODE_BUILD) {
auto states = std::vector<PopulateStateHandle>(args.async_xacts);
for (auto i = 0; i < args.async_xacts; i++) {
const auto key_begin = insertBegin(args.rows, process_idx, i, args.num_processes, args.async_xacts);
const auto key_end = insertEnd(args.rows, process_idx, i, args.num_processes, args.async_xacts);
auto db = databases[i % args.num_databases];
auto state =
std::make_shared<ResumableStateForPopulate>(Logger(WorkerProcess{}, args.verbose, process_idx, i),
db,
db.createTransaction(),
io_context,
args,
shm.workerStatsSlot(process_idx, i),
stopcount,
key_begin,
key_end);
state->watch_tx.start();
state->watch_total.start();
states[i] = state;
}
while (shm.headerConst().signal.load() != SIGNAL_GREEN)
usleep(1000);
// launch [async_xacts] concurrent transactions
for (auto state : states)
state->postNextTick();
while (stopcount.load() != args.async_xacts)
usleep(1000);
dump_samples(states);
} else if (args.mode == MODE_RUN) {
auto states = std::vector<RunWorkloadStateHandle>(args.async_xacts);
for (auto i = 0; i < args.async_xacts; i++) {
auto db = databases[i % args.num_databases];
const auto max_iters =
args.iteration == 0
? -1
: computeThreadIters(args.iteration, process_idx, i, args.num_processes, args.async_xacts);
// argument validation should ensure max_iters > 0
assert(args.iteration == 0 || max_iters > 0);
auto state =
std::make_shared<ResumableStateForRunWorkload>(Logger(WorkerProcess{}, args.verbose, process_idx, i),
db,
db.createTransaction(),
io_context,
args,
shm.workerStatsSlot(process_idx, i),
stopcount,
shm.headerConst().signal,
max_iters,
getOpBegin(args));
states[i] = state;
state->watch_tx.start();
}
while (shm.headerConst().signal.load() != SIGNAL_GREEN)
usleep(1000);
for (auto state : states)
state->postNextTick();
logr.debug("Launched {} concurrent transactions", states.size());
while (stopcount.load() != args.async_xacts)
usleep(1000);
logr.debug("All transactions completed");
dump_samples(states);
}
}
/* mako worker thread */
void workerThread(const ThreadArgs& thread_args) {
const auto& args = *thread_args.args;
const auto parent_id = thread_args.parent_id;
const auto process_idx = thread_args.process_idx;
const auto thread_idx = thread_args.thread_idx;
const auto dotrace = (process_idx == 0 && thread_idx == 0 && args.txntrace) ? args.txntrace : 0;
auto database = thread_args.database;
const auto dotagging = args.txntagging;
const auto& signal = thread_args.shm.headerConst().signal;
const auto& throttle_factor = thread_args.shm.headerConst().throttle_factor;
auto& readycount = thread_args.shm.header().readycount;
auto& stopcount = thread_args.shm.header().stopcount;
auto& workflow_stats = thread_args.shm.workerStatsSlot(process_idx, thread_idx);
auto& thread_stats = thread_args.shm.threadStatsSlot(process_idx, thread_idx);
logr = Logger(WorkerProcess{}, args.verbose, process_idx, thread_idx);
thread_stats.startThreadTimer();
logr.debug("started, tid: {}", reinterpret_cast<uint64_t>(pthread_self()));
const auto thread_tps =
args.tpsmax == 0 ? 0
: computeThreadTps(args.tpsmax, process_idx, thread_idx, args.num_processes, args.num_threads);
// argument validation should ensure thread_tps > 0
assert(args.tpsmax == 0 || thread_tps > 0);
const auto thread_iters =
args.iteration == 0
? -1
: computeThreadIters(args.iteration, process_idx, thread_idx, args.num_processes, args.num_threads);
// argument validation should ensure thread_iters > 0
assert(args.iteration == 0 || thread_iters > 0);
/* i'm ready */
readycount.fetch_add(1);
auto stopcount_guard = ExitGuard([&stopcount]() { stopcount.fetch_add(1); });
while (signal.load() == SIGNAL_OFF) {
usleep(10000); /* 10ms */
}
if (args.mode == MODE_CLEAN) {
auto rc = cleanupNormalKeyspace(database, args);
if (rc < 0) {
logr.error("cleanup failed");
}
} else if (args.mode == MODE_BUILD) {
auto rc = populate(database, thread_args, thread_tps, workflow_stats);
if (rc < 0) {
logr.error("populate failed");
}
} else if (args.mode == MODE_RUN) {
auto rc = runWorkload(
database, args, thread_tps, throttle_factor, thread_iters, signal, workflow_stats, dotrace, dotagging);
if (rc < 0) {
logr.error("runWorkload failed");
}
}
if (args.mode == MODE_BUILD || args.mode == MODE_RUN) {
dumpThreadSamples(args, parent_id, process_idx, thread_idx, workflow_stats);
}
thread_stats.endThreadTimer();
}
/* mako worker process */
int workerProcessMain(Arguments const& args, int process_idx, shared_memory::Access shm, pid_t pid_main) {
logr.debug("started");
auto err = Error{};
/* Everything starts from here */
if (args.setGlobalOptions() < 0) {
return -1;
}
/* Network thread must be setup before doing anything */
logr.debug("network::setup()");
network::setup();
shm.processStatsSlot(process_idx).startProcessTimer();
/* Each worker process will have its own network thread */
logr.debug("creating network thread");
auto network_thread = std::thread([parent_logr = logr, process_idx, shm]() {
shm.processStatsSlot(process_idx).startFDBNetworkTimer();
logr = parent_logr;
logr.debug("network thread started");
if (auto err = network::run()) {
logr.error("network::run(): {}", err.what());
}
shm.processStatsSlot(process_idx).endFDBNetworkTimer();
});
#if defined(__linux__)
pthread_setname_np(network_thread.native_handle(), "mako_network");
#endif
// prevent any exception from unwinding stack without joining the network thread
auto network_thread_guard = ExitGuard([&network_thread]() {
/* stop the network thread */
logr.debug("network::stop()");
auto err = network::stop();
if (err) {
logr.error("network::stop(): {}", err.what());
}
/* wait for the network thread to join */
logr.debug("waiting for network thread to join");
network_thread.join();
});
/*** let's party! ***/
auto databases = std::vector<fdb::Database>(args.num_databases);
/* set up database for worker threads */
for (auto i = 0; i < args.num_databases; i++) {
int cluster_index = i % args.num_fdb_clusters;
databases[i] = Database(args.cluster_files[cluster_index]);
logr.debug("creating database at cluster {}", args.cluster_files[cluster_index]);
if (args.disable_ryw) {
databases[i].setOption(FDB_DB_OPTION_SNAPSHOT_RYW_DISABLE, BytesRef{});
}
if (args.transaction_timeout_db > 0 && args.mode == MODE_RUN) {
databases[i].setOption(FDB_DB_OPTION_TRANSACTION_TIMEOUT, args.transaction_timeout_db);
}
}
if (!args.async_xacts) {
logr.debug("creating {} worker threads", args.num_threads);
auto worker_threads = std::vector<std::thread>(args.num_threads);
/* spawn worker threads */
auto thread_args = std::vector<ThreadArgs>(args.num_threads);
for (auto i = 0; i < args.num_threads; i++) {
auto& this_args = thread_args[i];
this_args.process_idx = process_idx;
this_args.thread_idx = i;
this_args.parent_id = pid_main;
this_args.active_tenants = args.active_tenants;
this_args.total_tenants = args.total_tenants;
this_args.args = &args;
this_args.shm = shm;
this_args.database = databases[i % args.num_databases];
worker_threads[i] = std::thread(workerThread, std::ref(this_args));
#if defined(__linux__)
const auto thread_name = "mako_worker_" + std::to_string(i);
pthread_setname_np(worker_threads[i].native_handle(), thread_name.c_str());
#endif
}
/* wait for everyone to finish */
for (auto i = 0; i < args.num_threads; i++) {
logr.debug("waiting for worker thread {} to join", i + 1);
worker_threads[i].join();
}
} else {
logr.debug("running async mode with {} concurrent transactions", args.async_xacts);
auto ctx = boost::asio::io_context{};
using WorkGuard = boost::asio::executor_work_guard<boost::asio::io_context::executor_type>;
auto wg = WorkGuard(ctx.get_executor());
auto worker_threads = std::vector<std::thread>(args.num_threads);
for (auto i = 0; i < args.num_threads; i++) {
worker_threads[i] = std::thread([&ctx, &args, process_idx, i, shm]() {
shm.threadStatsSlot(process_idx, i).startThreadTimer();
logr = Logger(WorkerProcess{}, args.verbose, process_idx);
logr.debug("Async-mode worker thread {} started", i + 1);
ctx.run();
logr.debug("Async-mode worker thread {} finished", i + 1);
shm.threadStatsSlot(process_idx, i).endThreadTimer();
});
#if defined(__linux__)
const auto thread_name = "mako_worker_" + std::to_string(i);
pthread_setname_np(worker_threads[i].native_handle(), thread_name.c_str());
#endif
}
shm.header().readycount.fetch_add(args.num_threads);
runAsyncWorkload(args, pid_main, process_idx, shm, ctx, databases);
wg.reset();
for (auto& thread : worker_threads)
thread.join();
shm.header().stopcount.fetch_add(args.num_threads);
}
shm.processStatsSlot(process_idx).endProcessTimer();
return 0;
}
/* initialize the parameters with default values */
Arguments::Arguments() {
num_fdb_clusters = 0;
num_databases = 1;
api_version = maxApiVersion();
json = 0;
num_processes = 1;
num_threads = 1;
async_xacts = 0;
mode = MODE_INVALID;
rows = 100000;
load_factor = 1.0;
row_digits = digits(rows);
seconds = 0;
iteration = 0;
tpsmax = 0;
tpsmin = -1;
tpsinterval = 10;
tpschange = TPS_SIN;
sampling = 1000;
key_length = 32;
value_length = 16;
active_tenants = 0;
total_tenants = 0;
tenant_batch_size = 10000;
zipf = 0;
commit_get = 0;
verbose = 1;
flatbuffers = 0; /* internal */
knobs[0] = '\0';
log_group[0] = '\0';
prefixpadding = 0;
trace = 0;
tracepath[0] = '\0';
traceformat = 0; /* default to client's default (XML) */
streaming_mode = FDB_STREAMING_MODE_WANT_ALL;
txntrace = 0;
txntagging = 0;
memset(cluster_files, 0, sizeof(cluster_files));
memset(txntagging_prefix, 0, TAGPREFIXLENGTH_MAX);
enable_token_based_authorization = false;
for (auto i = 0; i < MAX_OP; i++) {
txnspec.ops[i][OP_COUNT] = 0;
}
client_threads_per_version = 0;
disable_client_bypass = false;
disable_ryw = 0;
json_output_path[0] = '\0';
stats_export_path[0] = '\0';
bg_materialize_files = false;
bg_file_path[0] = '\0';
distributed_tracer_client = 0;
transaction_timeout_db = 0;
transaction_timeout_tx = 0;
num_report_files = 0;
}
int Arguments::setGlobalOptions() const {
selectApiVersion(api_version);
auto err = Error{};
/* enable distributed tracing */
switch (distributed_tracer_client) {
case DistributedTracerClient::NETWORK_LOSSY:
err = network::setOptionNothrow(FDB_NET_OPTION_DISTRIBUTED_CLIENT_TRACER, BytesRef(toBytePtr("network_lossy")));
break;
case DistributedTracerClient::LOG_FILE:
err = network::setOptionNothrow(FDB_NET_OPTION_DISTRIBUTED_CLIENT_TRACER, BytesRef(toBytePtr("log_file")));
break;
}
if (err) {
logr.error("network::setOption(FDB_NET_OPTION_DISTRIBUTED_CLIENT_TRACER): {}", err.what());
}
if (tls_certificate_file.has_value() && (logr.isFor(ProcKind::ADMIN) || !isAuthorizationEnabled())) {
logr.debug("TLS certificate file: {}", tls_certificate_file.value());
network::setOption(FDB_NET_OPTION_TLS_CERT_PATH, tls_certificate_file.value());
}
if (tls_key_file.has_value() && (logr.isFor(ProcKind::ADMIN) || !isAuthorizationEnabled())) {
logr.debug("TLS key file: {}", tls_key_file.value());
network::setOption(FDB_NET_OPTION_TLS_KEY_PATH, tls_key_file.value());
}
if (tls_ca_file.has_value()) {
logr.debug("TLS CA file: {}", tls_ca_file.value());
network::setOption(FDB_NET_OPTION_TLS_CA_PATH, tls_ca_file.value());
}
/* enable flatbuffers if specified */
if (flatbuffers) {
#ifdef FDB_NET_OPTION_USE_FLATBUFFERS
logr.debug("Using flatbuffers");
err = network::setOptionNothrow(FDB_NET_OPTION_USE_FLATBUFFERS, BytesRef(&flatbuffers, sizeof(flatbuffers)));
if (err) {
logr.error("network::setOption(USE_FLATBUFFERS): {}", err.what());
}
#else
logr.info("flatbuffers is not supported in FDB API version {}", FDB_API_VERSION);
#endif
}
/* Set client logr group */
if (log_group[0] != '\0') {
err = network::setOptionNothrow(FDB_NET_OPTION_TRACE_LOG_GROUP, BytesRef(toBytePtr(log_group)));
if (err) {
logr.error("network::setOption(FDB_NET_OPTION_TRACE_LOG_GROUP): {}", err.what());
}
}
/* enable tracing if specified */
if (trace) {
logr.debug("Enable Tracing in {} ({})",
(traceformat == 0) ? "XML" : "JSON",
(tracepath[0] == '\0') ? "current directory" : tracepath);
err = network::setOptionNothrow(FDB_NET_OPTION_TRACE_ENABLE, BytesRef(toBytePtr(tracepath)));
if (err) {
logr.error("network::setOption(TRACE_ENABLE): {}", err.what());
}
if (traceformat == 1) {
err = network::setOptionNothrow(FDB_NET_OPTION_TRACE_FORMAT, BytesRef(toBytePtr("json")));
if (err) {
logr.error("network::setOption(FDB_NET_OPTION_TRACE_FORMAT): {}", err.what());
}
}
}
/* enable knobs if specified */
if (knobs[0] != '\0') {
auto k = std::string_view(knobs);
const auto delim = std::string_view(", ");
while (true) {
k.remove_prefix(std::min(k.find_first_not_of(delim), k.size()));
auto knob = k.substr(0, k.find_first_of(delim));
if (knob.empty())
break;
logr.debug("Setting client knob: {}", knob);
err = network::setOptionNothrow(FDB_NET_OPTION_KNOB, toBytesRef(knob));
if (err) {
logr.error("network::setOption({}): {}", knob, err.what());
}
k.remove_prefix(knob.size());
}
}
if (client_threads_per_version > 0) {
err = network::setOptionNothrow(FDB_NET_OPTION_CLIENT_THREADS_PER_VERSION, client_threads_per_version);
if (err) {
logr.error("network::setOption (FDB_NET_OPTION_CLIENT_THREADS_PER_VERSION) ({}): {}",
client_threads_per_version,
err.what());
// let's exit here since we do not want to confuse users
// that mako is running with multi-threaded client enabled
return -1;
}
}
if (disable_client_bypass) {
err = network::setOptionNothrow(FDB_NET_OPTION_DISABLE_CLIENT_BYPASS);
if (err) {
logr.error(
"network::setOption (FDB_NET_OPTION_DISABLE_CLIENT_BYPASS): {}", disable_client_bypass, err.what());
return -1;
}
}
return 0;
}
bool Arguments::isAnyTimeoutEnabled() const {