forked from kohler/masstree-beta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mtd.cc
1696 lines (1536 loc) · 48.9 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-2013 President and Fellows of Harvard College
* Copyright (c) 2012-2013 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++ -*-
// kvd: 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 "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 "masstree_query.hh"
#include <algorithm>
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
static int port = 2117;
static uint64_t test_limit = ~uint64_t(0);
static int doprint = 0;
static volatile sig_atomic_t go_quit = 0;
static int quit_pipe[2];
static const char *logdir[MaxCores];
static const char *ckpdir[MaxCores];
static int nlogdir = 0;
static int nckpdir = 0;
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 void *tcpgo(void *);
static void *udpgo(void *);
static int handshake(struct kvin *kvin, struct kvout *kvout, threadinfo *ti, bool &ok);
static int onego(query<row_type> &q, struct kvin *kvin, struct kvout *kvout, reqst_machine &rsm, threadinfo *ti);
static void log_init();
static void recover(threadinfo *);
static kvepoch_t read_checkpoint(threadinfo *, const char *path);
static uint64_t traverse_checkpoint_inorder(uint64_t off, uint64_t n,
char *base, uint64_t *ind,
uint64_t max, threadinfo *ti);
static void *conc_checkpointer(void *);
static void recovercheckpoint(threadinfo *ti);
static void *canceling(void *);
static void catchint(int);
static void epochinc(int);
static void print_stat();
/* 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_->ti_index;
}
int nthreads() const {
return testthreads;
}
void set_thread(threadinfo *ti) {
ti_ = ti;
}
void register_timeouts(int n) {
mandatory_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;
}
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, ...);
void report(const Json &result) {
json_.merge(result);
fprintf(stderr, "%d: %s\n", ti_->ti_index, json_.unparse().c_str());
}
threadinfo *ti_;
query<row_type> q_[10];
const char *testname_;
kvrandom_lcg_nr rand;
int checks_;
Json json_;
struct kvout *kvo_;
static volatile int failing;
};
volatile int kvtest_client::failing;
void kvtest_client::get(long ikey, Str *value)
{
quick_istr key(ikey);
q_[0].begin_get1(key.string());
if (tree->get(q_[0], ti_))
*value = q_[0].get1_value();
else
*value = Str();
}
void kvtest_client::get(const Str &key)
{
q_[0].begin_get1(key);
(void) tree->get(q_[0], ti_);
}
void kvtest_client::get_check(const Str &key, const Str &expected)
{
q_[0].begin_get1(key);
if (!tree->get(q_[0], ti_)) {
fail("get(%.*s) failed (expected %.*s)\n", key.len, key.s, expected.len, expected.s);
return;
}
Str val = q_[0].get1_value();
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)
{
q_[0].begin_get1(key, col);
if (!tree->get(q_[0], ti_)) {
fail("get.%d(%.*s) failed (expected %.*s)\n", col, key.len, key.s,
expected.len, expected.s);
return;
}
Str val = q_[0].get1_value();
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);
q_[0].begin_get1(key.string());
return tree->get(q_[0], ti_);
}
void kvtest_client::put(const Str &key, const Str &value) {
while (failing)
/* do nothing */;
q_[0].begin_replace(key, value);
(void) tree->replace(q_[0], ti_);
if (ti_->ti_log) // NB may block
ti_->ti_log->record(logcmd_put1, q_[0].query_times(), key, value);
}
void kvtest_client::put_col(const Str &key, int col, const Str &value) {
while (failing)
/* do nothing */;
#if !KVDB_ROW_TYPE_STR
if (!kvo_)
kvo_ = new_kvout(-1, 2048);
Str req = row_type::make_put_col_request(kvo_, col, value);
q_[0].begin_put(key, req);
(void) tree->put(q_[0], ti_);
if (ti_->ti_log) // NB may block
ti_->ti_log->record(logcmd_put, q_[0].query_times(), key, req);
#else
(void) key, (void) col, (void) value;
assert(0);
#endif
}
bool kvtest_client::remove_sync(long ikey) {
quick_istr key(ikey);
q_[0].begin_remove(key.string());
bool removed = tree->remove(q_[0], ti_);
if (removed && ti_->ti_log) // NB may block
ti_->ti_log->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_->ti_index, m.c_str());
}
void kvtest_client::fail(const char *fmt, ...) {
static spinlock failing_lock = {0};
static spinlock fail_message_lock = {0};
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";
acquire(&fail_message_lock);
if (fail_message != m) {
fail_message = m;
fprintf(stderr, "%d: %s", ti_->ti_index, m.c_str());
}
release(&fail_message_lock);
if (doprint) {
acquire(&failing_lock);
fprintf(stdout, "%d: %s", ti_->ti_index, m.c_str());
tree->print(stdout, 0);
fflush(stdout);
}
mandatory_assert(0);
}
static void *testgo(void *arg) {
kvtest_client *kc = (kvtest_client *) arg;
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, 31949 + kc->id());
else if (strcmp(kc->testname_, "r1") == 0)
kvtest_r1_seed(*kc, 31949 + kc->id());
else if (strcmp(kc->testname_, "wcol1") == 0)
kvtest_wcol1(*kc, 31949 + kc->id() % 48, 5000000);
else if (strcmp(kc->testname_, "rcol1") == 0)
kvtest_rcol1(*kc, 31949 + 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_->ti_threadid, 0, testgo, &clients[i]);
mandatory_assert(r == 0);
}
for (int i = 0; i < nthreads; ++i)
pthread_join(clients[i].ti_->ti_threadid, 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].json_.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]);
}
/* 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 };
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 }
};
int
main(int argc, char *argv[])
{
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;
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, ",");
while (s) {
mandatory_assert(nlogdir < MaxCores);
logdir[nlogdir++] = s;
s = strtok(NULL, ",");
}
break;
}
case opt_ckpdir: {
const char *s = strtok((char *) clp->vstr, ",");
while (s) {
mandatory_assert(nckpdir < MaxCores);
ckpdir[nckpdir++] = s;
s = strtok(NULL, ",");
}
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;
default:
fprintf(stderr, "Usage: kvd [-np] [--ld dir1[,dir2,...]] [--cd dir1[,dir2,...]]\n");
exit(EXIT_FAILURE);
}
}
Clp_DeleteParser(clp);
Perf::stat::initmain(pinthreads);
if (nlogdir == 0) {
logdir[0] = ".";
nlogdir = 1;
}
if (nckpdir == 0) {
ckpdir[0] = ".";
nckpdir = 1;
}
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;
// increment the global epoch every second
if (!dotest) {
signal(SIGALRM, epochinc);
struct itimerval etimer;
etimer.it_interval.tv_sec = 1;
etimer.it_interval.tv_usec = 0;
etimer.it_value.tv_sec = 1;
etimer.it_value.tv_usec = 0;
ret = setitimer(ITIMER_REAL, &etimer, NULL);
mandatory_assert(ret == 0);
}
// arrange for a per-thread threadinfo pointer
ret = pthread_key_create(&threadinfo::key, 0);
mandatory_assert(ret == 0);
// for parallel recovery
ret = pthread_cond_init(&rec_cond, 0);
mandatory_assert(ret == 0);
ret = pthread_mutex_init(&rec_mu, 0);
mandatory_assert(ret == 0);
// for waking up the checkpoint thread
ret = pthread_cond_init(&checkpoint_cond, 0);
mandatory_assert(ret == 0);
ret = pthread_mutex_init(&checkpoint_mu, 0);
mandatory_assert(ret == 0);
threadinfo *main_ti = threadinfo::make(threadinfo::TI_MAIN, -1);
main_ti->enter();
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->ti_threadid, 0, udpgo, ti);
mandatory_assert(ret == 0);
}
if (dotest) {
if (strcmp(dotest, "palm") == 0) {
runtest("palma", 1);
runtest("palmb", tcpthreads);
} else
runtest(dotest, tcpthreads);
print_stat();
tree->stats(stderr);
if (doprint)
tree->print(stdout, 0);
exit(0);
}
// TCP socket and threads
s = socket(AF_INET, SOCK_STREAM, 0);
mandatory_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];
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(ti->ti_pipe);
mandatory_assert(ret == 0);
ret = pthread_create(&ti->ti_threadid, 0, tcpgo, ti);
mandatory_assert(ret == 0);
tcpti[i] = ti;
}
// Create a canceling thread.
ret = pipe(quit_pipe);
assert(ret == 0);
pthread_t tid;
pthread_create(&tid, NULL, canceling, NULL);
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);
mandatory_assert(s1 >= 0);
// Bind the connection to a particular core if required.
int target_core;
if (read(s1, &target_core, sizeof(target_core)) != sizeof(target_core)) {
perror("read");
continue;
}
setsockopt(s1, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes));
threadinfo *ti;
if (target_core == -1) {
ti = tcpti[next % tcpthreads];
++next;
} else {
assert(pinthreads && target_core < tcpthreads);
ti = tcpti[target_core];
}
ssize_t w = write(ti->ti_pipe[1], &s1, sizeof(s1));
mandatory_assert((size_t) w == sizeof(s1));
}
}
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:
mandatory_assert(0 && "Unknown threadtype");
break;
};
}
void
print_stat()
{
int nstat = 0;
const Perf::stat *allstat[MaxCores * 2];
bzero(allstat, sizeof(allstat));
for (threadinfo *ti = threadinfo::allthreads; ti; ti = ti->ti_next)
if (ti->ti_purpose == threadinfo::TI_PROCESS)
allstat[nstat ++] = &ti->pstat;
Perf::stat::print(allstat, nstat);
}
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);
pthread_t me = pthread_self();
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->ti_next)
if (ti->ti_purpose != threadinfo::TI_MAIN
&& ti->ti_purpose != threadinfo::TI_CHECKPOINT
&& !pthread_equal(me, ti->ti_threadid)) {
int r = pthread_cancel(ti->ti_threadid);
mandatory_assert(r == 0);
}
// join canceled threads
for (threadinfo *ti = threadinfo::allthreads; ti; ti = ti->ti_next)
if (ti->ti_purpose != threadinfo::TI_MAIN
&& !pthread_equal(me, ti->ti_threadid)) {
fprintf(stderr, "joining thread %s:%d\n",
threadtype(ti->ti_purpose), ti->ti_index);
int r = pthread_join(ti->ti_threadid, 0);
mandatory_assert(r == 0);
}
print_stat();
tree->stats(stderr);
exit(0);
}
void
epochinc(int)
{
globalepoch += 2;
}
// Return 1 if success, -1 if I/O error or protocol unmatch
int
handshake(struct kvin *kvin, struct kvout *kvout, threadinfo *ti, bool &ok)
{
struct kvproto kvproto;
if (KVR(kvin, kvproto) != sizeof(kvproto))
return -1;
ok = kvproto.check();
KVW(kvout, ok);
KVW(kvout, ti->ti_index);
return ok ? 1 : -1;
}
// returns 2 if the request is incompleted, 1 if one request is
// ready, -1 on error
int
tryreadreq(struct kvin *kvin, reqst_machine &rsm)
{
int avail = kvcheck(kvin, 0);
while (avail > 0) {
int c = std::min(avail, rsm.wanted);
if (kvread(kvin, rsm.p, c) != c)
return -1;
rsm.p += c;
rsm.wanted -= c;
if (rsm.wanted)
return 2;
avail -= c;
switch (rsm.ci) {
case CI_Cmd:
assert(rsm.cmd > Cmd_None && rsm.cmd < Cmd_Max);
rsm.goto_seq();
break;
case CI_Seq:
if (rsm.cmd == Cmd_Checkpoint)
return 1;
rsm.goto_keylen();
break;
case CI_Keylen:
rsm.goto_key();
break;
case CI_Key:
if (rsm.cmd == Cmd_Remove)
return 1;
rsm.goto_reqlen();
break;
case CI_Reqlen:
rsm.goto_req();
break;
case CI_Req:
if (rsm.cmd != Cmd_Scan)
return 1;
rsm.goto_numpairs();
break;
case CI_Numpairs:
assert(rsm.cmd == Cmd_Scan);
return 1;
default:
assert(0 && "Bad component index");
}
}
return 2;
}
// read one cmd from a kvin, execute it.
// returns 2 if the request is incompleted, 1 if one request is processed,
// -1 for error
int
onego(query<row_type> &q, struct kvin *kvin, struct kvout *kvout,
reqst_machine &rsm, threadinfo *ti)
{
int r;
if ((r = tryreadreq(kvin, rsm)) != 1)
return r;
if(rsm.cmd == Cmd_Checkpoint){
// force checkpoint
pthread_mutex_lock(&checkpoint_mu);
pthread_cond_broadcast(&checkpoint_cond);
pthread_mutex_unlock(&checkpoint_mu);
}
else if(rsm.cmd == Cmd_Get){
KVW(kvout, rsm.seq);
q.begin_get(Str(rsm.key, rsm.keylen), Str(rsm.req, rsm.reqlen), kvout);
bool val_exists = tree->get(q, ti);
if(!val_exists){
//printf("no val for key %.*s\n", rsm.keylen, rsm.key);
KVW(kvout, (short)-1);
}
} else if (rsm.cmd == Cmd_Put || rsm.cmd == Cmd_Put_Status) { // insert or update
Str key(rsm.key, rsm.keylen), req(rsm.req, rsm.reqlen);
q.begin_put(key, req);
int status = tree->put(q, ti);
if (ti->ti_log) // NB may block
ti->ti_log->record(logcmd_put, q.query_times(), key, req);
KVW(kvout, rsm.seq);
if (rsm.cmd == Cmd_Put_Status)
KVW(kvout, status);
} else if(rsm.cmd == Cmd_Remove){ // remove
Str key(rsm.key, rsm.keylen);
q.begin_remove(key);
bool removed = tree->remove(q, ti);
if (removed && ti->ti_log) // NB may block
ti->ti_log->record(logcmd_remove, q.query_times(), key, Str());
KVW(kvout, rsm.seq);
KVW(kvout, (int) removed);
} else {
assert(rsm.cmd == Cmd_Scan);
KVW(kvout, rsm.seq);
if (rsm.numpairs > 0) {
q.begin_scan(Str(rsm.key, rsm.keylen), rsm.numpairs, Str(rsm.req, rsm.reqlen), kvout);
tree->scan(q, ti);
}
KVW(kvout, (int)0);
}
rsm.reset();
return 1;
}
#if HAVE_SYS_EPOLL_H
struct tcpfds {
int epollfd;
tcpfds(int pipefd) {
epollfd = epoll_create(10);
if (epollfd < 0) {
perror("epoll_create");
exit(EXIT_FAILURE);
}
struct epoll_event ev;
ev.events = EPOLLIN;
ev.data.ptr = (void *) 1;
int r = epoll_ctl(epollfd, EPOLL_CTL_ADD, pipefd, &ev);
mandatory_assert(r == 0);
}
enum { max_events = 100 };
typedef struct epoll_event eventset[max_events];
int wait(eventset &es) {
return epoll_wait(epollfd, es, max_events, -1);
}
conn *event_conn(eventset &es, int i) const {
return (conn *) es[i].data.ptr;
}
void add(int fd, conn *c) {
struct epoll_event ev;
ev.events = EPOLLIN;
ev.data.ptr = c;
int r = epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &ev);
mandatory_assert(r == 0);
}
void remove(int fd) {
int r = epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, NULL);
mandatory_assert(r == 0);
}
};