forked from OpenAtomFoundation/pika
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpika_server.cc
1753 lines (1545 loc) · 53.9 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 <fstream>
#include <glog/logging.h>
#include <assert.h>
#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <sstream>
#include <iostream>
#include <iterator>
#include <ctime>
#include <algorithm>
#include <sys/resource.h>
#include "slash/include/env.h"
#include "slash/include/rsync.h"
#include "slash/include/slash_string.h"
#include "pink/include/bg_thread.h"
#include "include/pika_server.h"
#include "include/pika_conf.h"
#include "include/pika_dispatch_thread.h"
extern PikaConf *g_pika_conf;
PikaServer::PikaServer() :
ping_thread_(NULL),
exit_(false),
binlog_io_error_(false),
have_scheduled_crontask_(false),
last_check_compact_time_({0, 0}),
sid_(0),
master_ip_(""),
master_connection_(0),
master_port_(0),
repl_state_(PIKA_REPL_NO_CONNECT),
role_(PIKA_ROLE_SINGLE),
force_full_sync_(false),
double_master_sid_(0),
double_master_mode_(false),
bgsave_engine_(NULL),
purging_(false),
binlogbg_exit_(false),
binlogbg_cond_(&binlogbg_mutex_),
binlogbg_serial_(0),
slowlog_entry_id_(0) {
pthread_rwlockattr_t attr;
pthread_rwlockattr_init(&attr);
pthread_rwlockattr_setkind_np(&attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
pthread_rwlock_init(&rwlock_, &attr);
//Init server ip host
if (!ServerInit()) {
LOG(FATAL) << "ServerInit iotcl error";
}
//Create blackwidow handle
blackwidow::BlackwidowOptions bw_option;
RocksdbOptionInit(&bw_option);
std::string db_path = g_pika_conf->db_path();
LOG(INFO) << "Prepare Blackwidow DB...";
db_ = std::shared_ptr<blackwidow::BlackWidow>(new blackwidow::BlackWidow());
rocksdb::Status s = db_->Open(bw_option, db_path);
assert(db_);
assert(s.ok());
LOG(INFO) << "DB Success";
// 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);
pika_binlog_receiver_thread_ = new PikaBinlogReceiverThread(ips, port_ + 1000, 1000);
pika_heartbeat_thread_ = new PikaHeartbeatThread(ips, port_ + 2000, 1000);
pika_trysync_thread_ = new PikaTrysyncThread();
monitor_thread_ = new PikaMonitorThread();
pika_pubsub_thread_ = new pink::PubSubThread();
//for (int j = 0; j < g_pika_conf->binlogbg_thread_num; j++) {
for (int j = 0; j < g_pika_conf->sync_thread_num(); j++) {
binlogbg_workers_.push_back(new BinlogBGWorker(g_pika_conf->sync_buffer_size()));
}
pthread_rwlock_init(&state_protector_, NULL);
logger_ = new Binlog(g_pika_conf->log_path(), g_pika_conf->binlog_file_size());
uint64_t double_recv_offset;
uint32_t double_recv_num;
logger_->GetDoubleRecvInfo(&double_recv_num, &double_recv_offset);
LOG(INFO) << "double recv info: filenum " << double_recv_num << " offset " << double_recv_offset;
pthread_rwlock_init(&slowlog_protector_, NULL);
}
PikaServer::~PikaServer() {
delete bgsave_engine_;
// DispatchThread will use queue of worker thread,
// so we need to delete dispatch before worker.
delete pika_dispatch_thread_;
{
slash::MutexLock l(&slave_mutex_);
std::vector<SlaveItem>::iterator iter = slaves_.begin();
while (iter != slaves_.end()) {
if (iter->sender != NULL) {
delete static_cast<PikaBinlogSenderThread*>(iter->sender);
}
iter = slaves_.erase(iter);
LOG(INFO) << "Delete slave success";
}
}
delete pika_trysync_thread_;
delete ping_thread_;
delete pika_binlog_receiver_thread_;
delete pika_pubsub_thread_;
binlogbg_exit_ = true;
std::vector<BinlogBGWorker*>::iterator binlogbg_iter = binlogbg_workers_.begin();
while (binlogbg_iter != binlogbg_workers_.end()) {
binlogbg_cond_.SignalAll();
delete (*binlogbg_iter);
binlogbg_iter++;
}
delete pika_heartbeat_thread_;
delete monitor_thread_;
StopKeyScan();
key_scan_thread_.StopThread();
delete logger_;
db_.reset();
pthread_rwlock_destroy(&rwlock_);
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 == "") {
std::ifstream routeFile("/proc/net/route", std::ios_base::in);
if (!routeFile.good())
{
return false;
}
std::string line;
std::vector<std::string> tokens;
while(std::getline(routeFile, line))
{
std::istringstream stream(line);
std::copy(std::istream_iterator<std::string>(stream),
std::istream_iterator<std::string>(),
std::back_inserter<std::vector<std::string> >(tokens));
// the default interface is the one having the second
// field, Destination, set to "00000000"
if ((tokens.size() >= 2) && (tokens[1] == std::string("00000000")))
{
network_interface = tokens[0];
break;
}
tokens.clear();
}
routeFile.close();
}
LOG(INFO) << "Using Networker Interface: " << network_interface;
struct ifaddrs * ifAddrStruct = NULL;
struct ifaddrs * ifa = NULL;
void * tmpAddrPtr = NULL;
if (getifaddrs(&ifAddrStruct) == -1) {
LOG(FATAL) << "getifaddrs failed: " << strerror(errno);
}
for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == NULL) {
continue;
}
if (ifa ->ifa_addr->sa_family==AF_INET) { // Check it is
// a valid IPv4 address
tmpAddrPtr = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
char addressBuffer[INET_ADDRSTRLEN];
inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
if (std::string(ifa->ifa_name) == network_interface) {
host_ = addressBuffer;
break;
}
} else if (ifa->ifa_addr->sa_family==AF_INET6) { // Check it is
// a valid IPv6 address
tmpAddrPtr = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
char addressBuffer[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
if (std::string(ifa->ifa_name) == network_interface) {
host_ = addressBuffer;
break;
}
}
}
if (ifAddrStruct != NULL) {
freeifaddrs(ifAddrStruct);
}
if (ifa == NULL) {
LOG(FATAL) << "error network interface: " << network_interface << ", please check!";
}
port_ = g_pika_conf->port();
LOG(INFO) << "host: " << host_ << " port: " << port_;
return true;
}
void PikaServer::RocksdbOptionInit(blackwidow::BlackwidowOptions* bw_option) {
bw_option->options.create_if_missing = true;
bw_option->options.keep_log_file_num = 10;
bw_option->options.max_manifest_file_size = 64 * 1024 * 1024;
bw_option->options.max_log_file_size = 512 * 1024 * 1024;
bw_option->options.write_buffer_size = g_pika_conf->write_buffer_size();
bw_option->options.target_file_size_base = g_pika_conf->target_file_size_base();
bw_option->options.max_background_flushes = g_pika_conf->max_background_flushes();
bw_option->options.max_background_compactions = g_pika_conf->max_background_compactions();
bw_option->options.max_open_files = g_pika_conf->max_cache_files();
bw_option->options.max_bytes_for_level_multiplier = g_pika_conf->max_bytes_for_level_multiplier();
bw_option->options.optimize_filters_for_hits = g_pika_conf->optimize_filters_for_hits();
bw_option->options.level_compaction_dynamic_level_bytes = g_pika_conf->level_compaction_dynamic_level_bytes();
if (g_pika_conf->compression() == "none") {
bw_option->options.compression = rocksdb::CompressionType::kNoCompression;
} else if (g_pika_conf->compression() == "snappy") {
bw_option->options.compression = rocksdb::CompressionType::kSnappyCompression;
} else if (g_pika_conf->compression() == "zlib") {
bw_option->options.compression = rocksdb::CompressionType::kZlibCompression;
}
bw_option->table_options.block_size = g_pika_conf->block_size();
bw_option->table_options.cache_index_and_filter_blocks = g_pika_conf->cache_index_and_filter_blocks();
bw_option->block_cache_size = g_pika_conf->block_cache();
bw_option->share_block_cache = g_pika_conf->share_block_cache();
}
void PikaServer::Start() {
int ret = 0;
ret = pika_dispatch_thread_->StartThread();
if (ret != pink::kSuccess) {
delete logger_;
db_.reset();
LOG(FATAL) << "Start Dispatch Error: " << ret << (ret == pink::kBindError ? ": bind port " + std::to_string(port_) + " conflict"
: ": other error") << ", Listen on this port to handle the connected redis client";
}
ret = pika_binlog_receiver_thread_->StartThread();
if (ret != pink::kSuccess) {
delete logger_;
db_.reset();
LOG(FATAL) << "Start BinlogReceiver Error: " << ret << (ret == pink::kBindError ? ": bind port " + std::to_string(port_ + 1000) + " conflict"
: ": other error") << ", Listen on this port to handle the data sent by the Binlog Sender";
}
ret = pika_heartbeat_thread_->StartThread();
if (ret != pink::kSuccess) {
delete logger_;
db_.reset();
LOG(FATAL) << "Start Heartbeat Error: " << ret << (ret == pink::kBindError ? ": bind port " + std::to_string(port_ + 2000) + " conflict"
: ": other error") << ", Listen on this port to receive the heartbeat packets sent by the master";
}
ret = pika_trysync_thread_->StartThread();
if (ret != pink::kSuccess) {
delete logger_;
db_.reset();
LOG(FATAL) << "Start Trysync Error: " << ret << (ret == pink::kBindError ? ": bind port conflict" : ": other error");
}
ret = pika_pubsub_thread_->StartThread();
if (ret != pink::kSuccess) {
delete logger_;
db_.reset();
LOG(FATAL) << "Start Pubsub Error: " << ret << (ret == pink::kBindError ? ": bind port conflict" : ": 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);
}
}
// Double master mode
if (!g_pika_conf->double_master_ip().empty()) {
std::string double_master_ip = g_pika_conf->double_master_ip();
int32_t double_master_port = g_pika_conf->double_master_port();
double_master_sid_ = std::stoi(g_pika_conf->double_master_sid());
if ((double_master_ip == "127.0.0.1" || double_master_ip == host_) && double_master_port == port_) {
LOG(FATAL) << "set yourself as the peer-master, please check";
} else {
double_master_mode_ = true;
SetMaster(double_master_ip, double_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++ < 10) {
sleep(1);
}
}
LOG(INFO) << "Goodbye...";
}
void PikaServer::DeleteSlave(const std::string& ip, int64_t port) {
std::string ip_port = slash::IpPortString(ip, port);
int slave_num = 0;
{
slash::MutexLock l(&slave_mutex_);
std::vector<SlaveItem>::iterator iter = slaves_.begin();
while (iter != slaves_.end()) {
if (iter->ip_port == ip_port) {
break;
}
iter++;
}
if (iter == slaves_.end()) {
return;
}
if (iter->sender != NULL) {
delete static_cast<PikaBinlogSenderThread*>(iter->sender);
}
slaves_.erase(iter);
slave_num = slaves_.size();
}
slash::RWLock l(&state_protector_, true);
if (slave_num == 0) {
role_ &= ~PIKA_ROLE_MASTER;
if (DoubleMasterMode()) {
role_ |= PIKA_ROLE_DOUBLE_MASTER;
}
}
}
void PikaServer::DeleteSlave(int fd) {
int slave_num = 0;
{
slash::MutexLock l(&slave_mutex_);
std::vector<SlaveItem>::iterator iter = slaves_.begin();
while (iter != slaves_.end()) {
if (iter->hb_fd == fd) {
if (iter->sender != NULL) {
delete static_cast<PikaBinlogSenderThread*>(iter->sender);
}
slaves_.erase(iter);
LOG(INFO) << "Delete slave success";
break;
}
iter++;
}
slave_num = slaves_.size();
}
slash::RWLock l(&state_protector_, true);
if (slave_num == 0) {
role_ &= ~PIKA_ROLE_MASTER;
if (DoubleMasterMode()) {
role_ |= PIKA_ROLE_DOUBLE_MASTER;
}
}
}
/*
* Change a new db locate in new_path
* return true when change success
* db remain the old one if return false
*/
bool PikaServer::ChangeDb(const std::string& new_path) {
blackwidow::BlackwidowOptions bw_option;
RocksdbOptionInit(&bw_option);
std::string db_path = g_pika_conf->db_path();
std::string tmp_path(db_path);
if (tmp_path.back() == '/') {
tmp_path.resize(tmp_path.size() - 1);
}
tmp_path += "_bak";
slash::DeleteDirIfExist(tmp_path);
RWLock l(&rwlock_, true);
LOG(INFO) << "Prepare change db from: " << tmp_path;
db_.reset();
if (0 != slash::RenameFile(db_path.c_str(), tmp_path)) {
LOG(WARNING) << "Failed to rename db path when change db, error: " << strerror(errno);
return false;
}
if (0 != slash::RenameFile(new_path.c_str(), db_path.c_str())) {
LOG(WARNING) << "Failed to rename new db path when change db, error: " << strerror(errno);
return false;
}
db_.reset(new blackwidow::BlackWidow());
rocksdb::Status s = db_->Open(bw_option, db_path);
assert(db_);
assert(s.ok());
slash::DeleteDirIfExist(tmp_path);
LOG(INFO) << "Change db success";
return true;
}
bool PikaServer::IsDoubleMaster(const std::string master_ip, int master_port) {
if ((g_pika_conf->double_master_ip() == master_ip || host() == master_ip)
&& g_pika_conf->double_master_port() == master_port) {
return true;
} else {
return false;
}
}
void PikaServer::MayUpdateSlavesMap(int64_t sid, int32_t hb_fd) {
slash::MutexLock l(&slave_mutex_);
std::vector<SlaveItem>::iterator iter = slaves_.begin();
LOG(INFO) << "MayUpdateSlavesMap, sid: " << sid << " hb_fd: " << hb_fd;
while (iter != slaves_.end()) {
if (iter->sid == sid) {
iter->hb_fd = hb_fd;
iter->stage = SLAVE_ITEM_STAGE_TWO;
LOG(INFO) << "New Master-Slave connection established successfully, Slave host: " << iter->ip_port;
// If receive 'spci' from the peer-master
if (DoubleMasterMode() && repl_state_ == PIKA_REPL_NO_CONNECT && iter->sid == double_master_sid_) {
std::string double_master_ip = g_pika_conf->double_master_ip();
int32_t double_master_port = g_pika_conf->double_master_port();
SetMaster(double_master_ip, double_master_port);
}
break;
}
iter++;
}
}
// Try add Slave, return slave sid if success,
// return -1 when slave already exist
int64_t PikaServer::TryAddSlave(const std::string& ip, int64_t port) {
std::string ip_port = slash::IpPortString(ip, port);
slash::MutexLock l(&slave_mutex_);
std::vector<SlaveItem>::iterator iter = slaves_.begin();
while (iter != slaves_.end()) {
if (iter->ip_port == ip_port) {
return -1;
}
iter++;
}
// Not exist, so add new
LOG(INFO) << "Add new slave, " << ip << ":" << port;
SlaveItem s;
if (DoubleMasterMode() && IsDoubleMaster(ip, port)) { // Double master mode
s.sid = double_master_sid_;
} else {
s.sid = GenSid();
}
s.ip_port = ip_port;
s.port = port;
s.hb_fd = -1;
s.stage = SLAVE_ITEM_STAGE_ONE;
gettimeofday(&s.create_time, NULL);
s.sender = NULL;
slaves_.push_back(s);
return s.sid;
}
// Set binlog sender of SlaveItem
bool PikaServer::SetSlaveSender(const std::string& ip, int64_t port,
PikaBinlogSenderThread* s){
std::string ip_port = slash::IpPortString(ip, port);
slash::MutexLock l(&slave_mutex_);
std::vector<SlaveItem>::iterator iter = slaves_.begin();
while (iter != slaves_.end()) {
if (iter->ip_port == ip_port) {
break;
}
iter++;
}
if (iter == slaves_.end()) {
// Not exist
return false;
}
iter->sender = s;
iter->sender_tid = s->thread_id();
LOG(INFO) << "SetSlaveSender ok, tid is " << iter->sender_tid
<< " hd_fd: " << iter->hb_fd << " stage: " << iter->stage;
return true;
}
int32_t PikaServer::GetSlaveListString(std::string& slave_list_str) {
size_t index = 0;
std::string slave_ip_port;
std::stringstream tmp_stream;
slash::MutexLock l(&slave_mutex_);
std::vector<SlaveItem>::iterator iter = slaves_.begin();
for (; iter != slaves_.end(); ++iter) {
if ((*iter).sender == NULL) {
// Binlog Sender has not yet created
continue;
}
uint32_t master_filenum, slave_filenum;
uint64_t master_offset, slave_offset;
logger_->GetProducerStatus(&master_filenum, &master_offset);
PikaBinlogSenderThread* ptr_sender = static_cast<PikaBinlogSenderThread*>(iter->sender);
slave_filenum = ptr_sender->filenum();
slave_offset = ptr_sender->con_offset();
uint64_t lag = (master_filenum - slave_filenum) * logger_->file_size()
+ (master_offset - slave_offset);
slave_ip_port =(*iter).ip_port;
tmp_stream << "slave" << index++
<< ":ip=" << slave_ip_port.substr(0, slave_ip_port.find(":"))
<< ",port=" << slave_ip_port.substr(slave_ip_port.find(":") + 1)
<< ",state=" << ((*iter).stage == SLAVE_ITEM_STAGE_TWO ? "online" : "offline")
<< ",sid=" << (*iter).sid
<< ",lag=" << lag
<< "\r\n";
}
slave_list_str.assign(tmp_stream.str());
return index;
}
void PikaServer::BecomeMaster() {
slash::RWLock l(&state_protector_, true);
if (double_master_mode_) {
role_ |= PIKA_ROLE_DOUBLE_MASTER;
} else {
role_ |= PIKA_ROLE_MASTER;
}
}
bool PikaServer::SetMaster(std::string& master_ip, int master_port) {
if (master_ip == "127.0.0.1") {
master_ip = host_;
}
slash::RWLock l(&state_protector_, true);
if ((role_ ^ PIKA_ROLE_SLAVE) && repl_state_ == PIKA_REPL_NO_CONNECT) {
master_ip_ = master_ip;
master_port_ = master_port;
if (!double_master_mode_) {
role_ |= PIKA_ROLE_SLAVE;
repl_state_ = PIKA_REPL_CONNECT;
LOG(INFO) << "Open read-only mode";
g_pika_conf->SetReadonly(true);
return true;
} else {
role_ |= PIKA_ROLE_DOUBLE_MASTER;
repl_state_ = PIKA_REPL_CONNECT;
LOG(INFO) << "In double-master mode, do not open read-only mode";
return true;
}
}
return false;
}
bool PikaServer::WaitingDBSync() {
slash::RWLock l(&state_protector_, false);
DLOG(INFO) << "repl_state: " << repl_state_ << " role: " << role_ << " master_connection: " << master_connection_;
if (repl_state_ == PIKA_REPL_WAIT_DBSYNC) {
return true;
}
return false;
}
void PikaServer::NeedWaitDBSync() {
slash::RWLock l(&state_protector_, true);
repl_state_ = PIKA_REPL_WAIT_DBSYNC;
}
void PikaServer::WaitDBSyncFinish() {
slash::RWLock l(&state_protector_, true);
if (repl_state_ == PIKA_REPL_WAIT_DBSYNC) {
repl_state_ = PIKA_REPL_CONNECT;
}
}
void PikaServer::KillBinlogSenderConn() {
pika_binlog_receiver_thread_->KillBinlogSender();
}
bool PikaServer::ShouldConnectMaster() {
slash::RWLock l(&state_protector_, false);
DLOG(INFO) << "repl_state: " << repl_state_ << " role: " << role_ << " master_connection: " << master_connection_;
if (repl_state_ == PIKA_REPL_CONNECT) {
return true;
}
return false;
}
void PikaServer::ConnectMasterDone() {
slash::RWLock l(&state_protector_, true);
if (repl_state_ == PIKA_REPL_CONNECT) {
repl_state_ = PIKA_REPL_CONNECTING;
}
}
bool PikaServer::ShouldStartPingMaster() {
slash::RWLock l(&state_protector_, false);
DLOG(INFO) << "ShouldStartPingMaster: master_connection " << master_connection_ << " repl_state " << repl_state_;
if (repl_state_ == PIKA_REPL_CONNECTING && master_connection_ < 2) {
return true;
}
return false;
}
void PikaServer::MinusMasterConnection() {
slash::RWLock l(&state_protector_, true);
if (master_connection_ > 0) {
if ((--master_connection_) <= 0) {
// two connection with master has been deleted
if (role_ & PIKA_ROLE_SLAVE) {
repl_state_ = PIKA_REPL_CONNECT; // not change by slaveof no one, so set repl_state = PIKA_REPL_CONNECT, continue to connect master
} else {
repl_state_ = PIKA_REPL_NO_CONNECT; // change by slaveof no one, so set repl_state = PIKA_REPL_NO_CONNECT, reset to SINGLE state
}
master_connection_ = 0;
}
}
}
void PikaServer::PlusMasterConnection() {
slash::RWLock l(&state_protector_, true);
if (master_connection_ < 2) {
if ((++master_connection_) >= 2) {
// two connection with master has been established
repl_state_ = PIKA_REPL_CONNECTED;
master_connection_ = 2;
LOG(INFO) << "Master-Slave connection established successfully";
}
}
}
bool PikaServer::ShouldAccessConnAsMaster(const std::string& ip) {
slash::RWLock l(&state_protector_, false);
DLOG(INFO) << "ShouldAccessConnAsMaster, repl_state_: " << repl_state_ << " ip: " << ip << " master_ip: " << master_ip_;
if ((repl_state_ == PIKA_REPL_CONNECTING || repl_state_ == PIKA_REPL_CONNECTED) &&
ip == master_ip_) {
return true;
}
return false;
}
void PikaServer::SyncError() {
{
slash::RWLock l(&state_protector_, true);
repl_state_ = PIKA_REPL_ERROR;
}
if (ping_thread_ != NULL) {
int err = ping_thread_->StopThread();
if (err != 0) {
std::string msg = "can't join thread " + std::string(strerror(err));
LOG(WARNING) << msg;
}
delete ping_thread_;
ping_thread_ = NULL;
}
LOG(WARNING) << "Sync error, set repl_state to PIKA_REPL_ERROR";
}
void PikaServer::RemoveMaster() {
{
slash::RWLock l(&state_protector_, true);
repl_state_ = PIKA_REPL_NO_CONNECT;
if (DoubleMasterMode()) {
role_ &= ~PIKA_ROLE_DOUBLE_MASTER;
} else {
role_ &= ~PIKA_ROLE_SLAVE;
}
master_ip_ = "";
master_port_ = -1;
}
if (ping_thread_ != NULL) {
int err = ping_thread_->StopThread();
if (err != 0) {
std::string msg = "can't join thread " + std::string(strerror(err));
LOG(WARNING) << msg;
}
delete ping_thread_;
ping_thread_ = NULL;
}
{
slash::RWLock l(&state_protector_, true);
master_connection_ = 0;
}
LOG(INFO) << "close read-only mode";
g_pika_conf->SetReadonly(false);
}
void PikaServer::TryDBSync(const std::string& ip, int port, int32_t top) {
std::string bg_path;
uint32_t bg_filenum = 0;
{
slash::MutexLock l(&bgsave_protector_);
bg_path = bgsave_info_.path;
bg_filenum = bgsave_info_.filenum;
}
if (0 != slash::IsDir(bg_path) || //Bgsaving dir exist
!slash::FileExists(NewFileName(logger_->filename, bg_filenum)) || //filenum can be found in binglog
top - bg_filenum > kDBSyncMaxGap) { //The file is not too old
// Need Bgsave first
Bgsave();
}
DBSync(ip, port);
}
void PikaServer::DBSync(const std::string& ip, int port) {
// Only one DBSync task for every ip_port
{
slash::MutexLock ldb(&db_sync_protector_);
std::string ip_port = slash::IpPortString(ip, port);
if (db_sync_slaves_.find(ip_port) != db_sync_slaves_.end()) {
return;
}
db_sync_slaves_.insert(ip_port);
}
// Reuse the bgsave_thread_
// Since we expect Bgsave and DBSync execute serially
bgsave_thread_.StartThread();
DBSyncArg *arg = new DBSyncArg(this, ip, port);
bgsave_thread_.Schedule(&DoDBSync, static_cast<void*>(arg));
}
void PikaServer::DoDBSync(void* arg) {
DBSyncArg *ppurge = static_cast<DBSyncArg*>(arg);
PikaServer* ps = ppurge->p;
ps->DBSyncSendFile(ppurge->ip, ppurge->port);
delete (PurgeArg*)arg;
}
void PikaServer::DBSyncSendFile(const std::string& ip, int port) {
std::string bg_path;
uint32_t binlog_filenum;
uint64_t binlog_offset;
{
slash::MutexLock l(&bgsave_protector_);
bg_path = bgsave_info_.path;
binlog_filenum = bgsave_info_.filenum;
binlog_offset = bgsave_info_.offset;
}
// Get all files need to send
std::vector<std::string> descendant;
int ret = 0;
LOG(INFO) << "Start Send files in " << bg_path << " to " << ip;
ret = slash::GetChildren(bg_path, descendant);
if (ret != 0) {
std::string ip_port = slash::IpPortString(ip, port);
slash::MutexLock ldb(&db_sync_protector_);
db_sync_slaves_.erase(ip_port);
LOG(WARNING) << "Get child directory when try to do sync failed, error: " << strerror(ret);
return;
}
// Iterate to send files
ret = 0;
std::string local_path, target_path;
pink::PinkCli *cli = pink::NewRedisCli();
std::string lip(host_);
if (cli->Connect(ip, port, "").ok()) {
struct sockaddr_in laddr;
socklen_t llen = sizeof(laddr);
getsockname(cli->fd(), (struct sockaddr*) &laddr, &llen);
lip = inet_ntoa(laddr.sin_addr);
cli->Close();
}
std::string module = kDBSyncModule + "_" + slash::IpPortString(lip, port_);
std::vector<std::string>::iterator it = descendant.begin();
slash::RsyncRemote remote(ip, port, module, g_pika_conf->db_sync_speed() * 1024);
for (; it != descendant.end(); ++it) {
local_path = bg_path + "/" + *it;
target_path = *it;
if (target_path == kBgsaveInfoFile) {
continue;
}
if (slash::IsDir(local_path) == 0 &&
local_path.back() != '/') {
local_path.push_back('/');
target_path.push_back('/');
}
// We need specify the speed limit for every single file
ret = slash::RsyncSendFile(local_path, target_path, remote);
if (0 != ret) {
LOG(WARNING) << "rsync send file failed! From: " << *it
<< ", To: " << target_path
<< ", At: " << ip << ":" << port
<< ", Error: " << ret;
break;
}
}
// Clear target path
slash::RsyncSendClearTarget(bg_path + "/strings", "strings", remote);
slash::RsyncSendClearTarget(bg_path + "/hashes", "hashes", remote);
slash::RsyncSendClearTarget(bg_path + "/lists", "lists", remote);
slash::RsyncSendClearTarget(bg_path + "/sets", "sets", remote);
slash::RsyncSendClearTarget(bg_path + "/zsets", "zsets", remote);
// Send info file at last
if (0 == ret) {
// need to modify the IP addr in the info file
if (lip.compare(host_) != 0) {
std::ofstream fix;
std::string fn = bg_path + "/" + kBgsaveInfoFile + "." + std::to_string(time(NULL));
fix.open(fn, std::ios::in | std::ios::trunc);
if (fix.is_open()) {
fix << "0s\n" << lip << "\n" << port_ << "\n" << binlog_filenum << "\n" << binlog_offset << "\n";
fix.close();
}
ret = slash::RsyncSendFile(fn, kBgsaveInfoFile, remote);
slash::DeleteFile(fn);
if (ret != 0) {
LOG(WARNING) << "send modified info file failed";
}
} else if (0 != (ret = slash::RsyncSendFile(bg_path + "/" + kBgsaveInfoFile, kBgsaveInfoFile, remote))) {
LOG(WARNING) << "send info file failed";
}
}
// remove slave
{
std::string ip_port = slash::IpPortString(ip, port);
slash::MutexLock ldb(&db_sync_protector_);
db_sync_slaves_.erase(ip_port);
}
if (0 == ret) {
LOG(INFO) << "rsync send files success";
// If receiver is the peer-master,
// need to update receive binlog info
if ((g_pika_conf->double_master_ip() == ip || host() == ip)
&& (g_pika_conf->double_master_port() + 3000) == port) {
// Update Recv Info
logger_->SetDoubleRecvInfo(binlog_filenum, binlog_offset);
LOG(INFO) << "Update recv info filenum: " << binlog_filenum << " offset: " << binlog_offset;
}
}
}
/*
* BinlogSender
*/
Status PikaServer::AddBinlogSender(const std::string& ip, int64_t port,
int64_t sid,
uint32_t filenum, uint64_t con_offset) {
// Sanity check
if (con_offset > logger_->file_size()) {
return Status::InvalidArgument("AddBinlogSender invalid binlog offset");
}
uint32_t cur_filenum = 0;
uint64_t cur_offset = 0;
logger_->GetProducerStatus(&cur_filenum, &cur_offset);
if (filenum != UINT32_MAX &&
(cur_filenum < filenum || (cur_filenum == filenum && cur_offset < con_offset))) {
return Status::InvalidArgument("AddBinlogSender invalid binlog offset");
}
if (filenum == UINT32_MAX) {
LOG(INFO) << "Maybe force full sync";
}
// Create and set sender
slash::SequentialFile *readfile;
std::string confile = NewFileName(logger_->filename, filenum);
if (!slash::FileExists(confile)) {
// Not found binlog specified by filenum
// If in double-master mode, return error status
if (DoubleMasterMode() && IsDoubleMaster(ip, port) && filenum != UINT32_MAX) {
return Status::InvalidArgument("AddBinlogSender invalid binlog offset");
}
TryDBSync(ip, port + 3000, cur_filenum);
return Status::Incomplete("Bgsaving and DBSync first");
}
if (!slash::NewSequentialFile(confile, &readfile).ok()) {
return Status::IOError("AddBinlogSender new sequtialfile");
}
PikaBinlogSenderThread* sender = new PikaBinlogSenderThread(ip,
port + 1000, sid, readfile, filenum, con_offset);
if (sender->trim() == 0 // Error binlog
&& SetSlaveSender(ip, port, sender)) { // SlaveItem not exist
sender->StartThread();
return Status::OK();
} else {
delete sender;
LOG(WARNING) << "AddBinlogSender failed";
return Status::NotFound("AddBinlogSender bad sender");
}
}
// Prepare engine, need bgsave_protector protect
bool PikaServer::InitBgsaveEnv() {
{
slash::MutexLock l(&bgsave_protector_);
// Prepare for bgsave dir
bgsave_info_.start_time = time(NULL);
char s_time[32];
int len = strftime(s_time, sizeof(s_time), "%Y%m%d%H%M%S", localtime(&bgsave_info_.start_time));
bgsave_info_.s_start_time.assign(s_time, len);
std::string bgsave_path(g_pika_conf->bgsave_path());
bgsave_info_.path = bgsave_path + g_pika_conf->bgsave_prefix() + std::string(s_time, 8);
if (!slash::DeleteDirIfExist(bgsave_info_.path)) {
LOG(WARNING) << "remove exist bgsave dir failed";
return false;
}
slash::CreatePath(bgsave_info_.path, 0755);
// Prepare for failed dir
if (!slash::DeleteDirIfExist(bgsave_info_.path + "_FAILED")) {
LOG(WARNING) << "remove exist fail bgsave dir failed :";
return false;
}
}
return true;
}
// Prepare bgsave env, need bgsave_protector protect
bool PikaServer::InitBgsaveEngine() {
delete bgsave_engine_;
rocksdb::Status s = blackwidow::BackupEngine::Open(db().get(), &bgsave_engine_);
if (!s.ok()) {
LOG(WARNING) << "open backup engine failed " << s.ToString();
return false;
}
{
RWLock l(&rwlock_, true);
{
slash::MutexLock l(&bgsave_protector_);
logger_->GetProducerStatus(&bgsave_info_.filenum, &bgsave_info_.offset);
}
s = bgsave_engine_->SetBackupContent();
if (!s.ok()){
LOG(WARNING) << "set backup content failed " << s.ToString();
return false;
}
}
return true;
}
bool PikaServer::RunBgsaveEngine() {
// Prepare for Bgsaving
if (!InitBgsaveEnv() || !InitBgsaveEngine()) {
ClearBgsave();
return false;