-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathpika_server.cc
1590 lines (1396 loc) · 55.8 KB
/
pika_server.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
// Copyright (c) 2015-present, Qihoo, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include "include/pika_server.h"
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <sys/resource.h>
#include <algorithm>
#include <ctime>
#include <fstream>
#include "net/include/bg_thread.h"
#include "net/include/net_cli.h"
#include "net/include/net_interfaces.h"
#include "net/include/redis_cli.h"
#include "pstd/include/env.h"
#include "pstd/include/rsync.h"
#include "include/pika_cmd_table_manager.h"
#include "include/pika_dispatch_thread.h"
#include "include/pika_rm.h"
#include "include/pika_server.h"
extern PikaServer* g_pika_server;
extern PikaReplicaManager* g_pika_rm;
extern PikaCmdTableManager* g_pika_cmd_table_manager;
void DoPurgeDir(void* arg) {
std::string path = *(static_cast<std::string*>(arg));
LOG(INFO) << "Delete dir: " << path << " start";
pstd::DeleteDir(path);
LOG(INFO) << "Delete dir: " << path << " done";
delete static_cast<std::string*>(arg);
}
void DoDBSync(void* arg) {
DBSyncArg* dbsa = reinterpret_cast<DBSyncArg*>(arg);
PikaServer* const ps = dbsa->p;
ps->DbSyncSendFile(dbsa->ip, dbsa->port, dbsa->table_name, dbsa->partition_id);
delete dbsa;
}
PikaServer::PikaServer()
: exit_(false),
slot_state_(INFREE),
have_scheduled_crontask_(false),
last_check_compact_time_({0, 0}),
master_ip_(""),
master_port_(0),
repl_state_(PIKA_REPL_NO_CONNECT),
role_(PIKA_ROLE_SINGLE),
leader_protected_mode_(false),
last_meta_sync_timestamp_(0),
first_meta_sync_(false),
loop_partition_state_machine_(false),
force_full_sync_(false),
slowlog_entry_id_(0) {
// Init server ip host
if (!ServerInit()) {
LOG(FATAL) << "ServerInit iotcl error";
}
pthread_rwlockattr_t storage_options_rw_attr;
pthread_rwlockattr_init(&storage_options_rw_attr);
#if !defined(__APPLE__)
pthread_rwlockattr_setkind_np(&storage_options_rw_attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
#endif
pthread_rwlock_init(&storage_options_rw_, &storage_options_rw_attr);
InitStorageOptions();
pthread_rwlockattr_t tables_rw_attr;
pthread_rwlockattr_init(&tables_rw_attr);
#if !defined(__APPLE__)
pthread_rwlockattr_setkind_np(&tables_rw_attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
#endif
pthread_rwlock_init(&tables_rw_, &tables_rw_attr);
// Create thread
worker_num_ = std::min(g_pika_conf->thread_num(), PIKA_MAX_WORKER_THREAD_NUM);
std::set<std::string> ips;
if (g_pika_conf->network_interface().empty()) {
ips.insert("0.0.0.0");
} else {
ips.insert("127.0.0.1");
ips.insert(host_);
}
// We estimate the queue size
int worker_queue_limit = g_pika_conf->maxclients() / worker_num_ + 100;
LOG(INFO) << "Worker queue limit is " << worker_queue_limit;
pika_dispatch_thread_ =
new PikaDispatchThread(ips, port_, worker_num_, 3000, worker_queue_limit, g_pika_conf->max_conn_rbuf_size());
pika_monitor_thread_ = new PikaMonitorThread();
pika_rsync_service_ = new PikaRsyncService(g_pika_conf->db_sync_path(), g_pika_conf->port() + kPortShiftRSync);
pika_pubsub_thread_ = new net::PubSubThread();
pika_auxiliary_thread_ = new PikaAuxiliaryThread();
pika_client_processor_ = new PikaClientProcessor(g_pika_conf->thread_pool_size(), 100000);
pthread_rwlock_init(&state_protector_, nullptr);
pthread_rwlock_init(&slowlog_protector_, nullptr);
}
PikaServer::~PikaServer() {
// DispatchThread will use queue of worker thread,
// so we need to delete dispatch before worker.
pika_client_processor_->Stop();
delete pika_dispatch_thread_;
{
pstd::MutexLock l(&slave_mutex_);
std::vector<SlaveItem>::iterator iter = slaves_.begin();
while (iter != slaves_.end()) {
iter = slaves_.erase(iter);
LOG(INFO) << "Delete slave success";
}
}
delete pika_pubsub_thread_;
delete pika_auxiliary_thread_;
delete pika_rsync_service_;
delete pika_client_processor_;
delete pika_monitor_thread_;
bgsave_thread_.StopThread();
key_scan_thread_.StopThread();
tables_.clear();
pthread_rwlock_destroy(&tables_rw_);
pthread_rwlock_destroy(&state_protector_);
pthread_rwlock_destroy(&slowlog_protector_);
LOG(INFO) << "PikaServer " << pthread_self() << " exit!!!";
}
bool PikaServer::ServerInit() {
std::string network_interface = g_pika_conf->network_interface();
if (network_interface.empty()) {
network_interface = GetDefaultInterface();
}
if (network_interface.empty()) {
LOG(FATAL) << "Can't get Networker Interface";
return false;
}
host_ = GetIpByInterface(network_interface);
if (host_.empty()) {
LOG(FATAL) << "can't get host ip for " << network_interface;
return false;
}
port_ = g_pika_conf->port();
LOG(INFO) << "host: " << host_ << " port: " << port_;
return true;
}
void PikaServer::Start() {
int ret = 0;
// start rsync first, rocksdb opened fd will not appear in this fork
ret = pika_rsync_service_->StartRsync();
if (0 != ret) {
tables_.clear();
LOG(FATAL) << "Start Rsync Error: bind port " + std::to_string(pika_rsync_service_->ListenPort()) + " failed"
<< ", Listen on this port to receive Master FullSync Data";
}
// We Init Table Struct Before Start The following thread
InitTableStruct();
ret = pika_client_processor_->Start();
if (ret != net::kSuccess) {
tables_.clear();
LOG(FATAL) << "Start PikaClientProcessor Error: " << ret
<< (ret == net::kCreateThreadError ? ": create thread error " : ": other error");
}
ret = pika_dispatch_thread_->StartThread();
if (ret != net::kSuccess) {
tables_.clear();
LOG(FATAL) << "Start Dispatch Error: " << ret
<< (ret == net::kBindError ? ": bind port " + std::to_string(port_) + " conflict" : ": other error")
<< ", Listen on this port to handle the connected redis client";
}
ret = pika_pubsub_thread_->StartThread();
if (ret != net::kSuccess) {
tables_.clear();
LOG(FATAL) << "Start Pubsub Error: " << ret << (ret == net::kBindError ? ": bind port conflict" : ": other error");
}
ret = pika_auxiliary_thread_->StartThread();
if (ret != net::kSuccess) {
tables_.clear();
LOG(FATAL) << "Start Auxiliary Thread Error: " << ret
<< (ret == net::kCreateThreadError ? ": create thread error " : ": other error");
}
time(&start_time_s_);
std::string slaveof = g_pika_conf->slaveof();
if (!slaveof.empty()) {
int32_t sep = slaveof.find(":");
std::string master_ip = slaveof.substr(0, sep);
int32_t master_port = std::stoi(slaveof.substr(sep + 1));
if ((master_ip == "127.0.0.1" || master_ip == host_) && master_port == port_) {
LOG(FATAL) << "you will slaveof yourself as the config file, please check";
} else {
SetMaster(master_ip, master_port);
}
}
LOG(INFO) << "Pika Server going to start";
while (!exit_) {
DoTimingTask();
// wake up every 10 second
int try_num = 0;
while (!exit_ && try_num++ < 5) {
sleep(1);
}
}
LOG(INFO) << "Goodbye...";
}
void PikaServer::Exit() { exit_ = true; }
std::string PikaServer::host() { return host_; }
int PikaServer::port() { return port_; }
time_t PikaServer::start_time_s() { return start_time_s_; }
std::string PikaServer::master_ip() {
pstd::RWLock l(&state_protector_, false);
return master_ip_;
}
int PikaServer::master_port() {
pstd::RWLock l(&state_protector_, false);
return master_port_;
}
int PikaServer::role() {
pstd::RWLock l(&state_protector_, false);
return role_;
}
bool PikaServer::leader_protected_mode() {
pstd::RWLock(&state_protector_, false);
return leader_protected_mode_;
}
void PikaServer::CheckLeaderProtectedMode() {
if (!leader_protected_mode()) {
return;
}
if (g_pika_rm->CheckMasterSyncFinished()) {
LOG(INFO) << "Master finish sync and commit binlog";
pstd::RWLock(&state_protector_, true);
leader_protected_mode_ = false;
}
}
bool PikaServer::readonly(const std::string& table_name, const std::string& key) {
pstd::RWLock l(&state_protector_, false);
if ((role_ & PIKA_ROLE_SLAVE) && g_pika_conf->slave_read_only()) {
return true;
}
if (!g_pika_conf->classic_mode()) {
std::shared_ptr<Table> table = GetTable(table_name);
if (table == nullptr) {
// swallow this error will process later
return false;
}
uint32_t index = g_pika_cmd_table_manager->DistributeKey(key, table->PartitionNum());
int role = 0;
Status s = g_pika_rm->CheckPartitionRole(table_name, index, &role);
if (!s.ok()) {
// swallow this error will process later
return false;
}
if (role & PIKA_ROLE_SLAVE) {
return true;
}
}
return false;
}
bool PikaServer::ConsensusCheck(const std::string& table_name, const std::string& key) {
if (g_pika_conf->consensus_level() != 0) {
std::shared_ptr<Table> table = GetTable(table_name);
if (table == nullptr) {
return false;
}
uint32_t index = g_pika_cmd_table_manager->DistributeKey(key, table->PartitionNum());
std::shared_ptr<SyncMasterPartition> master_partition =
g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, index));
if (!master_partition) {
LOG(WARNING) << "Sync Master Partition: " << table_name << ":" << index << ", NotFound";
return false;
}
Status s = master_partition->ConsensusSanityCheck();
if (!s.ok()) {
return false;
} else {
return true;
}
}
return true;
}
int PikaServer::repl_state() {
pstd::RWLock l(&state_protector_, false);
return repl_state_;
}
std::string PikaServer::repl_state_str() {
pstd::RWLock l(&state_protector_, false);
switch (repl_state_) {
case PIKA_REPL_NO_CONNECT:
return "no connect";
case PIKA_REPL_SHOULD_META_SYNC:
return "should meta sync";
case PIKA_REPL_META_SYNC_DONE:
return "meta sync done";
case PIKA_REPL_ERROR:
return "error";
default:
return "";
}
}
bool PikaServer::force_full_sync() { return force_full_sync_; }
void PikaServer::SetForceFullSync(bool v) { force_full_sync_ = v; }
void PikaServer::SetDispatchQueueLimit(int queue_limit) {
rlimit limit;
rlim_t maxfiles = g_pika_conf->maxclients() + PIKA_MIN_RESERVED_FDS;
if (getrlimit(RLIMIT_NOFILE, &limit) == -1) {
LOG(WARNING) << "getrlimit error: " << strerror(errno);
} else if (limit.rlim_cur < maxfiles) {
rlim_t old_limit = limit.rlim_cur;
limit.rlim_cur = maxfiles;
limit.rlim_max = maxfiles;
if (setrlimit(RLIMIT_NOFILE, &limit) != -1) {
LOG(WARNING) << "your 'limit -n ' of " << old_limit
<< " is not enough for Redis to start. pika have successfully reconfig it to " << limit.rlim_cur;
} else {
LOG(FATAL) << "your 'limit -n ' of " << old_limit
<< " is not enough for Redis to start. pika can not reconfig it(" << strerror(errno)
<< "), do it by yourself";
}
}
pika_dispatch_thread_->SetQueueLimit(queue_limit);
}
storage::StorageOptions PikaServer::storage_options() {
pstd::RWLock rwl(&storage_options_rw_, false);
return storage_options_;
}
void PikaServer::InitTableStruct() {
std::string db_path = g_pika_conf->db_path();
std::string log_path = g_pika_conf->log_path();
std::vector<TableStruct> table_structs = g_pika_conf->table_structs();
pstd::RWLock rwl(&tables_rw_, true);
for (const auto& table : table_structs) {
std::string name = table.table_name;
uint32_t num = table.partition_num;
std::shared_ptr<Table> table_ptr = std::make_shared<Table>(name, num, db_path, log_path);
table_ptr->AddPartitions(table.partition_ids);
tables_.emplace(name, table_ptr);
}
}
Status PikaServer::AddTableStruct(std::string table_name, uint32_t num) {
std::shared_ptr<Table> table = g_pika_server->GetTable(table_name);
if (table) {
return Status::Corruption("table already exist");
}
std::string db_path = g_pika_conf->db_path();
std::string log_path = g_pika_conf->log_path();
std::shared_ptr<Table> table_ptr = std::make_shared<Table>(table_name, num, db_path, log_path);
pstd::RWLock rwl(&tables_rw_, true);
tables_.emplace(table_name, table_ptr);
return Status::OK();
}
Status PikaServer::DelTableStruct(std::string table_name) {
std::shared_ptr<Table> table = g_pika_server->GetTable(table_name);
if (!table) {
return Status::Corruption("table not found");
}
if (!table->TableIsEmpty()) {
return Status::Corruption("table have partitions");
}
Status s = table->Leave();
if (!s.ok()) {
return s;
}
tables_.erase(table_name);
return Status::OK();
}
std::shared_ptr<Table> PikaServer::GetTable(const std::string& table_name) {
pstd::RWLock l(&tables_rw_, false);
auto iter = tables_.find(table_name);
return (iter == tables_.end()) ? nullptr : iter->second;
}
std::set<uint32_t> PikaServer::GetTablePartitionIds(const std::string& table_name) {
std::set<uint32_t> empty;
pstd::RWLock l(&tables_rw_, false);
auto iter = tables_.find(table_name);
return (iter == tables_.end()) ? empty : iter->second->GetPartitionIds();
}
bool PikaServer::IsBgSaving() {
pstd::RWLock table_rwl(&tables_rw_, false);
for (const auto& table_item : tables_) {
pstd::RWLock partition_rwl(&table_item.second->partitions_rw_, false);
for (const auto& patition_item : table_item.second->partitions_) {
if (patition_item.second->IsBgSaving()) {
return true;
}
}
}
return false;
}
bool PikaServer::IsKeyScaning() {
pstd::RWLock table_rwl(&tables_rw_, false);
for (const auto& table_item : tables_) {
if (table_item.second->IsKeyScaning()) {
return true;
}
}
return false;
}
bool PikaServer::IsCompacting() {
pstd::RWLock table_rwl(&tables_rw_, false);
for (const auto& table_item : tables_) {
pstd::RWLock partition_rwl(&table_item.second->partitions_rw_, false);
for (const auto& partition_item : table_item.second->partitions_) {
partition_item.second->DbRWLockReader();
std::string task_type = partition_item.second->db()->GetCurrentTaskType();
partition_item.second->DbRWUnLock();
if (strcasecmp(task_type.data(), "no")) {
return true;
}
}
}
return false;
}
bool PikaServer::IsTableExist(const std::string& table_name) { return GetTable(table_name) ? true : false; }
bool PikaServer::IsTablePartitionExist(const std::string& table_name, uint32_t partition_id) {
std::shared_ptr<Table> table_ptr = GetTable(table_name);
if (!table_ptr) {
return false;
} else {
return table_ptr->GetPartitionById(partition_id) ? true : false;
}
}
bool PikaServer::IsCommandSupport(const std::string& command) {
if (g_pika_conf->consensus_level() != 0) {
// dont support multi key command
// used the same list as sharding mode use
bool res = !ConsensusNotSupportCommands.count(command);
if (!res) {
return res;
}
}
if (g_pika_conf->classic_mode()) {
return true;
} else {
std::string cmd = command;
pstd::StringToLower(cmd);
return !ShardingModeNotSupportCommands.count(cmd);
}
}
bool PikaServer::IsTableBinlogIoError(const std::string& table_name) {
std::shared_ptr<Table> table = GetTable(table_name);
return table ? table->IsBinlogIoError() : true;
}
// If no collection of specified tables is given, we execute task in all tables
Status PikaServer::DoSameThingSpecificTable(const TaskType& type, const std::set<std::string>& tables) {
pstd::RWLock rwl(&tables_rw_, false);
for (const auto& table_item : tables_) {
if (!tables.empty() && tables.find(table_item.first) == tables.end()) {
continue;
} else {
switch (type) {
case TaskType::kCompactAll:
table_item.second->Compact(storage::DataType::kAll);
break;
case TaskType::kCompactStrings:
table_item.second->Compact(storage::DataType::kStrings);
break;
case TaskType::kCompactHashes:
table_item.second->Compact(storage::DataType::kHashes);
break;
case TaskType::kCompactSets:
table_item.second->Compact(storage::DataType::kSets);
break;
case TaskType::kCompactZSets:
table_item.second->Compact(storage::DataType::kZSets);
break;
case TaskType::kCompactList:
table_item.second->Compact(storage::DataType::kLists);
break;
case TaskType::kStartKeyScan:
table_item.second->KeyScan();
break;
case TaskType::kStopKeyScan:
table_item.second->StopKeyScan();
break;
case TaskType::kBgSave:
table_item.second->BgSaveTable();
break;
default:
break;
}
}
}
return Status::OK();
}
void PikaServer::PreparePartitionTrySync() {
pstd::RWLock rwl(&tables_rw_, false);
ReplState state = force_full_sync_ ? ReplState::kTryDBSync : ReplState::kTryConnect;
for (const auto& table_item : tables_) {
for (const auto& partition_item : table_item.second->partitions_) {
Status s = g_pika_rm->ActivateSyncSlavePartition(
RmNode(g_pika_server->master_ip(), g_pika_server->master_port(), table_item.second->GetTableName(),
partition_item.second->GetPartitionId()),
state);
if (!s.ok()) {
LOG(WARNING) << s.ToString();
}
}
}
force_full_sync_ = false;
loop_partition_state_machine_ = true;
LOG(INFO) << "Mark try connect finish";
}
void PikaServer::PartitionSetMaxCacheStatisticKeys(uint32_t max_cache_statistic_keys) {
pstd::RWLock rwl(&tables_rw_, false);
for (const auto& table_item : tables_) {
for (const auto& partition_item : table_item.second->partitions_) {
partition_item.second->DbRWLockReader();
partition_item.second->db()->SetMaxCacheStatisticKeys(max_cache_statistic_keys);
partition_item.second->DbRWUnLock();
}
}
}
void PikaServer::PartitionSetSmallCompactionThreshold(uint32_t small_compaction_threshold) {
pstd::RWLock rwl(&tables_rw_, false);
for (const auto& table_item : tables_) {
for (const auto& partition_item : table_item.second->partitions_) {
partition_item.second->DbRWLockReader();
partition_item.second->db()->SetSmallCompactionThreshold(small_compaction_threshold);
partition_item.second->DbRWUnLock();
}
}
}
bool PikaServer::GetTablePartitionBinlogOffset(const std::string& table_name, uint32_t partition_id,
BinlogOffset* const boffset) {
std::shared_ptr<SyncMasterPartition> partition =
g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id));
if (!partition) {
return false;
}
Status s = partition->Logger()->GetProducerStatus(&(boffset->filenum), &(boffset->offset));
if (!s.ok()) {
return false;
}
return true;
}
// Only use in classic mode
std::shared_ptr<Partition> PikaServer::GetPartitionByDbName(const std::string& db_name) {
std::shared_ptr<Table> table = GetTable(db_name);
return table ? table->GetPartitionById(0) : nullptr;
}
std::shared_ptr<Partition> PikaServer::GetTablePartitionById(const std::string& table_name, uint32_t partition_id) {
std::shared_ptr<Table> table = GetTable(table_name);
return table ? table->GetPartitionById(partition_id) : nullptr;
}
std::shared_ptr<Partition> PikaServer::GetTablePartitionByKey(const std::string& table_name, const std::string& key) {
std::shared_ptr<Table> table = GetTable(table_name);
return table ? table->GetPartitionByKey(key) : nullptr;
}
Status PikaServer::DoSameThingEveryPartition(const TaskType& type) {
pstd::RWLock rwl(&tables_rw_, false);
std::shared_ptr<SyncSlavePartition> slave_partition = nullptr;
for (const auto& table_item : tables_) {
for (const auto& partition_item : table_item.second->partitions_) {
switch (type) {
case TaskType::kResetReplState: {
slave_partition = g_pika_rm->GetSyncSlavePartitionByName(
PartitionInfo(table_item.second->GetTableName(), partition_item.second->GetPartitionId()));
if (slave_partition == nullptr) {
LOG(WARNING) << "Slave Partition: " << table_item.second->GetTableName() << ":"
<< partition_item.second->GetPartitionId() << " Not Found";
}
slave_partition->SetReplState(ReplState::kNoConnect);
break;
}
case TaskType::kPurgeLog: {
std::shared_ptr<SyncMasterPartition> partition = g_pika_rm->GetSyncMasterPartitionByName(
PartitionInfo(table_item.second->GetTableName(), partition_item.second->GetPartitionId()));
if (!partition) {
LOG(WARNING) << table_item.second->GetTableName() << partition_item.second->GetPartitionId()
<< " Not Found.";
break;
}
partition->StableLogger()->PurgeStableLogs();
break;
}
case TaskType::kCompactAll:
partition_item.second->Compact(storage::kAll);
break;
default:
break;
}
}
}
return Status::OK();
}
void PikaServer::BecomeMaster() {
pstd::RWLock l(&state_protector_, true);
if ((role_ & PIKA_ROLE_MASTER) == 0 && g_pika_conf->write_binlog() && g_pika_conf->consensus_level() > 0) {
LOG(INFO) << "Become new master, start protect mode to waiting binlog sync and commit";
leader_protected_mode_ = true;
}
role_ |= PIKA_ROLE_MASTER;
}
void PikaServer::DeleteSlave(int fd) {
std::string ip;
int port = -1;
bool is_find = false;
int slave_num = -1;
{
pstd::MutexLock l(&slave_mutex_);
std::vector<SlaveItem>::iterator iter = slaves_.begin();
while (iter != slaves_.end()) {
if (iter->conn_fd == fd) {
ip = iter->ip;
port = iter->port;
is_find = true;
LOG(INFO) << "Delete Slave Success, ip_port: " << iter->ip << ":" << iter->port;
slaves_.erase(iter);
break;
}
iter++;
}
slave_num = slaves_.size();
}
if (is_find) {
g_pika_rm->LostConnection(ip, port);
g_pika_rm->DropItemInWriteQueue(ip, port);
}
if (slave_num == 0) {
pstd::RWLock l(&state_protector_, true);
role_ &= ~PIKA_ROLE_MASTER;
leader_protected_mode_ = false; // explicitly cancel protected mode
}
}
int32_t PikaServer::CountSyncSlaves() {
pstd::MutexLock ldb(&db_sync_protector_);
return db_sync_slaves_.size();
}
int32_t PikaServer::GetShardingSlaveListString(std::string& slave_list_str) {
std::vector<std::string> complete_replica;
g_pika_rm->FindCompleteReplica(&complete_replica);
std::stringstream tmp_stream;
size_t index = 0;
for (auto replica : complete_replica) {
std::string ip;
int port;
if (!pstd::ParseIpPortString(replica, ip, port)) {
continue;
}
tmp_stream << "slave" << index++ << ":ip=" << ip << ",port=" << port << "\r\n";
}
slave_list_str.assign(tmp_stream.str());
return index;
}
int32_t PikaServer::GetSlaveListString(std::string& slave_list_str) {
size_t index = 0;
SlaveState slave_state;
BinlogOffset master_boffset;
BinlogOffset sent_slave_boffset;
BinlogOffset acked_slave_boffset;
std::stringstream tmp_stream;
pstd::MutexLock l(&slave_mutex_);
std::shared_ptr<SyncMasterPartition> master_partition = nullptr;
for (const auto& slave : slaves_) {
tmp_stream << "slave" << index++ << ":ip=" << slave.ip << ",port=" << slave.port << ",conn_fd=" << slave.conn_fd
<< ",lag=";
for (const auto& ts : slave.table_structs) {
for (size_t idx = 0; idx < ts.partition_num; ++idx) {
std::shared_ptr<SyncMasterPartition> partition =
g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(ts.table_name, idx));
if (!partition) {
LOG(WARNING) << "Sync Master Partition: " << ts.table_name << ":" << idx << ", NotFound";
continue;
}
Status s = partition->GetSlaveState(slave.ip, slave.port, &slave_state);
if (s.ok() && slave_state == SlaveState::kSlaveBinlogSync &&
partition->GetSlaveSyncBinlogInfo(slave.ip, slave.port, &sent_slave_boffset, &acked_slave_boffset).ok()) {
Status s = partition->Logger()->GetProducerStatus(&(master_boffset.filenum), &(master_boffset.offset));
if (!s.ok()) {
continue;
} else {
uint64_t lag =
(uint64_t)(master_boffset.filenum - sent_slave_boffset.filenum) * g_pika_conf->binlog_file_size() +
master_boffset.offset - sent_slave_boffset.offset;
tmp_stream << "(" << partition->PartitionName() << ":" << lag << ")";
}
} else {
tmp_stream << "(" << partition->PartitionName() << ":not syncing)";
}
}
}
tmp_stream << "\r\n";
}
slave_list_str.assign(tmp_stream.str());
return index;
}
// Try add Slave, return true if success,
// return false when slave already exist
bool PikaServer::TryAddSlave(const std::string& ip, int64_t port, int fd,
const std::vector<TableStruct>& table_structs) {
std::string ip_port = pstd::IpPortString(ip, port);
pstd::MutexLock l(&slave_mutex_);
std::vector<SlaveItem>::iterator iter = slaves_.begin();
while (iter != slaves_.end()) {
if (iter->ip_port == ip_port) {
LOG(WARNING) << "Slave Already Exist, ip_port: " << ip << ":" << port;
return false;
}
iter++;
}
// Not exist, so add new
LOG(INFO) << "Add New Slave, " << ip << ":" << port;
SlaveItem s;
s.ip_port = ip_port;
s.ip = ip;
s.port = port;
s.conn_fd = fd;
s.stage = SLAVE_ITEM_STAGE_ONE;
s.table_structs = table_structs;
gettimeofday(&s.create_time, nullptr);
slaves_.push_back(s);
return true;
}
void PikaServer::SyncError() {
pstd::RWLock l(&state_protector_, true);
repl_state_ = PIKA_REPL_ERROR;
LOG(WARNING) << "Sync error, set repl_state to PIKA_REPL_ERROR";
}
void PikaServer::RemoveMaster() {
{
pstd::RWLock l(&state_protector_, true);
repl_state_ = PIKA_REPL_NO_CONNECT;
role_ &= ~PIKA_ROLE_SLAVE;
if (master_ip_ != "" && master_port_ != -1) {
g_pika_rm->CloseReplClientConn(master_ip_, master_port_ + kPortShiftReplServer);
g_pika_rm->LostConnection(master_ip_, master_port_);
loop_partition_state_machine_ = false;
UpdateMetaSyncTimestamp();
LOG(INFO) << "Remove Master Success, ip_port: " << master_ip_ << ":" << master_port_;
}
master_ip_ = "";
master_port_ = -1;
DoSameThingEveryPartition(TaskType::kResetReplState);
}
}
bool PikaServer::SetMaster(std::string& master_ip, int master_port) {
if (master_ip == "127.0.0.1") {
master_ip = host_;
}
pstd::RWLock l(&state_protector_, true);
if ((role_ ^ PIKA_ROLE_SLAVE) && repl_state_ == PIKA_REPL_NO_CONNECT) {
master_ip_ = master_ip;
master_port_ = master_port;
role_ |= PIKA_ROLE_SLAVE;
repl_state_ = PIKA_REPL_SHOULD_META_SYNC;
return true;
}
return false;
}
bool PikaServer::ShouldMetaSync() {
pstd::RWLock l(&state_protector_, false);
return repl_state_ == PIKA_REPL_SHOULD_META_SYNC;
}
void PikaServer::FinishMetaSync() {
pstd::RWLock l(&state_protector_, true);
assert(repl_state_ == PIKA_REPL_SHOULD_META_SYNC);
repl_state_ = PIKA_REPL_META_SYNC_DONE;
}
bool PikaServer::MetaSyncDone() {
pstd::RWLock l(&state_protector_, false);
return repl_state_ == PIKA_REPL_META_SYNC_DONE;
}
void PikaServer::ResetMetaSyncStatus() {
pstd::RWLock sp_l(&state_protector_, true);
if (role_ & PIKA_ROLE_SLAVE) {
// not change by slaveof no one, so set repl_state = PIKA_REPL_SHOULD_META_SYNC,
// continue to connect master
repl_state_ = PIKA_REPL_SHOULD_META_SYNC;
loop_partition_state_machine_ = false;
DoSameThingEveryPartition(TaskType::kResetReplState);
}
}
bool PikaServer::AllPartitionConnectSuccess() {
bool all_partition_connect_success = true;
pstd::RWLock rwl(&tables_rw_, false);
std::shared_ptr<SyncSlavePartition> slave_partition = nullptr;
for (const auto& table_item : tables_) {
for (const auto& partition_item : table_item.second->partitions_) {
slave_partition = g_pika_rm->GetSyncSlavePartitionByName(
PartitionInfo(table_item.second->GetTableName(), partition_item.second->GetPartitionId()));
if (slave_partition == nullptr) {
LOG(WARNING) << "Slave Partition: " << table_item.second->GetTableName() << ":"
<< partition_item.second->GetPartitionId() << ", NotFound";
return false;
}
ReplState repl_state = slave_partition->State();
if (repl_state != ReplState::kConnected) {
all_partition_connect_success = false;
break;
}
}
}
return all_partition_connect_success;
}
bool PikaServer::LoopPartitionStateMachine() {
pstd::RWLock sp_l(&state_protector_, false);
return loop_partition_state_machine_;
}
void PikaServer::SetLoopPartitionStateMachine(bool need_loop) {
pstd::RWLock sp_l(&state_protector_, true);
assert(repl_state_ == PIKA_REPL_META_SYNC_DONE);
loop_partition_state_machine_ = need_loop;
}
int PikaServer::GetMetaSyncTimestamp() {
pstd::RWLock sp_l(&state_protector_, false);
return last_meta_sync_timestamp_;
}
void PikaServer::UpdateMetaSyncTimestamp() {
pstd::RWLock sp_l(&state_protector_, true);
last_meta_sync_timestamp_ = time(nullptr);
}
bool PikaServer::IsFirstMetaSync() {
pstd::RWLock sp_l(&state_protector_, true);
return first_meta_sync_;
}
void PikaServer::SetFirstMetaSync(bool v) {
pstd::RWLock sp_l(&state_protector_, true);
first_meta_sync_ = v;
}
void PikaServer::ScheduleClientPool(net::TaskFunc func, void* arg) { pika_client_processor_->SchedulePool(func, arg); }
void PikaServer::ScheduleClientBgThreads(net::TaskFunc func, void* arg, const std::string& hash_str) {
pika_client_processor_->ScheduleBgThreads(func, arg, hash_str);
}
size_t PikaServer::ClientProcessorThreadPoolCurQueueSize() {
if (!pika_client_processor_) {
return 0;
}
return pika_client_processor_->ThreadPoolCurQueueSize();
}
void PikaServer::BGSaveTaskSchedule(net::TaskFunc func, void* arg) {
bgsave_thread_.StartThread();
bgsave_thread_.Schedule(func, arg);
}
void PikaServer::PurgelogsTaskSchedule(net::TaskFunc func, void* arg) {
purge_thread_.StartThread();
purge_thread_.Schedule(func, arg);
}
void PikaServer::PurgeDir(const std::string& path) {
std::string* dir_path = new std::string(path);
PurgeDirTaskSchedule(&DoPurgeDir, static_cast<void*>(dir_path));
}
void PikaServer::PurgeDirTaskSchedule(void (*function)(void*), void* arg) {
purge_thread_.StartThread();
purge_thread_.Schedule(function, arg);
}
void PikaServer::DBSync(const std::string& ip, int port, const std::string& table_name, uint32_t partition_id) {
{
std::string task_index = DbSyncTaskIndex(ip, port, table_name, partition_id);
pstd::MutexLock ml(&db_sync_protector_);
if (db_sync_slaves_.find(task_index) != db_sync_slaves_.end()) {
return;
}
db_sync_slaves_.insert(task_index);
}
// Reuse the bgsave_thread_
// Since we expect BgSave and DBSync execute serially
bgsave_thread_.StartThread();
DBSyncArg* arg = new DBSyncArg(this, ip, port, table_name, partition_id);
bgsave_thread_.Schedule(&DoDBSync, reinterpret_cast<void*>(arg));
}
void PikaServer::TryDBSync(const std::string& ip, int port, const std::string& table_name, uint32_t partition_id,
int32_t top) {
std::shared_ptr<Partition> partition = GetTablePartitionById(table_name, partition_id);
if (!partition) {
LOG(WARNING) << "can not find Partition whose id is " << partition_id << " in table " << table_name
<< ", TryDBSync Failed";
return;
}
std::shared_ptr<SyncMasterPartition> sync_partition =
g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id));
if (!sync_partition) {
LOG(WARNING) << "can not find Partition whose id is " << partition_id << " in table " << table_name
<< ", TryDBSync Failed";
return;
}
BgSaveInfo bgsave_info = partition->bgsave_info();
std::string logger_filename = sync_partition->Logger()->filename();
if (pstd::IsDir(bgsave_info.path) != 0 ||
!pstd::FileExists(NewFileName(logger_filename, bgsave_info.offset.b_offset.filenum)) ||
top - bgsave_info.offset.b_offset.filenum > kDBSyncMaxGap) {
// Need Bgsave first
partition->BgSavePartition();
}
DBSync(ip, port, table_name, partition_id);
}
void PikaServer::DbSyncSendFile(const std::string& ip, int port, const std::string& table_name, uint32_t partition_id) {
std::shared_ptr<Partition> partition = GetTablePartitionById(table_name, partition_id);
if (!partition) {
LOG(WARNING) << "can not find Partition whose id is " << partition_id << " in table " << table_name
<< ", DbSync send file Failed";
return;
}
BgSaveInfo bgsave_info = partition->bgsave_info();
std::string bg_path = bgsave_info.path;
uint32_t binlog_filenum = bgsave_info.offset.b_offset.filenum;
uint64_t binlog_offset = bgsave_info.offset.b_offset.offset;
uint32_t term = bgsave_info.offset.l_offset.term;
uint64_t index = bgsave_info.offset.l_offset.index;