-
Notifications
You must be signed in to change notification settings - Fork 0
/
mtd.cc
1721 lines (1551 loc) · 53 KB
/
mtd.cc
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
/* Masstree
* Eddie Kohler, Yandong Mao, Robert Morris
* Copyright (c) 2012-2014 President and Fellows of Harvard College
* Copyright (c) 2012-2014 Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, subject to the conditions
* listed in the Masstree LICENSE file. These conditions include: you must
* preserve this copyright notice, and you cannot mention the copyright
* holders in advertising related to the Software without their permission.
* The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
* notice is a summary of the Masstree LICENSE file; the license in that file
* is legally binding.
*/
// -*- mode: c++ -*-
// mtd: key/value server
//
#include <stdio.h>
#include <stdarg.h>
#include <ctype.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/select.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <limits.h>
#if HAVE_SYS_EPOLL_H
#include <sys/epoll.h>
#endif
#if __linux__
#include <asm-generic/mman.h>
#endif
#include <fcntl.h>
#include <assert.h>
#include <string.h>
#include <pthread.h>
#include <math.h>
#include <signal.h>
#include <errno.h>
#ifdef __linux__
#include <malloc.h>
#endif
#include "nodeversion.hh"
#include "kvstats.hh"
#include "json.hh"
#include "kvtest.hh"
#include "kvrandom.hh"
#include "clp.h"
#include "log.hh"
#include "checkpoint.hh"
#include "file.hh"
#include "kvproto.hh"
#include "query_masstree.hh"
#include "masstree_tcursor.hh"
#include "masstree_insert.hh"
#include "masstree_remove.hh"
#include "masstree_scan.hh"
#include "msgpack.hh"
#include <algorithm>
#include <deque>
#include "incll_configs.hh"
#include "incll_globals.hh"
using lcdf::StringAccum;
enum { CKState_Quit, CKState_Uninit, CKState_Ready, CKState_Go };
volatile bool timeout[2] = {false, false};
double duration[2] = {10, 0};
Masstree::default_table *tree;
// all default to the number of cores
static int udpthreads = 0;
static int tcpthreads = 0;
static int nckthreads = 0;
static int testthreads = 0;
static int nlogger = 0;
static std::vector<int> cores;
static bool logging = true;
static bool pinthreads = false;
static bool recovery_only = false;
volatile uint64_t globalepoch = 1; // global epoch, updated by main thread regularly
volatile mrcu_epoch_type failedepoch = 0;
int delaycount = 0;
volatile uint64_t active_epoch = 1;
static int port = 2117;
static uint64_t test_limit = ~uint64_t(0);
static int doprint = 0;
int kvtest_first_seed = 31949;
static volatile sig_atomic_t go_quit = 0;
static int quit_pipe[2];
static std::vector<const char*> logdirs;
static std::vector<const char*> ckpdirs;
static logset* logs;
volatile bool recovering = false; // so don't add log entries, and free old value immediately
static double checkpoint_interval = 1000000;
static kvepoch_t ckp_gen = 0; // recover from checkpoint
static ckstate *cks = NULL; // checkpoint status of all checkpointing threads
static pthread_cond_t rec_cond;
pthread_mutex_t rec_mu;
static int rec_nactive;
static int rec_state = REC_NONE;
kvtimestamp_t initial_timestamp;
static pthread_cond_t checkpoint_cond;
static pthread_mutex_t checkpoint_mu;
static void prepare_thread(threadinfo *ti);
static int* tcp_thread_pipes;
static void* tcp_threadfunc(void* ti);
static void* udp_threadfunc(void* ti);
static void log_init();
static void recover(threadinfo*);
static kvepoch_t read_checkpoint(threadinfo*, const char *path);
static void* conc_checkpointer(void* ti);
static void recovercheckpoint(threadinfo* ti);
static void *canceling(void *);
static void catchint(int);
static void epochinc(int);
/* running local tests */
void test_timeout(int) {
size_t n;
for (n = 0; n < arraysize(timeout) && timeout[n]; ++n)
/* do nothing */;
if (n < arraysize(timeout)) {
timeout[n] = true;
if (n + 1 < arraysize(timeout) && duration[n + 1])
xalarm(duration[n + 1]);
}
}
struct kvtest_client {
kvtest_client()
: checks_(0), kvo_() {
}
kvtest_client(const char *testname)
: testname_(testname), checks_(0), kvo_() {
}
int id() const {
return ti_->index();
}
int nthreads() const {
return testthreads;
}
void set_thread(threadinfo *ti) {
ti_ = ti;
}
void register_timeouts(int n) {
always_assert(n <= (int) arraysize(::timeout));
for (int i = 1; i < n; ++i)
if (duration[i] == 0)
duration[i] = 0;//duration[i - 1];
}
bool timeout(int which) const {
return ::timeout[which];
}
uint64_t limit() const {
return test_limit;
}
Json param(const String&) const {
return Json();
}
double now() const {
return ::now();
}
void get(long ikey, Str *value);
void get(const Str &key);
void get(long ikey) {
quick_istr key(ikey);
get(key.string());
}
void get_check(const Str &key, const Str &expected);
void get_check(const char *key, const char *expected) {
get_check(Str(key, strlen(key)), Str(expected, strlen(expected)));
}
void get_check(long ikey, long iexpected) {
quick_istr key(ikey), expected(iexpected);
get_check(key.string(), expected.string());
}
void get_check_key8(long ikey, long iexpected) {
quick_istr key(ikey, 8), expected(iexpected);
get_check(key.string(), expected.string());
}
void get_check_key10(long ikey, long iexpected) {
quick_istr key(ikey, 10), expected(iexpected);
get_check(key.string(), expected.string());
}
void get_col_check(const Str &key, int col, const Str &expected);
void get_col_check_key10(long ikey, int col, long iexpected) {
quick_istr key(ikey, 10), expected(iexpected);
get_col_check(key.string(), col, expected.string());
}
bool get_sync(long ikey);
void put(const Str &key, const Str &value);
void put(const char *key, const char *val) {
put(Str(key, strlen(key)), Str(val, strlen(val)));
}
void put(long ikey, long ivalue) {
quick_istr key(ikey), value(ivalue);
put(key.string(), value.string());
}
void put_key8(long ikey, long ivalue) {
quick_istr key(ikey, 8), value(ivalue);
put(key.string(), value.string());
}
void put_key10(long ikey, long ivalue) {
quick_istr key(ikey, 10), value(ivalue);
put(key.string(), value.string());
}
void put_col(const Str &key, int col, const Str &value);
void put_col_key10(long ikey, int col, long ivalue) {
quick_istr key(ikey, 10), value(ivalue);
put_col(key.string(), col, value.string());
}
bool remove_sync(long ikey);
void puts_done() {
}
void wait_all() {
}
void rcu_quiesce() {
}
String make_message(StringAccum &sa) const;
void notice(const char *fmt, ...);
void fail(const char *fmt, ...);
const Json& report(const Json& x) {
return report_.merge(x);
}
void finish() {
fprintf(stderr, "%d: %s\n", ti_->index(), report_.unparse().c_str());
}
threadinfo *ti_;
query<row_type> q_[10];
const char *testname_;
kvrandom_lcg_nr rand;
int checks_;
Json report_;
struct kvout *kvo_;
static volatile int failing;
};
volatile int kvtest_client::failing;
void kvtest_client::get(long ikey, Str *value)
{
quick_istr key(ikey);
if (!q_[0].run_get1(tree->table(), key.string(), 0, *value, *ti_))
*value = Str();
}
void kvtest_client::get(const Str &key)
{
Str val;
(void) q_[0].run_get1(tree->table(), key, 0, val, *ti_);
}
void kvtest_client::get_check(const Str &key, const Str &expected)
{
Str val;
if (!q_[0].run_get1(tree->table(), key, 0, val, *ti_)) {
fail("get(%.*s) failed (expected %.*s)\n", key.len, key.s, expected.len, expected.s);
return;
}
if (val.len != expected.len || memcmp(val.s, expected.s, val.len) != 0)
fail("get(%.*s) returned unexpected value %.*s (expected %.*s)\n", key.len, key.s,
std::min(val.len, 40), val.s, std::min(expected.len, 40), expected.s);
else
++checks_;
}
void kvtest_client::get_col_check(const Str &key, int col, const Str &expected)
{
Str val;
if (!q_[0].run_get1(tree->table(), key, col, val, *ti_)) {
fail("get.%d(%.*s) failed (expected %.*s)\n", col, key.len, key.s,
expected.len, expected.s);
return;
}
if (val.len != expected.len || memcmp(val.s, expected.s, val.len) != 0)
fail("get.%d(%.*s) returned unexpected value %.*s (expected %.*s)\n",
col, key.len, key.s, std::min(val.len, 40), val.s,
std::min(expected.len, 40), expected.s);
else
++checks_;
}
bool kvtest_client::get_sync(long ikey) {
quick_istr key(ikey);
Str val;
return q_[0].run_get1(tree->table(), key.string(), 0, val, *ti_);
}
void kvtest_client::put(const Str &key, const Str &value) {
while (failing)
/* do nothing */;
q_[0].run_replace(tree->table(), key, value, *ti_);
if (ti_->logger()) // NB may block
ti_->logger()->record(logcmd_replace, q_[0].query_times(), key, value);
}
void kvtest_client::put_col(const Str &key, int col, const Str &value) {
while (failing)
/* do nothing */;
#if !MASSTREE_ROW_TYPE_STR
if (!kvo_)
kvo_ = new_kvout(-1, 2048);
Json req[2] = {Json(col), Json(String::make_stable(value))};
(void) q_[0].run_put(tree->table(), key, &req[0], &req[2], *ti_);
if (ti_->logger()) // NB may block
ti_->logger()->record(logcmd_put, q_[0].query_times(), key,
&req[0], &req[2]);
#else
(void) key, (void) col, (void) value;
assert(0);
#endif
}
bool kvtest_client::remove_sync(long ikey) {
quick_istr key(ikey);
bool removed = q_[0].run_remove(tree->table(), key.string(), *ti_);
if (removed && ti_->logger()) // NB may block
ti_->logger()->record(logcmd_remove, q_[0].query_times(), key.string(), Str());
return removed;
}
String kvtest_client::make_message(StringAccum &sa) const {
const char *begin = sa.begin();
while (begin != sa.end() && isspace((unsigned char) *begin))
++begin;
String s = String(begin, sa.end());
if (!s.empty() && s.back() != '\n')
s += '\n';
return s;
}
void kvtest_client::notice(const char *fmt, ...) {
va_list val;
va_start(val, fmt);
String m = make_message(StringAccum().vsnprintf(500, fmt, val));
va_end(val);
if (m)
fprintf(stderr, "%d: %s", ti_->index(), m.c_str());
}
void kvtest_client::fail(const char *fmt, ...) {
static nodeversion32 failing_lock(false);
static nodeversion32 fail_message_lock(false);
static String fail_message;
failing = 1;
va_list val;
va_start(val, fmt);
String m = make_message(StringAccum().vsnprintf(500, fmt, val));
va_end(val);
if (!m)
m = "unknown failure";
fail_message_lock.lock();
if (fail_message != m) {
fail_message = m;
fprintf(stderr, "%d: %s", ti_->index(), m.c_str());
}
fail_message_lock.unlock();
if (doprint) {
failing_lock.lock();
fprintf(stdout, "%d: %s", ti_->index(), m.c_str());
tree->print(stdout);
fflush(stdout);
}
always_assert(0);
}
static void* testgo(void* x) {
kvtest_client *kc = reinterpret_cast<kvtest_client*>(x);
kc->ti_->pthread() = pthread_self();
prepare_thread(kc->ti_);
if (strcmp(kc->testname_, "rw1") == 0)
kvtest_rw1(*kc);
else if (strcmp(kc->testname_, "rw2") == 0)
kvtest_rw2(*kc);
else if (strcmp(kc->testname_, "rw3") == 0)
kvtest_rw3(*kc);
else if (strcmp(kc->testname_, "rw4") == 0)
kvtest_rw4(*kc);
else if (strcmp(kc->testname_, "rwsmall24") == 0)
kvtest_rwsmall24(*kc);
else if (strcmp(kc->testname_, "rwsep24") == 0)
kvtest_rwsep24(*kc);
else if (strcmp(kc->testname_, "palma") == 0)
kvtest_palma(*kc);
else if (strcmp(kc->testname_, "palmb") == 0)
kvtest_palmb(*kc);
else if (strcmp(kc->testname_, "rw16") == 0)
kvtest_rw16(*kc);
else if (strcmp(kc->testname_, "rw5") == 0
|| strcmp(kc->testname_, "rw1fixed") == 0)
kvtest_rw1fixed(*kc);
else if (strcmp(kc->testname_, "ycsbk") == 0)
kvtest_ycsbk(*kc);
else if (strcmp(kc->testname_, "wd1") == 0)
kvtest_wd1(10000000, 1, *kc);
else if (strcmp(kc->testname_, "wd1check") == 0)
kvtest_wd1_check(10000000, 1, *kc);
else if (strcmp(kc->testname_, "w1") == 0)
kvtest_w1_seed(*kc, kvtest_first_seed + kc->id());
else if (strcmp(kc->testname_, "r1") == 0)
kvtest_r1_seed(*kc, kvtest_first_seed + kc->id());
else if (strcmp(kc->testname_, "wcol1") == 0)
kvtest_wcol1at(*kc, kc->id() % 24, kvtest_first_seed + kc->id() % 48, 5000000);
else if (strcmp(kc->testname_, "rcol1") == 0)
kvtest_rcol1at(*kc, kc->id() % 24, kvtest_first_seed + kc->id() % 48, 5000000);
else
kc->fail("unknown test '%s'", kc->testname_);
return 0;
}
static const char * const kvstats_name[] = {
"ops", "ops_per_sec", "puts", "gets", "scans", "puts_per_sec", "gets_per_sec", "scans_per_sec"
};
void runtest(const char *testname, int nthreads) {
std::vector<kvtest_client> clients(nthreads, kvtest_client(testname));
::testthreads = nthreads;
for (int i = 0; i < nthreads; ++i)
clients[i].set_thread(threadinfo::make(threadinfo::TI_PROCESS, i));
bzero((void *)timeout, sizeof(timeout));
signal(SIGALRM, test_timeout);
if (duration[0])
xalarm(duration[0]);
for (int i = 0; i < nthreads; ++i) {
int r = pthread_create(&clients[i].ti_->pthread(), 0, testgo, &clients[i]);
always_assert(r == 0);
}
for (int i = 0; i < nthreads; ++i)
pthread_join(clients[i].ti_->pthread(), 0);
kvstats kvs[arraysize(kvstats_name)];
for (int i = 0; i < nthreads; ++i)
for (int j = 0; j < (int) arraysize(kvstats_name); ++j)
if (double x = clients[i].report_.get_d(kvstats_name[j]))
kvs[j].add(x);
for (int j = 0; j < (int) arraysize(kvstats_name); ++j)
kvs[j].print_report(kvstats_name[j]);
}
struct conn {
int fd;
enum { inbufsz = 20 * 1024, inbufrefill = 16 * 1024 };
conn(int s)
: fd(s), inbuf_(new char[inbufsz]),
inbufpos_(0), inbuflen_(0), kvout(new_kvout(s, 20 * 1024)),
inbuftotal_(0) {
}
~conn() {
close(fd);
free_kvout(kvout);
delete[] inbuf_;
for (char* x : oldinbuf_)
delete[] x;
}
Json& receive() {
while (!parser_.done() && check(2))
inbufpos_ += parser_.consume(inbuf_ + inbufpos_,
inbuflen_ - inbufpos_,
String::make_stable(inbuf_, inbufsz));
if (parser_.success() && parser_.result().is_a())
parser_.reset();
else
parser_.result() = Json();
return parser_.result();
}
int check(int tryhard) {
if (inbufpos_ == inbuflen_ && tryhard)
hard_check(tryhard);
return inbuflen_ - inbufpos_;
}
uint64_t xposition() const {
return inbuftotal_ + inbufpos_;
}
Str recent_string(uint64_t xposition) const {
if (xposition - inbuftotal_ <= unsigned(inbufpos_))
return Str(inbuf_ + (xposition - inbuftotal_),
inbuf_ + inbufpos_);
else
return Str();
}
private:
char* inbuf_;
int inbufpos_;
int inbuflen_;
std::vector<char*> oldinbuf_;
msgpack::streaming_parser parser_;
public:
struct kvout *kvout;
private:
uint64_t inbuftotal_;
void hard_check(int tryhard);
};
void conn::hard_check(int tryhard) {
masstree_precondition(inbufpos_ == inbuflen_);
if (parser_.empty()) {
inbuftotal_ += inbufpos_;
inbufpos_ = inbuflen_ = 0;
for (auto x : oldinbuf_)
delete[] x;
oldinbuf_.clear();
} else if (inbufpos_ == inbufsz) {
oldinbuf_.push_back(inbuf_);
inbuf_ = new char[inbufsz];
inbuftotal_ += inbufpos_;
inbufpos_ = inbuflen_ = 0;
}
if (tryhard == 1) {
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
struct timeval tv = {0, 0};
if (select(fd + 1, &rfds, NULL, NULL, &tv) <= 0)
return;
} else
kvflush(kvout);
ssize_t r = read(fd, inbuf_ + inbufpos_, inbufsz - inbufpos_);
if (r != -1)
inbuflen_ += r;
}
struct conninfo {
int s;
Json handshake;
};
/* main loop */
enum { clp_val_suffixdouble = Clp_ValFirstUser };
enum { opt_nolog = 1, opt_pin, opt_logdir, opt_port, opt_ckpdir, opt_duration,
opt_test, opt_test_name, opt_threads, opt_cores,
opt_print, opt_norun, opt_checkpoint, opt_limit, opt_epoch_interval };
static const Clp_Option options[] = {
{ "no-log", 0, opt_nolog, 0, 0 },
{ 0, 'n', opt_nolog, 0, 0 },
{ "no-run", 0, opt_norun, 0, 0 },
{ "pin", 'p', opt_pin, 0, Clp_Negate },
{ "logdir", 0, opt_logdir, Clp_ValString, 0 },
{ "ld", 0, opt_logdir, Clp_ValString, 0 },
{ "checkpoint", 'c', opt_checkpoint, Clp_ValDouble, Clp_Optional | Clp_Negate },
{ "ckp", 0, opt_checkpoint, Clp_ValDouble, Clp_Optional | Clp_Negate },
{ "ckpdir", 0, opt_ckpdir, Clp_ValString, 0 },
{ "ckdir", 0, opt_ckpdir, Clp_ValString, 0 },
{ "cd", 0, opt_ckpdir, Clp_ValString, 0 },
{ "port", 0, opt_port, Clp_ValInt, 0 },
{ "duration", 'd', opt_duration, Clp_ValDouble, 0 },
{ "limit", 'l', opt_limit, clp_val_suffixdouble, 0 },
{ "test", 0, opt_test, Clp_ValString, 0 },
{ "test-rw1", 0, opt_test_name, 0, 0 },
{ "test-rw2", 0, opt_test_name, 0, 0 },
{ "test-rw3", 0, opt_test_name, 0, 0 },
{ "test-rw4", 0, opt_test_name, 0, 0 },
{ "test-rw5", 0, opt_test_name, 0, 0 },
{ "test-rw16", 0, opt_test_name, 0, 0 },
{ "test-palm", 0, opt_test_name, 0, 0 },
{ "test-ycsbk", 0, opt_test_name, 0, 0 },
{ "test-rw1fixed", 0, opt_test_name, 0, 0 },
{ "threads", 'j', opt_threads, Clp_ValInt, 0 },
{ "cores", 0, opt_cores, Clp_ValString, 0 },
{ "print", 0, opt_print, 0, Clp_Negate },
{ "epoch-interval", 0, opt_epoch_interval, Clp_ValDouble, 0 }
};
int
main(int argc, char *argv[])
{
using std::swap;
int s, ret, yes = 1, i = 1, firstcore = -1, corestride = 1;
const char *dotest = 0;
nlogger = tcpthreads = udpthreads = nckthreads = sysconf(_SC_NPROCESSORS_ONLN);
Clp_Parser *clp = Clp_NewParser(argc, argv, (int) arraysize(options), options);
Clp_AddType(clp, clp_val_suffixdouble, Clp_DisallowOptions, clp_parse_suffixdouble, 0);
int opt;
double epoch_interval_ms = 1000;
while ((opt = Clp_Next(clp)) >= 0) {
switch (opt) {
case opt_nolog:
logging = false;
break;
case opt_pin:
pinthreads = !clp->negated;
break;
case opt_threads:
nlogger = tcpthreads = udpthreads = nckthreads = clp->val.i;
break;
case opt_logdir: {
const char *s = strtok((char *) clp->vstr, ",");
for (; s; s = strtok(NULL, ","))
logdirs.push_back(s);
break;
}
case opt_ckpdir: {
const char *s = strtok((char *) clp->vstr, ",");
for (; s; s = strtok(NULL, ","))
ckpdirs.push_back(s);
break;
}
case opt_checkpoint:
if (clp->negated || (clp->have_val && clp->val.d <= 0))
checkpoint_interval = -1;
else if (clp->have_val)
checkpoint_interval = clp->val.d;
else
checkpoint_interval = 30;
break;
case opt_port:
port = clp->val.i;
break;
case opt_duration:
duration[0] = clp->val.d;
break;
case opt_limit:
test_limit = (uint64_t) clp->val.d;
break;
case opt_test:
dotest = clp->vstr;
break;
case opt_test_name:
dotest = clp->option->long_name + 5;
break;
case opt_print:
doprint = !clp->negated;
break;
case opt_cores:
if (firstcore >= 0 || cores.size() > 0) {
Clp_OptionError(clp, "%<%O%> already given");
exit(EXIT_FAILURE);
} else {
const char *plus = strchr(clp->vstr, '+');
Json ij = Json::parse(clp->vstr),
aj = Json::parse(String("[") + String(clp->vstr) + String("]")),
pj1 = Json::parse(plus ? String(clp->vstr, plus) : "x"),
pj2 = Json::parse(plus ? String(plus + 1) : "x");
for (int i = 0; aj && i < aj.size(); ++i)
if (!aj[i].is_int() || aj[i].to_i() < 0)
aj = Json();
if (ij && ij.is_int() && ij.to_i() >= 0)
firstcore = ij.to_i(), corestride = 1;
else if (pj1 && pj2 && pj1.is_int() && pj1.to_i() >= 0 && pj2.is_int())
firstcore = pj1.to_i(), corestride = pj2.to_i();
else if (aj) {
for (int i = 0; i < aj.size(); ++i)
cores.push_back(aj[i].to_i());
} else {
Clp_OptionError(clp, "bad %<%O%>, expected %<CORE1%>, %<CORE1+STRIDE%>, or %<CORE1,CORE2,...%>");
exit(EXIT_FAILURE);
}
}
break;
case opt_norun:
recovery_only = true;
break;
case opt_epoch_interval:
epoch_interval_ms = clp->val.d;
break;
default:
fprintf(stderr, "Usage: mtd [-np] [--ld dir1[,dir2,...]] [--cd dir1[,dir2,...]]\n");
exit(EXIT_FAILURE);
}
}
Clp_DeleteParser(clp);
if (logdirs.empty())
logdirs.push_back(".");
if (ckpdirs.empty())
ckpdirs.push_back(".");
if (firstcore < 0)
firstcore = cores.size() ? cores.back() + 1 : 0;
for (; (int) cores.size() < udpthreads; firstcore += corestride)
cores.push_back(firstcore);
// for -pg profiling
signal(SIGINT, catchint);
// log epoch starts at 1
global_log_epoch = 1;
global_wake_epoch = 0;
log_epoch_interval.tv_sec = 0;
log_epoch_interval.tv_usec = 200000;
// set a timer for incrementing the global epoch
if (!dotest) {
if (!epoch_interval_ms) {
printf("WARNING: epoch interval is 0, it means no GC is executed\n");
} else {
signal(SIGALRM, epochinc);
struct itimerval etimer;
etimer.it_interval.tv_sec = epoch_interval_ms / 1000;
etimer.it_interval.tv_usec = fmod(epoch_interval_ms, 1000) * 1000;
etimer.it_value.tv_sec = epoch_interval_ms / 1000;
etimer.it_value.tv_usec = fmod(epoch_interval_ms, 1000) * 1000;
ret = setitimer(ITIMER_REAL, &etimer, NULL);
always_assert(ret == 0);
}
}
// for parallel recovery
ret = pthread_cond_init(&rec_cond, 0);
always_assert(ret == 0);
ret = pthread_mutex_init(&rec_mu, 0);
always_assert(ret == 0);
// for waking up the checkpoint thread
ret = pthread_cond_init(&checkpoint_cond, 0);
always_assert(ret == 0);
ret = pthread_mutex_init(&checkpoint_mu, 0);
always_assert(ret == 0);
threadinfo *main_ti = threadinfo::make(threadinfo::TI_MAIN, -1);
main_ti->pthread() = pthread_self();
initial_timestamp = timestamp();
tree = new Masstree::default_table;
tree->initialize(*main_ti);
printf("%s, %s, pin-threads %s, ", tree->name(), row_type::name(),
pinthreads ? "enabled" : "disabled");
if(logging){
printf("logging enabled\n");
log_init();
recover(main_ti);
} else {
printf("logging disabled\n");
}
// UDP threads, each with its own port.
if (udpthreads == 0)
printf("0 udp threads\n");
else if (udpthreads == 1)
printf("1 udp thread (port %d)\n", port);
else
printf("%d udp threads (ports %d-%d)\n", udpthreads, port, port + udpthreads - 1);
for(i = 0; i < udpthreads; i++){
threadinfo *ti = threadinfo::make(threadinfo::TI_PROCESS, i);
ret = pthread_create(&ti->pthread(), 0, udp_threadfunc, ti);
always_assert(ret == 0);
}
if (dotest) {
if (strcmp(dotest, "palm") == 0) {
runtest("palma", 1);
runtest("palmb", tcpthreads);
} else
runtest(dotest, tcpthreads);
tree->stats(stderr);
if (doprint)
tree->print(stdout);
exit(0);
}
// TCP socket and threads
s = socket(AF_INET, SOCK_STREAM, 0);
always_assert(s >= 0);
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes));
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(port);
ret = bind(s, (struct sockaddr *) &sin, sizeof(sin));
if (ret < 0) {
perror("bind");
exit(EXIT_FAILURE);
}
ret = listen(s, 100);
if (ret < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
threadinfo **tcpti = new threadinfo *[tcpthreads];
tcp_thread_pipes = new int[tcpthreads * 2];
printf("%d tcp threads (port %d)\n", tcpthreads, port);
for(i = 0; i < tcpthreads; i++){
threadinfo *ti = threadinfo::make(threadinfo::TI_PROCESS, i);
ret = pipe(&tcp_thread_pipes[i * 2]);
always_assert(ret == 0);
ret = pthread_create(&ti->pthread(), 0, tcp_threadfunc, ti);
always_assert(ret == 0);
tcpti[i] = ti;
}
// Create a canceling thread.
ret = pipe(quit_pipe);
always_assert(ret == 0);
pthread_t canceling_tid;
ret = pthread_create(&canceling_tid, NULL, canceling, NULL);
always_assert(ret == 0);
static int next = 0;
while(1){
int s1;
struct sockaddr_in sin1;
socklen_t sinlen = sizeof(sin1);
bzero(&sin1, sizeof(sin1));
s1 = accept(s, (struct sockaddr *) &sin1, &sinlen);
always_assert(s1 >= 0);
setsockopt(s1, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes));
// Complete handshake.
char buf[BUFSIZ];
ssize_t nr = read(s1, buf, BUFSIZ);
if (nr == -1) {
perror("read");
kill_connection:
close(s1);
continue;
}
msgpack::streaming_parser sp;
if (nr == 0 || sp.consume(buf, nr) != (size_t) nr
|| !sp.result().is_a() || sp.result().size() < 2
|| !sp.result()[1].is_i() || sp.result()[1].as_i() != Cmd_Handshake) {
fprintf(stderr, "failed handshake\n");
goto kill_connection;
}
int target_core = -1;
if (sp.result().size() >= 3 && sp.result()[2].is_o()
&& sp.result()[2]["core"].is_i())
target_core = sp.result()[2]["core"].as_i();
if (target_core < 0 || target_core >= tcpthreads) {
target_core = next % tcpthreads;
++next;
}
conninfo* ci = new conninfo;
ci->s = s1;
swap(ci->handshake, sp.result());
ssize_t w = write(tcp_thread_pipes[2*target_core + 1], &ci, sizeof(ci));
always_assert((size_t) w == sizeof(ci));
}
}
void
catchint(int)
{
go_quit = 1;
char cmd = 0;
// Does not matter if the write fails (when the pipe is full)
int r = write(quit_pipe[1], &cmd, sizeof(cmd));
(void)r;
}
inline const char *threadtype(int type) {
switch (type) {
case threadinfo::TI_MAIN:
return "main";
case threadinfo::TI_PROCESS:
return "process";
case threadinfo::TI_LOG:
return "log";
case threadinfo::TI_CHECKPOINT:
return "checkpoint";
default:
always_assert(0 && "Unknown threadtype");
break;
};
}
void *
canceling(void *)
{
char cmd;
int r = read(quit_pipe[0], &cmd, sizeof(cmd));
(void) r;
assert(r == sizeof(cmd) && cmd == 0);
// Cancel wake up checkpointing threads
pthread_mutex_lock(&checkpoint_mu);
pthread_cond_signal(&checkpoint_cond);
pthread_mutex_unlock(&checkpoint_mu);
fprintf(stderr, "\n");
// cancel outstanding threads. Checkpointing threads will exit safely
// when the checkpointing thread 0 sees go_quit, and don't need cancel
for (threadinfo *ti = threadinfo::allthreads; ti; ti = ti->next())
if (ti->purpose() != threadinfo::TI_MAIN
&& ti->purpose() != threadinfo::TI_CHECKPOINT) {
int r = pthread_cancel(ti->pthread());
always_assert(r == 0);
}
// join canceled threads
for (threadinfo *ti = threadinfo::allthreads; ti; ti = ti->next())
if (ti->purpose() != threadinfo::TI_MAIN) {
fprintf(stderr, "joining thread %s:%d\n",
threadtype(ti->purpose()), ti->index());
int r = pthread_join(ti->pthread(), 0);
always_assert(r == 0);
}
tree->stats(stderr);
exit(0);
}
void
epochinc(int)
{
globalepoch += 2;
active_epoch = threadinfo::min_active_epoch();
}
// Return 1 if success, -1 if I/O error or protocol unmatch
int handshake(Json& request, threadinfo& ti) {
always_assert(request.is_a() && request.size() >= 2
&& request[1].is_i() && request[1].as_i() == Cmd_Handshake
&& (request.size() == 2 || request[2].is_o()));
if (request.size() >= 2
&& request[2]["maxkeylen"].is_i()
&& request[2]["maxkeylen"].as_i() > MASSTREE_MAXKEYLEN) {
request[2] = false;
request[3] = "bad maxkeylen";
request.resize(4);
} else {
request[2] = true;
request[3] = ti.index();
request[4] = row_type::name();
request.resize(5);
}
request[1] = Cmd_Handshake + 1;
return request[2].as_b() ? 1 : -1;
}
// execute command, return result.
int onego(query<row_type>& q, Json& request, Str request_str, threadinfo& ti) {
int command = request[1].as_i();
if (command == Cmd_Checkpoint) {
// force checkpoint
pthread_mutex_lock(&checkpoint_mu);
pthread_cond_broadcast(&checkpoint_cond);
pthread_mutex_unlock(&checkpoint_mu);
request.resize(2);
} else if (command == Cmd_Get) {
q.run_get(tree->table(), request, ti);
} else if (command == Cmd_Put && request.size() > 3
&& (request.size() % 2) == 1) { // insert or update
Str key(request[2].as_s());
const Json* req = request.array_data() + 3;
const Json* end_req = request.end_array_data();
request[2] = q.run_put(tree->table(), request[2].as_s(),
req, end_req, ti);
if (ti.logger() && request_str) {
// use the client's parsed version of the request
msgpack::parser mp(request_str.data());
mp.skip_array_size().skip_primitives(3);
ti.logger()->record(logcmd_put, q.query_times(), key, Str(mp.position(), request_str.end()));
} else if (ti.logger())
ti.logger()->record(logcmd_put, q.query_times(), key, req, end_req);
request.resize(3);
} else if (command == Cmd_Replace) { // insert or update
Str key(request[2].as_s()), value(request[3].as_s());
request[2] = q.run_replace(tree->table(), key, value, ti);
if (ti.logger()) // NB may block
ti.logger()->record(logcmd_replace, q.query_times(), key, value);
request.resize(3);
} else if (command == Cmd_Remove) { // remove
Str key(request[2].as_s());
bool removed = q.run_remove(tree->table(), key, ti);
if (removed && ti.logger()) // NB may block
ti.logger()->record(logcmd_remove, q.query_times(), key, Str());