-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathpika_server.cc
1923 lines (1685 loc) · 67.7 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 <arpa/inet.h>
#include <netinet/in.h>
#include <sys/resource.h>
#include <algorithm>
#include <ctime>
#include <fstream>
#include <memory>
#include <utility>
#include "net/include/net_cli.h"
#include "net/include/net_interfaces.h"
#include "net/include/net_stats.h"
#include "net/include/redis_cli.h"
#include "pstd/include/env.h"
#include "pstd/include/rsync.h"
#include "pstd/include/pika_codis_slot.h"
#include "include/pika_cmd_table_manager.h"
#include "include/pika_dispatch_thread.h"
#include "include/pika_instant.h"
#include "include/pika_monotonic_time.h"
#include "include/pika_rm.h"
#include "include/pika_server.h"
using pstd::Status;
extern PikaServer* g_pika_server;
extern std::unique_ptr<PikaReplicaManager> g_pika_rm;
extern std::unique_ptr<PikaCmdTableManager> g_pika_cmd_table_manager;
extern std::unique_ptr<net::NetworkStatistic> g_network_statistic;
// QUEUE_SIZE_THRESHOLD_PERCENTAGE is used to represent a percentage value and should be within the range of 0 to 100.
const size_t QUEUE_SIZE_THRESHOLD_PERCENTAGE = 75;
void DoPurgeDir(void* arg) {
std::unique_ptr<std::string> path(static_cast<std::string*>(arg));
LOG(INFO) << "Delete dir: " << *path << " start";
pstd::DeleteDir(*path);
LOG(INFO) << "Delete dir: " << *path << " done";
}
PikaServer::PikaServer()
: exit_(false),
slow_cmd_thread_pool_flag_(g_pika_conf->slow_cmd_pool()),
last_check_compact_time_({0, 0}),
last_check_resume_time_({0, 0}),
repl_state_(PIKA_REPL_NO_CONNECT),
role_(PIKA_ROLE_SINGLE) {
// Init server ip host
if (!ServerInit()) {
LOG(FATAL) << "ServerInit iotcl error";
}
InitStorageOptions();
// 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;
for_each(ips.begin(), ips.end(), [](auto& ip) { LOG(WARNING) << ip; });
pika_dispatch_thread_ = std::make_unique<PikaDispatchThread>(ips, port_, worker_num_, 3000, worker_queue_limit,
g_pika_conf->max_conn_rbuf_size());
pika_rsync_service_ =
std::make_unique<PikaRsyncService>(g_pika_conf->db_sync_path(), g_pika_conf->port() + kPortShiftRSync);
// TODO: remove pika_rsync_service_,reuse pika_rsync_service_ port
rsync_server_ = std::make_unique<rsync::RsyncServer>(ips, port_ + kPortShiftRsync2);
pika_pubsub_thread_ = std::make_unique<net::PubSubThread>();
pika_auxiliary_thread_ = std::make_unique<PikaAuxiliaryThread>();
pika_migrate_ = std::make_unique<PikaMigrate>();
pika_migrate_thread_ = std::make_unique<PikaMigrateThread>();
pika_client_processor_ = std::make_unique<PikaClientProcessor>(g_pika_conf->thread_pool_size(), 100000);
pika_slow_cmd_thread_pool_ = std::make_unique<net::ThreadPool>(g_pika_conf->slow_cmd_thread_pool_size(), 100000);
pika_admin_cmd_thread_pool_ = std::make_unique<net::ThreadPool>(g_pika_conf->admin_thread_pool_size(), 100000);
instant_ = std::make_unique<Instant>();
exit_mutex_.lock();
int64_t lastsave = GetLastSaveTime(g_pika_conf->bgsave_path());
UpdateLastSave(lastsave);
// init role
std::string slaveof = g_pika_conf->slaveof();
if (!slaveof.empty()) {
auto sep = static_cast<int32_t>(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);
}
}
acl_ = std::make_unique<::Acl>();
SetSlowCmdThreadPoolFlag(g_pika_conf->slow_cmd_pool());
bgsave_thread_.set_thread_name("PikaServer::bgsave_thread_");
purge_thread_.set_thread_name("PikaServer::purge_thread_");
bgslots_cleanup_thread_.set_thread_name("PikaServer::bgslots_cleanup_thread_");
common_bg_thread_.set_thread_name("PikaServer::common_bg_thread_");
key_scan_thread_.set_thread_name("PikaServer::key_scan_thread_");
}
PikaServer::~PikaServer() {
rsync_server_->Stop();
// DispatchThread will use queue of worker thread
// so we need to Stop dispatch before worker.
pika_dispatch_thread_->StopThread();
pika_client_processor_->Stop();
pika_slow_cmd_thread_pool_->stop_thread_pool();
pika_admin_cmd_thread_pool_->stop_thread_pool();
{
std::lock_guard l(slave_mutex_);
auto iter = slaves_.begin();
while (iter != slaves_.end()) {
iter = slaves_.erase(iter);
LOG(INFO) << "Delete slave success";
}
}
bgsave_thread_.StopThread();
key_scan_thread_.StopThread();
pika_migrate_thread_->StopThread();
dbs_.clear();
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
// TODO: temporarily disable rsync server
/*
ret = pika_rsync_service_->StartRsync();
if (0 != ret) {
dbs_.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";
}
*/
ret = pika_client_processor_->Start();
if (ret != net::kSuccess) {
dbs_.clear();
LOG(FATAL) << "Start PikaClientProcessor Error: " << ret
<< (ret == net::kCreateThreadError ? ": create thread error " : ": other error");
}
ret = pika_slow_cmd_thread_pool_->start_thread_pool();
if (ret != net::kSuccess) {
dbs_.clear();
LOG(FATAL) << "Start PikaLowLevelThreadPool Error: " << ret
<< (ret == net::kCreateThreadError ? ": create thread error " : ": other error");
}
ret = pika_admin_cmd_thread_pool_->start_thread_pool();
if (ret != net::kSuccess) {
dbs_.clear();
LOG(FATAL) << "Start PikaAdminThreadPool Error: " << ret
<< (ret == net::kCreateThreadError ? ": create thread error " : ": other error");
}
ret = pika_dispatch_thread_->StartThread();
if (ret != net::kSuccess) {
dbs_.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";
}
pika_dispatch_thread_->SetLogNetActivities(g_pika_conf->log_net_activities());
ret = pika_pubsub_thread_->StartThread();
if (ret != net::kSuccess) {
dbs_.clear();
LOG(FATAL) << "Start Pubsub Error: " << ret << (ret == net::kBindError ? ": bind port conflict" : ": other error");
}
ret = pika_auxiliary_thread_->StartThread();
if (ret != net::kSuccess) {
dbs_.clear();
LOG(FATAL) << "Start Auxiliary Thread Error: " << ret
<< (ret == net::kCreateThreadError ? ": create thread error " : ": other error");
}
time(&start_time_s_);
LOG(INFO) << "Pika Server going to start";
rsync_server_->Start();
while (!exit_) {
DoTimingTask();
// wake up every 5 seconds
if (!exit_ && exit_mutex_.try_lock_for(std::chrono::seconds(5))) {
exit_mutex_.unlock();
}
}
LOG(INFO) << "Goodbye...";
}
void PikaServer::SetSlowCmdThreadPoolFlag(bool flag) {
slow_cmd_thread_pool_flag_ = flag;
int ret = 0;
if (flag) {
ret = pika_slow_cmd_thread_pool_->start_thread_pool();
if (ret != net::kSuccess) {
dbs_.clear();
LOG(ERROR) << "Start PikaLowLevelThreadPool Error: " << ret
<< (ret == net::kCreateThreadError ? ": create thread error " : ": other error");
}
} else {
while (SlowCmdThreadPoolCurQueueSize() != 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
pika_slow_cmd_thread_pool_->stop_thread_pool();
}
}
void PikaServer::Exit() {
g_pika_server->DisableCompact();
exit_mutex_.unlock();
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() {
std::shared_lock l(state_protector_);
return master_ip_;
}
int PikaServer::master_port() {
std::shared_lock l(state_protector_);
return master_port_;
}
int PikaServer::role() {
std::shared_lock l(state_protector_);
return role_;
}
bool PikaServer::leader_protected_mode() {
std::shared_lock l(state_protector_);
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";
std::lock_guard l(state_protector_);
leader_protected_mode_ = false;
}
}
bool PikaServer::readonly(const std::string& db_name) {
std::shared_lock l(state_protector_);
return ((role_ & PIKA_ROLE_SLAVE) != 0) && g_pika_conf->slave_read_only();
}
int PikaServer::repl_state() {
std::shared_lock l(state_protector_);
return repl_state_;
}
std::string PikaServer::repl_state_str() {
std::shared_lock l(state_protector_);
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() {
std::shared_lock rwl(storage_options_rw_);
return storage_options_;
}
void PikaServer::InitDBStruct() {
std::string db_path = g_pika_conf->db_path();
std::string log_path = g_pika_conf->log_path();
std::vector<DBStruct> db_structs = g_pika_conf->db_structs();
std::lock_guard rwl(dbs_rw_);
for (const auto& db : db_structs) {
std::string name = db.db_name;
std::shared_ptr<DB> db_ptr = std::make_shared<DB>(name, db_path, log_path);
db_ptr->Init();
dbs_.emplace(name, db_ptr);
}
}
std::shared_ptr<DB> PikaServer::GetDB(const std::string& db_name) {
std::shared_lock l(dbs_rw_);
auto iter = dbs_.find(db_name);
return (iter == dbs_.end()) ? nullptr : iter->second;
}
bool PikaServer::IsBgSaving() {
std::shared_lock l(dbs_rw_);
for (const auto& db_item : dbs_) {
if (db_item.second->IsBgSaving()) {
return true;
}
}
return false;
}
bool PikaServer::IsKeyScaning() {
std::shared_lock l(dbs_rw_);
for (const auto& db_item : dbs_) {
if (db_item.second->IsKeyScaning()) {
return true;
}
}
return false;
}
bool PikaServer::IsCompacting() {
std::shared_lock db_rwl(dbs_rw_);
for (const auto& db_item : dbs_) {
db_item.second->DBLockShared();
std::string task_type = db_item.second->storage()->GetCurrentTaskType();
db_item.second->DBUnlockShared();
if (strcasecmp(task_type.data(), "no") != 0) {
return true;
}
}
return false;
}
bool PikaServer::IsDBExist(const std::string& db_name) { return static_cast<bool>(GetDB(db_name)); }
bool PikaServer::IsDBBinlogIoError(const std::string& db_name) {
std::shared_ptr<DB> db = GetDB(db_name);
return db ? db->IsBinlogIoError() : true;
}
std::set<std::string> PikaServer::GetAllDBName() {
std::set<std::string> dbs;
std::shared_lock l(dbs_rw_);
for (const auto& db_item : dbs_) {
dbs.insert(db_item.first);
}
return dbs;
}
Status PikaServer::DoSameThingSpecificDB(const std::set<std::string>& dbs, const TaskArg& arg) {
std::shared_lock rwl(dbs_rw_);
for (const auto& db_item : dbs_) {
if (dbs.find(db_item.first) == dbs.end()) {
continue;
}
switch (arg.type) {
case TaskType::kCompactAll:
db_item.second->Compact(storage::DataType::kAll);
break;
case TaskType::kStartKeyScan:
db_item.second->KeyScan();
break;
case TaskType::kStopKeyScan:
db_item.second->StopKeyScan();
break;
case TaskType::kBgSave:
db_item.second->BgSaveDB();
break;
case TaskType::kCompactRangeAll:
db_item.second->CompactRange(storage::DataType::kAll, arg.argv[0], arg.argv[1]);
break;
default:
break;
}
}
return Status::OK();
}
void PikaServer::PrepareDBTrySync() {
std::shared_lock rwl(dbs_rw_);
ReplState state = force_full_sync_ ? ReplState::kTryDBSync : ReplState::kTryConnect;
for (const auto& db_item : dbs_) {
Status s = g_pika_rm->ActivateSyncSlaveDB(
RmNode(g_pika_server->master_ip(), g_pika_server->master_port(), db_item.second->GetDBName()), state);
if (!s.ok()) {
LOG(WARNING) << s.ToString();
}
}
force_full_sync_ = false;
LOG(INFO) << "Mark try connect finish";
}
void PikaServer::DBSetMaxCacheStatisticKeys(uint32_t max_cache_statistic_keys) {
std::shared_lock rwl(dbs_rw_);
for (const auto& db_item : dbs_) {
db_item.second->DBLockShared();
db_item.second->storage()->SetMaxCacheStatisticKeys(max_cache_statistic_keys);
db_item.second->DBUnlockShared();
}
}
void PikaServer::DBSetSmallCompactionThreshold(uint32_t small_compaction_threshold) {
std::shared_lock rwl(dbs_rw_);
for (const auto& db_item : dbs_) {
db_item.second->DBLockShared();
db_item.second->storage()->SetSmallCompactionThreshold(small_compaction_threshold);
db_item.second->DBUnlockShared();
}
}
void PikaServer::DBSetSmallCompactionDurationThreshold(uint32_t small_compaction_duration_threshold) {
std::shared_lock rwl(dbs_rw_);
for (const auto& db_item : dbs_) {
db_item.second->DBLockShared();
db_item.second->storage()->SetSmallCompactionDurationThreshold(small_compaction_duration_threshold);
db_item.second->DBUnlockShared();
}
}
bool PikaServer::GetDBBinlogOffset(const std::string& db_name, BinlogOffset* const boffset) {
std::shared_ptr<SyncMasterDB> db = g_pika_rm->GetSyncMasterDBByName(DBInfo(db_name));
if (!db) {
return false;
}
Status s = db->Logger()->GetProducerStatus(&(boffset->filenum), &(boffset->offset));
return s.ok();
}
Status PikaServer::DoSameThingEveryDB(const TaskType& type) {
std::shared_lock rwl(dbs_rw_);
std::shared_ptr<SyncSlaveDB> slave_db = nullptr;
for (const auto& db_item : dbs_) {
switch (type) {
case TaskType::kResetReplState: {
slave_db = g_pika_rm->GetSyncSlaveDBByName(DBInfo(db_item.second->GetDBName()));
if (!slave_db) {
LOG(WARNING) << "Slave DB: " << db_item.second->GetDBName() << ":"
<< " Not Found";
}
slave_db->SetReplState(ReplState::kNoConnect);
break;
}
case TaskType::kPurgeLog: {
std::shared_ptr<SyncMasterDB> db = g_pika_rm->GetSyncMasterDBByName(
DBInfo(db_item.second->GetDBName()));
if (!db) {
LOG(WARNING) << "DB: " << db_item.second->GetDBName() << ":"
<< " Not Found.";
break;
}
db->StableLogger()->PurgeStableLogs();
break;
}
case TaskType::kCompactAll:
db_item.second->Compact(storage::DataType::kAll);
break;
case TaskType::kCompactOldestOrBestDeleteRatioSst:
db_item.second->LongestNotCompactionSstCompact(storage::DataType::kAll);
break;
default:
break;
}
}
return Status::OK();
}
void PikaServer::BecomeMaster() {
std::lock_guard l(state_protector_);
role_ |= PIKA_ROLE_MASTER;
}
void PikaServer::DeleteSlave(int fd) {
std::string ip;
int port = -1;
bool is_find = false;
int slave_num = -1;
{
std::lock_guard l(slave_mutex_);
auto 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 = static_cast<int32_t>(slaves_.size());
}
if (is_find) {
g_pika_rm->LostConnection(ip, port);
g_pika_rm->DropItemInWriteQueue(ip, port);
}
if (slave_num == 0) {
std::lock_guard l(state_protector_);
role_ &= ~PIKA_ROLE_MASTER;
leader_protected_mode_ = false; // explicitly cancel protected mode
}
}
int32_t PikaServer::CountSyncSlaves() {
int32_t count = 0;
std::lock_guard l(slave_mutex_);
for (const auto& slave : slaves_) {
for (const auto& ts : slave.db_structs) {
SlaveState slave_state;
std::shared_ptr<SyncMasterDB> db = g_pika_rm->GetSyncMasterDBByName(DBInfo(ts.db_name));
if (!db) {
continue;
}
Status s = db->GetSlaveState(slave.ip, slave.port, &slave_state);
if (s.ok() && slave_state == SlaveState::kSlaveDbSync) {
count++;
}
}
}
return count;
}
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;
std::lock_guard l(slave_mutex_);
std::shared_ptr<SyncMasterDB> master_db = 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.db_structs) {
std::shared_ptr<SyncMasterDB> db = g_pika_rm->GetSyncMasterDBByName(DBInfo(ts.db_name));
if (!db) {
LOG(WARNING) << "Sync Master DB: " << ts.db_name << ", NotFound";
continue;
}
Status s = db->GetSlaveState(slave.ip, slave.port, &slave_state);
if (s.ok() && slave_state == SlaveState::kSlaveBinlogSync &&
db->GetSlaveSyncBinlogInfo(slave.ip, slave.port, &sent_slave_boffset, &acked_slave_boffset).ok()) {
Status s = db->Logger()->GetProducerStatus(&(master_boffset.filenum), &(master_boffset.offset));
if (!s.ok()) {
continue;
} else {
uint64_t lag =
static_cast<uint64_t>((master_boffset.filenum - sent_slave_boffset.filenum)) * g_pika_conf->binlog_file_size() +
master_boffset.offset - sent_slave_boffset.offset;
tmp_stream << "(" << db->DBName() << ":" << lag << ")";
}
} else if (s.ok() && slave_state == SlaveState::kSlaveDbSync) {
tmp_stream << "(" << db->DBName() << ":full syncing)";
} else {
tmp_stream << "(" << db->DBName() << ":not syncing)";
}
}
tmp_stream << "\r\n";
}
slave_list_str.assign(tmp_stream.str());
return static_cast<int32_t>(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<DBStruct>& db_structs) {
std::string ip_port = pstd::IpPortString(ip, static_cast<int32_t>(port));
std::lock_guard l(slave_mutex_);
auto 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 = static_cast<int32_t>(port);
s.conn_fd = fd;
s.stage = SLAVE_ITEM_STAGE_ONE;
s.db_structs = db_structs;
gettimeofday(&s.create_time, nullptr);
slaves_.push_back(s);
return true;
}
void PikaServer::SyncError() {
std::lock_guard l(state_protector_);
repl_state_ = PIKA_REPL_ERROR;
LOG(WARNING) << "Sync error, set repl_state to PIKA_REPL_ERROR";
}
void PikaServer::RemoveMaster() {
{
std::lock_guard l(state_protector_);
repl_state_ = PIKA_REPL_NO_CONNECT;
role_ &= ~PIKA_ROLE_SLAVE;
if (!master_ip_.empty() && master_port_ != -1) {
g_pika_rm->CloseReplClientConn(master_ip_, master_port_ + kPortShiftReplServer);
g_pika_rm->DeactivateSyncSlaveDB(master_ip_, master_port_);
UpdateMetaSyncTimestampWithoutLock();
LOG(INFO) << "Remove Master Success, ip_port: " << master_ip_ << ":" << master_port_;
}
master_ip_ = "";
master_port_ = -1;
DoSameThingEveryDB(TaskType::kResetReplState);
}
}
bool PikaServer::SetMaster(std::string& master_ip, int master_port) {
if (master_ip == "127.0.0.1") {
master_ip = host_;
}
std::lock_guard l(state_protector_);
if (((role_ ^ PIKA_ROLE_SLAVE) != 0) && 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() {
std::shared_lock l(state_protector_);
return repl_state_ == PIKA_REPL_SHOULD_META_SYNC;
}
void PikaServer::FinishMetaSync() {
std::lock_guard l(state_protector_);
assert(repl_state_ == PIKA_REPL_SHOULD_META_SYNC);
repl_state_ = PIKA_REPL_META_SYNC_DONE;
}
bool PikaServer::MetaSyncDone() {
std::shared_lock l(state_protector_);
return repl_state_ == PIKA_REPL_META_SYNC_DONE;
}
void PikaServer::ResetMetaSyncStatus() {
std::lock_guard sp_l(state_protector_);
if ((role_ & PIKA_ROLE_SLAVE) != 0) {
// 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;
DoSameThingEveryDB(TaskType::kResetReplState);
}
}
int PikaServer::GetMetaSyncTimestamp() {
std::shared_lock sp_l(state_protector_);
return last_meta_sync_timestamp_;
}
void PikaServer::UpdateMetaSyncTimestamp() {
std::lock_guard sp_l(state_protector_);
last_meta_sync_timestamp_ = static_cast<int32_t>(time(nullptr));
}
void PikaServer::UpdateMetaSyncTimestampWithoutLock() {
last_meta_sync_timestamp_ = static_cast<int32_t>(time(nullptr));
}
bool PikaServer::IsFirstMetaSync() {
std::shared_lock sp_l(state_protector_);
return first_meta_sync_;
}
void PikaServer::SetFirstMetaSync(bool v) {
std::lock_guard sp_l(state_protector_);
first_meta_sync_ = v;
}
void PikaServer::ScheduleClientPool(net::TaskFunc func, void* arg, bool is_slow_cmd, bool is_admin_cmd) {
if (is_slow_cmd && g_pika_conf->slow_cmd_pool()) {
pika_slow_cmd_thread_pool_->Schedule(func, arg);
return;
}
if (is_admin_cmd) {
pika_admin_cmd_thread_pool_->Schedule(func, arg);
return;
}
pika_client_processor_->SchedulePool(func, arg);
}
size_t PikaServer::ClientProcessorThreadPoolCurQueueSize() {
if (!pika_client_processor_) {
return 0;
}
return pika_client_processor_->ThreadPoolCurQueueSize();
}
size_t PikaServer::ClientProcessorThreadPoolMaxQueueSize() {
if (!pika_client_processor_) {
return 0;
}
return pika_client_processor_->ThreadPoolMaxQueueSize();
}
size_t PikaServer::SlowCmdThreadPoolCurQueueSize() {
if (!pika_slow_cmd_thread_pool_) {
return 0;
}
size_t cur_size = 0;
pika_slow_cmd_thread_pool_->cur_queue_size(&cur_size);
return cur_size;
}
size_t PikaServer::SlowCmdThreadPoolMaxQueueSize() {
if (!pika_slow_cmd_thread_pool_) {
return 0;
}
return pika_slow_cmd_thread_pool_->max_queue_size();
}
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) {
auto 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);
}
pstd::Status PikaServer::GetDumpUUID(const std::string& db_name, std::string* snapshot_uuid) {
std::shared_ptr<DB> db = GetDB(db_name);
if (!db) {
LOG(WARNING) << "cannot find db for db_name " << db_name;
return pstd::Status::NotFound("db no found");
}
db->GetBgSaveUUID(snapshot_uuid);
return pstd::Status::OK();
}
pstd::Status PikaServer::GetDumpMeta(const std::string& db_name, std::vector<std::string>* fileNames, std::string* snapshot_uuid) {
std::shared_ptr<DB> db = GetDB(db_name);
if (!db) {
LOG(WARNING) << "cannot find db for db_name " << db_name;
return pstd::Status::NotFound("db no found");
}
db->GetBgSaveMetaData(fileNames, snapshot_uuid);
return pstd::Status::OK();
}
void PikaServer::TryDBSync(const std::string& ip, int port, const std::string& db_name,
int32_t top) {
std::shared_ptr<DB> db = GetDB(db_name);
if (!db) {
LOG(WARNING) << "can not find DB : " << db_name
<< ", TryDBSync Failed";
return;
}
std::shared_ptr<SyncMasterDB> sync_db =
g_pika_rm->GetSyncMasterDBByName(DBInfo(db_name));
if (!sync_db) {
LOG(WARNING) << "can not find DB: " << db_name
<< ", TryDBSync Failed";
return;
}
BgSaveInfo bgsave_info = db->bgsave_info();
std::string logger_filename = sync_db->Logger()->filename();
if (pstd::IsDir(bgsave_info.path) != 0 ||
!pstd::FileExists(NewFileName(logger_filename, bgsave_info.offset.b_offset.filenum)) ||
static_cast<int64_t>(top) - static_cast<int64_t>(bgsave_info.offset.b_offset.filenum) >
static_cast<int64_t>(kDBSyncMaxGap)) {
// Need Bgsave first
db->BgSaveDB();
}
}
void PikaServer::KeyScanTaskSchedule(net::TaskFunc func, void* arg) {
key_scan_thread_.StartThread();
key_scan_thread_.Schedule(func, arg);
}
void PikaServer::ClientKillAll() {
pika_dispatch_thread_->ClientKillAll();
pika_pubsub_thread_->NotifyCloseAllConns();
}
void PikaServer::ClientKillPubSub() { pika_pubsub_thread_->NotifyCloseAllConns();
}
void PikaServer::ClientKillAllNormal() {
pika_dispatch_thread_->ClientKillAll();
}
int PikaServer::ClientKill(const std::string& ip_port) {
if (pika_dispatch_thread_->ClientKill(ip_port)) {
return 1;
}
return 0;
}
int64_t PikaServer::ClientList(std::vector<ClientInfo>* clients) {
int64_t clients_num = 0;
clients_num += static_cast<int64_t>(pika_dispatch_thread_->ThreadClientList(clients));
return clients_num;
}
bool PikaServer::HasMonitorClients() const {
std::unique_lock lock(monitor_mutex_protector_);
return !pika_monitor_clients_.empty();
}
bool PikaServer::ClientIsMonitor(const std::shared_ptr<PikaClientConn>& client_ptr) const {
std::unique_lock lock(monitor_mutex_protector_);
return pika_monitor_clients_.count(client_ptr) != 0;
}
void PikaServer::AddMonitorMessage(const std::string& monitor_message) {
const std::string msg = "+" + monitor_message + "\r\n";
std::vector<std::shared_ptr<PikaClientConn>> clients;
std::unique_lock lock(monitor_mutex_protector_);
clients.reserve(pika_monitor_clients_.size());
for (auto it = pika_monitor_clients_.begin(); it != pika_monitor_clients_.end();) {
auto cli = (*it).lock();
if (cli) {
clients.push_back(std::move(cli));
++it;
} else {
it = pika_monitor_clients_.erase(it);
}
}
for (const auto& cli : clients) {
cli->WriteResp(msg);
cli->SendReply();
}
lock.unlock(); // SendReply without lock
}
void PikaServer::AddMonitorClient(const std::shared_ptr<PikaClientConn>& client_ptr) {
if (client_ptr) {
std::unique_lock lock(monitor_mutex_protector_);
pika_monitor_clients_.insert(client_ptr);
}
}
void PikaServer::SlowlogTrim() {
std::lock_guard l(slowlog_protector_);
while (slowlog_list_.size() > static_cast<uint32_t>(g_pika_conf->slowlog_max_len())) {
slowlog_list_.pop_back();
}
}
void PikaServer::SlowlogReset() {
std::lock_guard l(slowlog_protector_);
slowlog_list_.clear();
}
uint32_t PikaServer::SlowlogLen() {
std::shared_lock l(slowlog_protector_);
return slowlog_list_.size();
}
void PikaServer::SlowlogObtain(int64_t number, std::vector<SlowlogEntry>* slowlogs) {
std::shared_lock l(slowlog_protector_);
slowlogs->clear();
auto iter = slowlog_list_.begin();
while (((number--) != 0) && iter != slowlog_list_.end()) {
slowlogs->push_back(*iter);
iter++;
}
}
void PikaServer::SlowlogPushEntry(const PikaCmdArgsType& argv, int64_t time, int64_t duration) {
SlowlogEntry entry;
uint32_t slargc = (argv.size() < SLOWLOG_ENTRY_MAX_ARGC) ? argv.size() : SLOWLOG_ENTRY_MAX_ARGC;
for (uint32_t idx = 0; idx < slargc; ++idx) {
if (slargc != argv.size() && idx == slargc - 1) {
char buffer[32];
snprintf(buffer, sizeof(buffer), "... (%lu more arguments)", argv.size() - slargc + 1);
entry.argv.push_back(std::string(buffer));
} else {
if (argv[idx].size() > SLOWLOG_ENTRY_MAX_STRING) {
char buffer[32];
snprintf(buffer, sizeof(buffer), "... (%lu more bytes)", argv[idx].size() - SLOWLOG_ENTRY_MAX_STRING);
std::string suffix(buffer);
std::string brief = argv[idx].substr(0, SLOWLOG_ENTRY_MAX_STRING);
entry.argv.push_back(brief + suffix);
} else {
entry.argv.push_back(argv[idx]);
}
}
}
{
std::lock_guard lock(slowlog_protector_);
entry.id = static_cast<int64_t>(slowlog_entry_id_++);
entry.start_time = time;
entry.duration = duration;
slowlog_list_.push_front(entry);
slowlog_counter_++;
}
SlowlogTrim();
}
uint64_t PikaServer::SlowlogCount() {
std::shared_lock l(slowlog_protector_);
return slowlog_counter_;
}
void PikaServer::ResetStat() {
statistic_.server_stat.accumulative_connections.store(0);
statistic_.server_stat.qps.querynum.store(0);
statistic_.server_stat.qps.last_querynum.store(0);
}
uint64_t PikaServer::ServerQueryNum() { return statistic_.server_stat.qps.querynum.load(); }