forked from XiaoMi/rdsn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
replica_stub.cpp
2642 lines (2382 loc) · 105 KB
/
replica_stub.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
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* Description:
* replica container - replica stub
*
* Revision history:
* Mar., 2015, @imzhenyu (Zhenyu Guo), first version
* xxxx-xx-xx, author, fix bug about xxx
*/
#include "replica.h"
#include "replica_stub.h"
#include "mutation_log.h"
#include "mutation.h"
#include "duplication/duplication_sync_timer.h"
#include "dist/replication/lib/backup/replica_backup_manager.h"
#include <dsn/cpp/json_helper.h>
#include <dsn/utility/filesystem.h>
#include <dsn/utility/rand.h>
#include <dsn/utility/string_conv.h>
#include <dsn/tool-api/command_manager.h>
#include <dsn/dist/replication/replication_app_base.h>
#include <vector>
#include <deque>
#include <dsn/dist/fmt_logging.h>
#ifdef DSN_ENABLE_GPERF
#include <gperftools/malloc_extension.h>
#endif
#include <dsn/utility/fail_point.h>
namespace dsn {
namespace replication {
bool replica_stub::s_not_exit_on_log_failure = false;
replica_stub::replica_stub(replica_state_subscriber subscriber /*= nullptr*/,
bool is_long_subscriber /* = true*/)
: serverlet("replica_stub"),
_kill_partition_command(nullptr),
_deny_client_command(nullptr),
_verbose_client_log_command(nullptr),
_verbose_commit_log_command(nullptr),
_trigger_chkpt_command(nullptr),
_query_compact_command(nullptr),
_query_app_envs_command(nullptr),
_useless_dir_reserve_seconds_command(nullptr),
_deny_client(false),
_verbose_client_log(false),
_verbose_commit_log(false),
_gc_disk_error_replica_interval_seconds(3600),
_gc_disk_garbage_replica_interval_seconds(3600),
_release_tcmalloc_memory(false),
_mem_release_max_reserved_mem_percentage(10),
_learn_app_concurrent_count(0),
_fs_manager(false)
{
#ifdef DSN_ENABLE_GPERF
_release_tcmalloc_memory_command = nullptr;
_max_reserved_memory_percentage_command = nullptr;
#endif
_replica_state_subscriber = subscriber;
_is_long_subscriber = is_long_subscriber;
_failure_detector = nullptr;
_state = NS_Disconnected;
_log = nullptr;
_primary_address_str[0] = '\0';
install_perf_counters();
_max_allowed_write_size = dsn_config_get_value_uint64("replication",
"max_allowed_write_size",
1 << 20,
"write operation exceed this "
"threshold will be logged and reject, "
"default is 1MB, 0 means no check");
}
replica_stub::~replica_stub(void) { close(); }
void replica_stub::install_perf_counters()
{
_counter_replicas_count.init_app_counter(
"eon.replica_stub", "replica(Count)", COUNTER_TYPE_NUMBER, "# in replica_stub._replicas");
_counter_replicas_opening_count.init_app_counter("eon.replica_stub",
"opening.replica(Count)",
COUNTER_TYPE_NUMBER,
"# in replica_stub._opening_replicas");
_counter_replicas_closing_count.init_app_counter("eon.replica_stub",
"closing.replica(Count)",
COUNTER_TYPE_NUMBER,
"# in replica_stub._closing_replicas");
_counter_replicas_commit_qps.init_app_counter("eon.replica_stub",
"replicas.commit.qps",
COUNTER_TYPE_RATE,
"server-level commit throughput");
_counter_replicas_learning_count.init_app_counter("eon.replica_stub",
"replicas.learning.count",
COUNTER_TYPE_NUMBER,
"current learning count");
_counter_replicas_learning_max_duration_time_ms.init_app_counter(
"eon.replica_stub",
"replicas.learning.max.duration.time(ms)",
COUNTER_TYPE_NUMBER,
"current learning max duration time(ms)");
_counter_replicas_learning_max_copy_file_size.init_app_counter(
"eon.replica_stub",
"replicas.learning.max.copy.file.size",
COUNTER_TYPE_NUMBER,
"current learning max copy file size");
_counter_replicas_learning_recent_start_count.init_app_counter(
"eon.replica_stub",
"replicas.learning.recent.start.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"current learning start count in the recent period");
_counter_replicas_learning_recent_round_start_count.init_app_counter(
"eon.replica_stub",
"replicas.learning.recent.round.start.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"learning round start count in the recent period");
_counter_replicas_learning_recent_copy_file_count.init_app_counter(
"eon.replica_stub",
"replicas.learning.recent.copy.file.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"learning copy file count in the recent period");
_counter_replicas_learning_recent_copy_file_size.init_app_counter(
"eon.replica_stub",
"replicas.learning.recent.copy.file.size",
COUNTER_TYPE_VOLATILE_NUMBER,
"learning copy file size in the recent period");
_counter_replicas_learning_recent_copy_buffer_size.init_app_counter(
"eon.replica_stub",
"replicas.learning.recent.copy.buffer.size",
COUNTER_TYPE_VOLATILE_NUMBER,
"learning copy buffer size in the recent period");
_counter_replicas_learning_recent_learn_cache_count.init_app_counter(
"eon.replica_stub",
"replicas.learning.recent.learn.cache.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"learning LT_CACHE count in the recent period");
_counter_replicas_learning_recent_learn_app_count.init_app_counter(
"eon.replica_stub",
"replicas.learning.recent.learn.app.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"learning LT_APP count in the recent period");
_counter_replicas_learning_recent_learn_log_count.init_app_counter(
"eon.replica_stub",
"replicas.learning.recent.learn.log.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"learning LT_LOG count in the recent period");
_counter_replicas_learning_recent_learn_reset_count.init_app_counter(
"eon.replica_stub",
"replicas.learning.recent.learn.reset.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"learning reset count in the recent period"
"for the reason of resp.last_committed_decree < _app->last_committed_decree()");
_counter_replicas_learning_recent_learn_fail_count.init_app_counter(
"eon.replica_stub",
"replicas.learning.recent.learn.fail.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"learning fail count in the recent period");
_counter_replicas_learning_recent_learn_succ_count.init_app_counter(
"eon.replica_stub",
"replicas.learning.recent.learn.succ.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"learning succeed count in the recent period");
_counter_replicas_recent_prepare_fail_count.init_app_counter(
"eon.replica_stub",
"replicas.recent.prepare.fail.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"prepare fail count in the recent period");
_counter_replicas_recent_replica_move_error_count.init_app_counter(
"eon.replica_stub",
"replicas.recent.replica.move.error.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"replica move to error count in the recent period");
_counter_replicas_recent_replica_move_garbage_count.init_app_counter(
"eon.replica_stub",
"replicas.recent.replica.move.garbage.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"replica move to garbage count in the recent period");
_counter_replicas_recent_replica_remove_dir_count.init_app_counter(
"eon.replica_stub",
"replicas.recent.replica.remove.dir.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"replica directory remove count in the recent period");
_counter_replicas_error_replica_dir_count.init_app_counter("eon.replica_stub",
"replicas.error.replica.dir.count",
COUNTER_TYPE_NUMBER,
"error replica directory count");
_counter_replicas_garbage_replica_dir_count.init_app_counter(
"eon.replica_stub",
"replicas.garbage.replica.dir.count",
COUNTER_TYPE_NUMBER,
"garbage replica directory count");
_counter_shared_log_size.init_app_counter(
"eon.replica_stub", "shared.log.size(MB)", COUNTER_TYPE_NUMBER, "shared log size(MB)");
_counter_shared_log_recent_write_size.init_app_counter(
"eon.replica_stub",
"shared.log.recent.write.size",
COUNTER_TYPE_VOLATILE_NUMBER,
"shared log write size in the recent period");
_counter_recent_trigger_emergency_checkpoint_count.init_app_counter(
"eon.replica_stub",
"recent.trigger.emergency.checkpoint.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"trigger emergency checkpoint count in the recent period");
// <- Duplication Metrics ->
_counter_dup_confirmed_rate.init_app_counter("eon.replica_stub",
"dup.confirmed_rate",
COUNTER_TYPE_RATE,
"increasing rate of confirmed mutations");
_counter_dup_pending_mutations_count.init_app_counter(
"eon.replica_stub",
"dup.pending_mutations_count",
COUNTER_TYPE_VOLATILE_NUMBER,
"number of mutations pending for duplication");
_counter_dup_time_lag.init_app_counter(
"eon.replica_stub",
"dup.time_lag(ms)",
COUNTER_TYPE_NUMBER_PERCENTILES,
"time (in ms) lag between master and slave in the duplication");
// <- Cold Backup Metrics ->
_counter_cold_backup_running_count.init_app_counter("eon.replica_stub",
"cold.backup.running.count",
COUNTER_TYPE_NUMBER,
"current cold backup count");
_counter_cold_backup_recent_start_count.init_app_counter(
"eon.replica_stub",
"cold.backup.recent.start.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"current cold backup start count in the recent period");
_counter_cold_backup_recent_succ_count.init_app_counter(
"eon.replica_stub",
"cold.backup.recent.succ.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"current cold backup succeed count in the recent period");
_counter_cold_backup_recent_fail_count.init_app_counter(
"eon.replica_stub",
"cold.backup.recent.fail.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"current cold backup fail count in the recent period");
_counter_cold_backup_recent_cancel_count.init_app_counter(
"eon.replica_stub",
"cold.backup.recent.cancel.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"current cold backup cancel count in the recent period");
_counter_cold_backup_recent_pause_count.init_app_counter(
"eon.replica_stub",
"cold.backup.recent.pause.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"current cold backup pause count in the recent period");
_counter_cold_backup_recent_upload_file_succ_count.init_app_counter(
"eon.replica_stub",
"cold.backup.recent.upload.file.succ.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"current cold backup upload file succeed count in the recent period");
_counter_cold_backup_recent_upload_file_fail_count.init_app_counter(
"eon.replica_stub",
"cold.backup.recent.upload.file.fail.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"current cold backup upload file failed count in the recent period");
_counter_cold_backup_recent_upload_file_size.init_app_counter(
"eon.replica_stub",
"cold.backup.recent.upload.file.size",
COUNTER_TYPE_VOLATILE_NUMBER,
"current cold backup upload file size in the recent perriod");
_counter_cold_backup_max_duration_time_ms.init_app_counter(
"eon.replica_stub",
"cold.backup.max.duration.time.ms",
COUNTER_TYPE_NUMBER,
"current cold backup max duration time");
_counter_cold_backup_max_upload_file_size.init_app_counter(
"eon.replica_stub",
"cold.backup.max.upload.file.size",
COUNTER_TYPE_NUMBER,
"current cold backup max upload file size");
_counter_recent_read_fail_count.init_app_counter("eon.replica_stub",
"recent.read.fail.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"read fail count in the recent period");
_counter_recent_write_fail_count.init_app_counter("eon.replica_stub",
"recent.write.fail.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"write fail count in the recent period");
_counter_recent_read_busy_count.init_app_counter("eon.replica_stub",
"recent.read.busy.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"read busy count in the recent period");
_counter_recent_write_busy_count.init_app_counter("eon.replica_stub",
"recent.write.busy.count",
COUNTER_TYPE_VOLATILE_NUMBER,
"write busy count in the recent period");
_counter_recent_write_size_exceed_threshold_count.init_app_counter(
"eon.replica_stub",
"recent_write_size_exceed_threshold_count",
COUNTER_TYPE_VOLATILE_NUMBER,
"write size exceed threshold count in the recent period");
#ifdef DSN_ENABLE_GPERF
_counter_tcmalloc_release_memory_size.init_app_counter("eon.replica_stub",
"tcmalloc.release.memory.size",
COUNTER_TYPE_NUMBER,
"current tcmalloc release memory size");
#endif
}
void replica_stub::initialize(bool clear /* = false*/)
{
replication_options opts;
opts.initialize();
initialize(opts, clear);
}
void replica_stub::initialize(const replication_options &opts, bool clear /* = false*/)
{
_primary_address = dsn_primary_address();
strcpy(_primary_address_str, _primary_address.to_string());
ddebug("primary_address = %s", _primary_address_str);
set_options(opts);
std::ostringstream oss;
for (int i = 0; i < _options.meta_servers.size(); ++i) {
if (i != 0)
oss << ",";
oss << _options.meta_servers[i].to_string();
}
ddebug("meta_servers = %s", oss.str().c_str());
_deny_client = _options.deny_client_on_start;
_verbose_client_log = _options.verbose_client_log_on_start;
_verbose_commit_log = _options.verbose_commit_log_on_start;
_gc_disk_error_replica_interval_seconds = _options.gc_disk_error_replica_interval_seconds;
_gc_disk_garbage_replica_interval_seconds = _options.gc_disk_garbage_replica_interval_seconds;
_release_tcmalloc_memory = _options.mem_release_enabled;
_mem_release_max_reserved_mem_percentage = _options.mem_release_max_reserved_mem_percentage;
// clear dirs if need
if (clear) {
if (!dsn::utils::filesystem::remove_path(_options.slog_dir)) {
dassert(false, "Fail to remove %s.", _options.slog_dir.c_str());
}
for (auto &dir : _options.data_dirs) {
if (!dsn::utils::filesystem::remove_path(dir)) {
dassert(false, "Fail to remove %s.", dir.c_str());
}
}
}
// init dirs
if (!dsn::utils::filesystem::create_directory(_options.slog_dir)) {
dassert(false, "Fail to create directory %s.", _options.slog_dir.c_str());
}
std::string cdir;
if (!dsn::utils::filesystem::get_absolute_path(_options.slog_dir, cdir)) {
dassert(false, "Fail to get absolute path from %s.", _options.slog_dir.c_str());
}
_options.slog_dir = cdir;
int count = 0;
for (auto &dir : _options.data_dirs) {
if (!dsn::utils::filesystem::create_directory(dir)) {
dassert(false, "Fail to create directory %s.", dir.c_str());
}
std::string cdir;
if (!dsn::utils::filesystem::get_absolute_path(dir, cdir)) {
dassert(false, "Fail to get absolute path from %s.", dir.c_str());
}
dir = cdir;
ddebug("data_dirs[%d] = %s", count, dir.c_str());
count++;
}
{
dsn::error_code err;
err = _fs_manager.initialize(_options.data_dirs, _options.data_dir_tags, false);
dassert(err == dsn::ERR_OK, "initialize fs manager failed, err(%s)", err.to_string());
}
_log = new mutation_log_shared(_options.slog_dir,
_options.log_shared_file_size_mb,
_options.log_shared_force_flush,
&_counter_shared_log_recent_write_size);
ddebug("slog_dir = %s", _options.slog_dir.c_str());
// init rps
ddebug("start to load replicas");
std::vector<std::string> dir_list;
for (auto &dir : _options.data_dirs) {
std::vector<std::string> tmp_list;
if (!dsn::utils::filesystem::get_subdirectories(dir, tmp_list, false)) {
dassert(false, "Fail to get subdirectories in %s.", dir.c_str());
}
dir_list.insert(dir_list.end(), tmp_list.begin(), tmp_list.end());
}
replicas rps;
utils::ex_lock rps_lock;
std::deque<task_ptr> load_tasks;
uint64_t start_time = dsn_now_ms();
for (auto &dir : dir_list) {
if (dir.length() >= 4 &&
(dir.substr(dir.length() - 4) == ".err" || dir.substr(dir.length() - 4) == ".gar" ||
dir.substr(dir.length() - 4) == ".bak")) {
ddebug("ignore dir %s", dir.c_str());
continue;
}
load_tasks.push_back(tasking::create_task(
LPC_REPLICATION_INIT_LOAD,
&_tracker,
[this, dir, &rps, &rps_lock] {
ddebug("process dir %s", dir.c_str());
auto r = replica::load(this, dir.c_str());
if (r != nullptr) {
ddebug("%s@%s: load replica '%s' success, <durable, commit> = <%" PRId64
", %" PRId64 ">, last_prepared_decree = %" PRId64,
r->get_gpid().to_string(),
dsn_primary_address().to_string(),
dir.c_str(),
r->last_durable_decree(),
r->last_committed_decree(),
r->last_prepared_decree());
utils::auto_lock<utils::ex_lock> l(rps_lock);
if (rps.find(r->get_gpid()) != rps.end()) {
dassert(false,
"conflict replica dir: %s <--> %s",
r->dir().c_str(),
rps[r->get_gpid()]->dir().c_str());
}
rps[r->get_gpid()] = r;
}
},
load_tasks.size()));
load_tasks.back()->enqueue();
}
for (auto &tsk : load_tasks) {
tsk->wait();
}
uint64_t finish_time = dsn_now_ms();
dir_list.clear();
load_tasks.clear();
ddebug("load replicas succeed, replica_count = %d, time_used = %" PRIu64 " ms",
static_cast<int>(rps.size()),
finish_time - start_time);
// init shared prepare log
ddebug("start to replay shared log");
std::map<gpid, decree> replay_condition;
for (auto it = rps.begin(); it != rps.end(); ++it) {
replay_condition[it->first] = it->second->last_committed_decree();
}
start_time = dsn_now_ms();
error_code err = _log->open(
[&rps](int log_length, mutation_ptr &mu) {
auto it = rps.find(mu->data.header.pid);
if (it != rps.end()) {
return it->second->replay_mutation(mu, false);
} else {
return false;
}
},
[this](error_code err) { this->handle_log_failure(err); },
replay_condition);
finish_time = dsn_now_ms();
if (err == ERR_OK) {
ddebug("replay shared log succeed, time_used = %" PRIu64 " ms", finish_time - start_time);
} else {
derror("replay shared log failed, err = %s, time_used = %" PRIu64 " ms, clear all logs ...",
err.to_string(),
finish_time - start_time);
// we must delete or update meta server the error for all replicas
// before we fix the logs
// otherwise, the next process restart may consider the replicas'
// state complete
// delete all replicas
// TODO: checkpoint latest state and update on meta server so learning is cheaper
for (auto it = rps.begin(); it != rps.end(); ++it) {
it->second->close();
// move to '.err' directory
const char *dir = it->second->dir().c_str();
char rename_dir[1024];
sprintf(rename_dir, "%s.%" PRIu64 ".err", dir, dsn_now_us());
bool ret = dsn::utils::filesystem::rename_path(dir, rename_dir);
dassert(ret, "init_replica: failed to move directory '%s' to '%s'", dir, rename_dir);
dwarn("init_replica: {replica_dir_op} succeed to move directory '%s' to '%s'",
dir,
rename_dir);
_counter_replicas_recent_replica_move_error_count->increment();
}
rps.clear();
// restart log service
_log->close();
_log = nullptr;
if (!utils::filesystem::remove_path(_options.slog_dir)) {
dassert(false, "remove directory %s failed", _options.slog_dir.c_str());
}
_log = new mutation_log_shared(_options.slog_dir,
_options.log_shared_file_size_mb,
_options.log_shared_force_flush,
&_counter_shared_log_recent_write_size);
auto lerr = _log->open(nullptr, [this](error_code err) { this->handle_log_failure(err); });
dassert(lerr == ERR_OK, "restart log service must succeed");
}
bool is_log_complete = true;
for (auto it = rps.begin(); it != rps.end(); ++it) {
auto err = it->second->background_sync_checkpoint();
dassert(err == ERR_OK, "sync checkpoint failed, err = %s", err.to_string());
it->second->reset_prepare_list_after_replay();
decree smax = _log->max_decree(it->first);
decree pmax = invalid_decree;
decree pmax_commit = invalid_decree;
if (it->second->private_log()) {
pmax = it->second->private_log()->max_decree(it->first);
pmax_commit = it->second->private_log()->max_commit_on_disk();
// possible when shared log is restarted
if (smax == 0) {
_log->update_max_decree(it->first, pmax);
smax = pmax;
}
else if (err == ERR_OK && pmax < smax) {
it->second->private_log()->flush();
pmax = it->second->private_log()->max_decree(it->first);
}
}
ddebug("%s: load replica done, err = %s, durable = %" PRId64 ", committed = %" PRId64 ", "
"prepared = %" PRId64 ", ballot = %" PRId64 ", "
"valid_offset_in_plog = %" PRId64 ", max_decree_in_plog = %" PRId64
", max_commit_on_disk_in_plog = %" PRId64 ", "
"valid_offset_in_slog = %" PRId64 ", max_decree_in_slog = %" PRId64 "",
it->second->name(),
err.to_string(),
it->second->last_durable_decree(),
it->second->last_committed_decree(),
it->second->max_prepared_decree(),
it->second->get_ballot(),
it->second->get_app()->init_info().init_offset_in_private_log,
pmax,
pmax_commit,
it->second->get_app()->init_info().init_offset_in_shared_log,
smax);
if (err == ERR_OK) {
if (smax != pmax) {
derror("%s: some shared log state must be lost, smax(%" PRId64 ") vs pmax(%" PRId64
")",
it->second->name(),
smax,
pmax);
is_log_complete = false;
} else {
// just leave inactive_state_transient as its old value
}
} else {
it->second->set_inactive_state_transient(false);
}
}
// we will mark all replicas inactive not transient unless all logs are complete
if (!is_log_complete) {
derror("logs are not complete for some replicas, which means that shared log is truncated, "
"mark all replicas as inactive");
for (auto it = rps.begin(); it != rps.end(); ++it) {
it->second->set_inactive_state_transient(false);
}
}
// gc
if (false == _options.gc_disabled) {
_gc_timer_task = tasking::enqueue_timer(
LPC_GARBAGE_COLLECT_LOGS_AND_REPLICAS,
&_tracker,
[this] { on_gc(); },
std::chrono::milliseconds(_options.gc_interval_ms),
0,
std::chrono::milliseconds(rand::next_u32(0, _options.gc_interval_ms)));
}
// disk stat
if (false == _options.disk_stat_disabled) {
_disk_stat_timer_task = ::dsn::tasking::enqueue_timer(
LPC_DISK_STAT,
&_tracker,
[this]() { on_disk_stat(); },
std::chrono::seconds(_options.disk_stat_interval_seconds),
0,
std::chrono::seconds(_options.disk_stat_interval_seconds));
}
// attach rps
_replicas = std::move(rps);
_counter_replicas_count->add((uint64_t)_replicas.size());
for (const auto &kv : _replicas) {
_fs_manager.add_replica(kv.first, kv.second->dir());
}
_nfs = std::move(dsn::nfs_node::create());
_nfs->start();
_cli_service = std::move(dsn::cli_service::create_service());
_cli_service->open_service();
if (_options.delay_for_fd_timeout_on_start) {
uint64_t now_time_ms = dsn_now_ms();
uint64_t delay_time_ms =
(_options.fd_grace_seconds + 3) * 1000; // for more 3 seconds than grace seconds
if (now_time_ms < dsn::utils::process_start_millis() + delay_time_ms) {
uint64_t delay = dsn::utils::process_start_millis() + delay_time_ms - now_time_ms;
ddebug("delay for %" PRIu64 "ms to make failure detector timeout", delay);
tasking::enqueue(LPC_REPLICA_SERVER_DELAY_START,
&_tracker,
[this]() { this->initialize_start(); },
0,
std::chrono::milliseconds(delay));
} else {
initialize_start();
}
} else {
initialize_start();
}
}
void replica_stub::initialize_start()
{
// start timer for configuration sync
if (!_options.config_sync_disabled) {
_config_sync_timer_task =
tasking::enqueue_timer(LPC_QUERY_CONFIGURATION_ALL,
&_tracker,
[this]() {
zauto_lock l(_state_lock);
this->query_configuration_by_node();
},
std::chrono::milliseconds(_options.config_sync_interval_ms),
0,
std::chrono::milliseconds(_options.config_sync_interval_ms));
}
#ifdef DSN_ENABLE_GPERF
_mem_release_timer_task =
tasking::enqueue_timer(LPC_MEM_RELEASE,
&_tracker,
std::bind(&replica_stub::gc_tcmalloc_memory, this),
std::chrono::milliseconds(_options.mem_release_check_interval_ms),
0,
std::chrono::milliseconds(_options.mem_release_check_interval_ms));
#endif
if (_options.duplication_enabled) {
_duplication_sync_timer = dsn::make_unique<duplication_sync_timer>(this);
_duplication_sync_timer->start();
}
// init liveness monitor
dassert(NS_Disconnected == _state, "");
if (_options.fd_disabled == false) {
_failure_detector = new ::dsn::dist::slave_failure_detector_with_multimaster(
_options.meta_servers,
[this]() { this->on_meta_server_disconnected(); },
[this]() { this->on_meta_server_connected(); });
auto err = _failure_detector->start(_options.fd_check_interval_seconds,
_options.fd_beacon_interval_seconds,
_options.fd_lease_seconds,
_options.fd_grace_seconds);
dassert(err == ERR_OK, "FD start failed, err = %s", err.to_string());
_failure_detector->register_master(_failure_detector->current_server_contact());
} else {
_state = NS_Connected;
}
}
dsn::error_code replica_stub::on_kill_replica(gpid id)
{
ddebug("kill replica: gpid = %s", id.to_string());
if (id.get_app_id() == -1 || id.get_partition_index() == -1) {
replicas rs;
{
zauto_read_lock l(_replicas_lock);
rs = _replicas;
}
for (auto it = rs.begin(); it != rs.end(); ++it) {
replica_ptr &r = it->second;
if (id.get_app_id() == -1 || id.get_app_id() == r->get_gpid().get_app_id())
r->inject_error(ERR_INJECTED);
}
return ERR_OK;
} else {
error_code err = ERR_INVALID_PARAMETERS;
replica_ptr r = get_replica(id);
if (r == nullptr) {
err = ERR_OBJECT_NOT_FOUND;
} else {
r->inject_error(ERR_INJECTED);
err = ERR_OK;
}
return err;
}
}
replica_ptr replica_stub::get_replica(gpid id)
{
zauto_read_lock l(_replicas_lock);
auto it = _replicas.find(id);
if (it != _replicas.end())
return it->second;
else
return nullptr;
}
replica_stub::replica_life_cycle replica_stub::get_replica_life_cycle(gpid id)
{
zauto_read_lock l(_replicas_lock);
if (_opening_replicas.find(id) != _opening_replicas.end())
return replica_stub::RL_creating;
if (_replicas.find(id) != _replicas.end())
return replica_stub::RL_serving;
if (_closing_replicas.find(id) != _closing_replicas.end())
return replica_stub::RL_closing;
if (_closed_replicas.find(id) != _closed_replicas.end())
return replica_stub::RL_closed;
return replica_stub::RL_invalid;
}
void replica_stub::on_client_write(gpid id, dsn::message_ex *request)
{
if (_deny_client) {
// ignore and do not reply
return;
}
if (_verbose_client_log && request) {
ddebug("%s@%s: client = %s, code = %s, timeout = %d",
id.to_string(),
_primary_address_str,
request->header->from_address.to_string(),
request->header->rpc_name,
request->header->client.timeout_ms);
}
replica_ptr rep = get_replica(id);
if (rep != nullptr) {
rep->on_client_write(request);
} else {
response_client(id, false, request, partition_status::PS_INVALID, ERR_OBJECT_NOT_FOUND);
}
}
void replica_stub::on_client_read(gpid id, dsn::message_ex *request)
{
if (_deny_client) {
// ignore and do not reply
return;
}
if (_verbose_client_log && request) {
ddebug("%s@%s: client = %s, code = %s, timeout = %d",
id.to_string(),
_primary_address_str,
request->header->from_address.to_string(),
request->header->rpc_name,
request->header->client.timeout_ms);
}
replica_ptr rep = get_replica(id);
if (rep != nullptr) {
rep->on_client_read(request);
} else {
response_client(id, true, request, partition_status::PS_INVALID, ERR_OBJECT_NOT_FOUND);
}
}
void replica_stub::on_config_proposal(const configuration_update_request &proposal)
{
if (!is_connected()) {
dwarn("%s@%s: received config proposal %s for %s: not connected, ignore",
proposal.config.pid.to_string(),
_primary_address_str,
enum_to_string(proposal.type),
proposal.node.to_string());
return;
}
ddebug("%s@%s: received config proposal %s for %s",
proposal.config.pid.to_string(),
_primary_address_str,
enum_to_string(proposal.type),
proposal.node.to_string());
replica_ptr rep = get_replica(proposal.config.pid);
if (rep == nullptr) {
if (proposal.type == config_type::CT_ASSIGN_PRIMARY) {
std::shared_ptr<configuration_update_request> req2(new configuration_update_request);
*req2 = proposal;
begin_open_replica(proposal.info, proposal.config.pid, nullptr, req2);
} else if (proposal.type == config_type::CT_UPGRADE_TO_PRIMARY) {
remove_replica_on_meta_server(proposal.info, proposal.config);
}
}
if (rep != nullptr) {
rep->on_config_proposal((configuration_update_request &)proposal);
}
}
void replica_stub::on_query_decree(const query_replica_decree_request &req,
/*out*/ query_replica_decree_response &resp)
{
replica_ptr rep = get_replica(req.pid);
if (rep != nullptr) {
resp.err = ERR_OK;
if (partition_status::PS_POTENTIAL_SECONDARY == rep->status()) {
resp.last_decree = 0;
} else {
resp.last_decree = rep->last_committed_decree();
// TODO: use the following to alleviate data lost
// resp.last_decree = rep->last_prepared_decree();
}
} else {
resp.err = ERR_OBJECT_NOT_FOUND;
resp.last_decree = 0;
}
}
void replica_stub::on_query_replica_info(const query_replica_info_request &req,
/*out*/ query_replica_info_response &resp)
{
std::set<gpid> visited_replicas;
{
zauto_read_lock l(_replicas_lock);
for (auto it = _replicas.begin(); it != _replicas.end(); ++it) {
replica_ptr &r = it->second;
replica_info info;
get_replica_info(info, r);
if (visited_replicas.find(info.pid) == visited_replicas.end()) {
visited_replicas.insert(info.pid);
resp.replicas.push_back(std::move(info));
}
}
for (auto it = _closing_replicas.begin(); it != _closing_replicas.end(); ++it) {
const replica_info &info = std::get<3>(it->second);
if (visited_replicas.find(info.pid) == visited_replicas.end()) {
visited_replicas.insert(info.pid);
resp.replicas.push_back(info);
}
}
for (auto it = _closed_replicas.begin(); it != _closed_replicas.end(); ++it) {
const replica_info &info = it->second.second;
if (visited_replicas.find(info.pid) == visited_replicas.end()) {
visited_replicas.insert(info.pid);
resp.replicas.push_back(info);
}
}
}
resp.err = ERR_OK;
}
// ThreadPool: THREAD_POOL_DEFAULT
void replica_stub::on_query_disk_info(const query_disk_info_request &req,
/*out*/ query_disk_info_response &resp)
{
int app_id = 0;
if (!req.app_name.empty()) {
zauto_read_lock l(_replicas_lock);
if (!(app_id = get_app_id_from_replicas(req.app_name))) {
resp.err = ERR_OBJECT_NOT_FOUND;
return;
}
}
for (const auto &dir_node : _fs_manager._dir_nodes) {
disk_info info;
// app_name empty means query all app replica_count
if (req.app_name.empty()) {
for (const auto &holding_primary_replicas : dir_node->holding_primary_replicas) {
info.holding_primary_replica_counts[holding_primary_replicas.first] =
static_cast<int>(holding_primary_replicas.second.size());
}
for (const auto &holding_secondary_replicas : dir_node->holding_secondary_replicas) {
info.holding_secondary_replica_counts[holding_secondary_replicas.first] =
static_cast<int>(holding_secondary_replicas.second.size());
}
} else {
const auto &primary_iter = dir_node->holding_primary_replicas.find(app_id);
if (primary_iter != dir_node->holding_primary_replicas.end()) {
info.holding_primary_replica_counts[app_id] =
static_cast<int>(primary_iter->second.size());
}
const auto &secondary_iter = dir_node->holding_secondary_replicas.find(app_id);
if (secondary_iter != dir_node->holding_secondary_replicas.end()) {
info.holding_secondary_replica_counts[app_id] =
static_cast<int>(secondary_iter->second.size());
}
}
info.tag = dir_node->tag;
info.full_dir = dir_node->full_dir;
info.disk_capacity_mb = dir_node->disk_capacity_mb;
info.disk_available_mb = dir_node->disk_available_mb;
resp.disk_infos.emplace_back(info);
}
resp.total_capacity_mb = _fs_manager._total_capacity_mb;
resp.total_available_mb = _fs_manager._total_available_mb;
resp.err = ERR_OK;
}
void replica_stub::on_query_app_info(const query_app_info_request &req,
query_app_info_response &resp)
{
ddebug("got query app info request from (%s)", req.meta_server.to_string());
resp.err = dsn::ERR_OK;
std::set<app_id> visited_apps;
{
zauto_read_lock l(_replicas_lock);
for (auto it = _replicas.begin(); it != _replicas.end(); ++it) {
replica_ptr &r = it->second;
const app_info &info = *r->get_app_info();
if (visited_apps.find(info.app_id) == visited_apps.end()) {
resp.apps.push_back(info);
visited_apps.insert(info.app_id);
}
}
for (auto it = _closing_replicas.begin(); it != _closing_replicas.end(); ++it) {
const app_info &info = std::get<2>(it->second);
if (visited_apps.find(info.app_id) == visited_apps.end()) {
resp.apps.push_back(info);
visited_apps.insert(info.app_id);
}
}
for (auto it = _closed_replicas.begin(); it != _closed_replicas.end(); ++it) {
const app_info &info = it->second.first;
if (visited_apps.find(info.app_id) == visited_apps.end()) {
resp.apps.push_back(info);
visited_apps.insert(info.app_id);
}
}
}
}
void replica_stub::on_cold_backup(const backup_request &request, /*out*/ backup_response &response)
{
ddebug("received cold backup request: backup{%s.%s.%" PRId64 "}",
request.pid.to_string(),
request.policy.policy_name.c_str(),
request.backup_id);
response.pid = request.pid;
response.policy_name = request.policy.policy_name;
response.backup_id = request.backup_id;
if (_options.cold_backup_root.empty()) {
derror("backup{%s.%s.%" PRId64