forked from OpenAtomFoundation/pikiwidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpika_slot_command.cc
1530 lines (1319 loc) · 41.8 KB
/
pika_slot_command.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 <algorithm>
#include <memory>
#include <string>
#include <vector>
#include "include/pika_slot_command.h"
#include "include/pika_command.h"
#include "include/pika_data_distribution.h"
#include "include/pika_migrate_thread.h"
#include "include/pika_server.h"
#include "include/pika_admin.h"
#include "include/pika_cmd_table_manager.h"
#include "include/pika_rm.h"
#include "pstd/include/pstd_status.h"
#include "pstd/include/pstd_string.h"
#include "include/pika_conf.h"
#include "pstd/include/pika_codis_slot.h"
#include "include/pika_define.h"
#include "storage/include/storage/storage.h"
#define min(a, b) (((a) > (b)) ? (b) : (a))
#define MAX_MEMBERS_NUM 512
extern std::unique_ptr<PikaServer> g_pika_server;
extern std::unique_ptr<PikaConf> g_pika_conf;
extern std::unique_ptr<PikaReplicaManager> g_pika_rm;
extern std::unique_ptr<PikaCmdTableManager> g_pika_cmd_table_manager;
PikaMigrate::PikaMigrate() { migrate_clients_.clear(); }
PikaMigrate::~PikaMigrate() {
// close and release all clients
// get the mutex lock
std::lock_guard lm(mutex_);
KillAllMigrateClient();
}
net::NetCli *PikaMigrate::GetMigrateClient(const std::string &host, const int port, int timeout) {
std::string ip_port = host + ":" + std::to_string(port);
net::NetCli *migrate_cli;
pstd::Status s;
auto migrate_clients_iter = migrate_clients_.find(ip_port);
if (migrate_clients_iter == migrate_clients_.end()) {
migrate_cli = net::NewRedisCli();
s = migrate_cli->Connect(host, port, g_pika_server->host());
if (!s.ok()) {
LOG(ERROR) << "GetMigrateClient: new migrate_cli[" << ip_port.c_str() << "] failed";
delete migrate_cli;
return nullptr;
}
LOG(INFO) << "GetMigrateClient: new migrate_cli[" << ip_port.c_str() << "]";
// add a new migrate client to the map
migrate_clients_[ip_port] = migrate_cli;
} else {
migrate_cli = static_cast<net::NetCli *>(migrate_clients_iter->second);
}
// set the client connect timeout
migrate_cli->set_send_timeout(timeout);
migrate_cli->set_recv_timeout(timeout);
// modify the client last time
gettimeofday(&migrate_cli->last_interaction_, nullptr);
return migrate_cli;
}
void PikaMigrate::KillMigrateClient(net::NetCli *migrate_cli) {
auto migrate_clients_iter = migrate_clients_.begin();
while (migrate_clients_iter != migrate_clients_.end()) {
if (migrate_cli == static_cast<net::NetCli *>(migrate_clients_iter->second)) {
LOG(INFO) << "KillMigrateClient: kill migrate_cli[" << migrate_clients_iter->first.c_str() << "]";
migrate_cli->Close();
delete migrate_cli;
migrate_cli = nullptr;
migrate_clients_.erase(migrate_clients_iter);
break;
}
++migrate_clients_iter;
}
}
// clean and realse timeout client
void PikaMigrate::CleanMigrateClient() {
struct timeval now;
// if the size of migrate_clients_ <= 0, don't need clean
if (migrate_clients_.size() <= 0) {
return;
}
gettimeofday(&now, nullptr);
auto migrate_clients_iter = migrate_clients_.begin();
while (migrate_clients_iter != migrate_clients_.end()) {
auto migrate_cli = static_cast<net::NetCli *>(migrate_clients_iter->second);
// pika_server do DoTimingTask every 10s, so we Try colse the migrate_cli before pika timeout, do it at least 20s in
// advance
int timeout = (g_pika_conf->timeout() > 0) ? g_pika_conf->timeout() : 60;
if (now.tv_sec - migrate_cli->last_interaction_.tv_sec > timeout - 20) {
LOG(INFO) << "CleanMigrateClient: clean migrate_cli[" << migrate_clients_iter->first.c_str() << "]";
migrate_cli->Close();
delete migrate_cli;
migrate_clients_iter = migrate_clients_.erase(migrate_clients_iter);
} else {
++migrate_clients_iter;
}
}
}
// clean and realse all client
void PikaMigrate::KillAllMigrateClient() {
auto migrate_clients_iter = migrate_clients_.begin();
while (migrate_clients_iter != migrate_clients_.end()) {
auto migrate_cli = static_cast<net::NetCli *>(migrate_clients_iter->second);
LOG(INFO) << "KillAllMigrateClient: kill migrate_cli[" << migrate_clients_iter->first.c_str() << "]";
migrate_cli->Close();
delete migrate_cli;
migrate_clients_iter = migrate_clients_.erase(migrate_clients_iter);
}
}
/* *
* do migrate a key-value for slotsmgrt/slotsmgrtone commands
* return value:
* -1 - error happens
* >=0 - # of success migration (0 or 1)
* */
int PikaMigrate::MigrateKey(const std::string &host, const int port, int timeout, const std::string& key,
const char type, std::string &detail, const std::shared_ptr<DB>& db) {
int send_command_num = -1;
net::NetCli *migrate_cli = GetMigrateClient(host, port, timeout);
if (!migrate_cli) {
detail = "IOERR error or timeout connecting to the client";
return -1;
}
send_command_num = MigrateSend(migrate_cli, key, type, detail, db);
if (send_command_num <= 0) {
return send_command_num;
}
if (MigrateRecv(migrate_cli, send_command_num, detail)) {
return send_command_num;
}
return -1;
}
int PikaMigrate::MigrateSend(net::NetCli* migrate_cli, const std::string& key, const char type, std::string& detail,
const std::shared_ptr<DB>& db) {
std::string wbuf_str;
pstd::Status s;
int command_num = -1;
// chech the client is alive
if (!migrate_cli) {
return -1;
}
command_num = ParseKey(key, type, wbuf_str, db);
if (command_num < 0) {
detail = "ParseKey failed";
return command_num;
}
// don't need seed data, key is not exists
if (command_num == 0 || wbuf_str.empty()) {
return 0;
}
s = migrate_cli->Send(&wbuf_str);
if (!s.ok()) {
LOG(ERROR) << "Connect slots target, Send error: " << s.ToString();
detail = "Connect slots target, Send error: " + s.ToString();
KillMigrateClient(migrate_cli);
return -1;
}
return command_num;
}
bool PikaMigrate::MigrateRecv(net::NetCli* migrate_cli, int need_receive, std::string& detail) {
pstd::Status s;
std::string reply;
int64_t ret;
if (nullptr == migrate_cli || need_receive < 0) {
return false;
}
net::RedisCmdArgsType argv;
while (need_receive) {
s = migrate_cli->Recv(&argv);
if (!s.ok()) {
LOG(ERROR) << "Connect slots target, Recv error: " << s.ToString();
detail = "Connect slots target, Recv error: " + s.ToString();
KillMigrateClient(migrate_cli);
return false;
}
reply = argv[0];
need_receive--;
// set return ok
// zadd return number
// hset return 0 or 1
// hmset return ok
// sadd return number
// rpush return length
if (argv.size() == 1 &&
(kInnerReplOk == pstd::StringToLower(reply) || pstd::string2int(reply.data(), reply.size(), &ret))) {
// continue reiceve response
if (need_receive > 0) {
continue;
}
// has got all responses
break;
}
// failed
detail = "something wrong with slots migrate, reply: " + reply;
LOG(ERROR) << "something wrong with slots migrate, reply:" << reply;
return false;
}
return true;
}
// return -1 is error; 0 don't migrate; >0 the number of commond
int PikaMigrate::ParseKey(const std::string& key, const char type, std::string& wbuf_str, const std::shared_ptr<DB>& db) {
int command_num = -1;
int64_t ttl = 0;
rocksdb::Status s;
switch (type) {
case 'k':
command_num = ParseKKey(key, wbuf_str, db);
break;
case 'h':
command_num = ParseHKey(key, wbuf_str, db);
break;
case 'l':
command_num = ParseLKey(key, wbuf_str, db);
break;
case 'z':
command_num = ParseZKey(key, wbuf_str, db);
break;
case 's':
command_num = ParseSKey(key, wbuf_str, db);
break;
default:
LOG(INFO) << "ParseKey key[" << key << "], the type[" << type << "] is not support.";
return -1;
break;
}
// error or key is not existed
if (command_num <= 0) {
LOG(INFO) << "ParseKey key[" << key << "], parse return " << command_num
<< ", the key maybe is not exist or expired.";
return command_num;
}
// skip kv, because kv cmd: SET key value ttl
if (type == 'k') {
return command_num;
}
ttl = TTLByType(type, key, db);
//-1 indicates the key is valid forever
if (ttl == -1) {
return command_num;
}
// key is expired or not exist, don't migrate
if (ttl == 0 or ttl == -2) {
wbuf_str.clear();
return 0;
}
// no kv, because kv cmd: SET key value ttl
if (SetTTL(key, wbuf_str, ttl)) {
command_num += 1;
}
return command_num;
}
bool PikaMigrate::SetTTL(const std::string& key, std::string& wbuf_str, int64_t ttl) {
//-1 indicates the key is valid forever
if (ttl == -1) {
return false;
}
// if ttl = -2 indicates, the key is not existed
if (ttl < 0) {
LOG(INFO) << "SetTTL key[" << key << "], ttl is " << ttl;
ttl = 0;
}
net::RedisCmdArgsType argv;
std::string cmd;
argv.emplace_back("EXPIRE");
argv.emplace_back(key);
argv.emplace_back(std::to_string(ttl));
net::SerializeRedisCommand(argv, &cmd);
wbuf_str.append(cmd);
return true;
}
// return -1 is error; 0 don't migrate; >0 the number of commond
int PikaMigrate::ParseKKey(const std::string& key, std::string& wbuf_str, const std::shared_ptr<DB>& db) {
net::RedisCmdArgsType argv;
std::string cmd;
std::string value;
int64_t ttl = 0;
rocksdb::Status s;
s = db->storage()->Get(key, &value);
// if key is not existed, don't migrate
if (s.IsNotFound()) {
return 0;
}
if (!s.ok()) {
return -1;
}
argv.emplace_back("SET");
argv.emplace_back(key);
argv.emplace_back(value);
ttl = TTLByType('k', key, db);
// ttl = -1 indicates the key is valid forever, dont process
// key is expired or not exist, dont migrate
// todo check ttl
if (ttl == 0 || ttl == -2) {
wbuf_str.clear();
return 0;
}
if (ttl > 0) {
argv.emplace_back("EX");
argv.emplace_back(std::to_string(ttl));
}
net::SerializeRedisCommand(argv, &cmd);
wbuf_str.append(cmd);
return 1;
}
int64_t PikaMigrate::TTLByType(const char key_type, const std::string& key, const std::shared_ptr<DB>& db) {
std::map<storage::DataType, int64_t> type_timestamp;
std::map<storage::DataType, rocksdb::Status> type_status;
type_timestamp = db->storage()->TTL(key, &type_status);
switch (key_type) {
case 'k': {
return type_timestamp[storage::kStrings];
} break;
case 'h': {
return type_timestamp[storage::kHashes];
} break;
case 'z': {
return type_timestamp[storage::kZSets];
} break;
case 's': {
return type_timestamp[storage::kSets];
} break;
case 'l': {
return type_timestamp[storage::kLists];
} break;
default:
return -3;
}
}
int PikaMigrate::ParseZKey(const std::string& key, std::string& wbuf_str, const std::shared_ptr<DB>& db) {
int command_num = 0;
int64_t next_cursor = 0;
std::vector<storage::ScoreMember> score_members;
do {
score_members.clear();
rocksdb::Status s = db->storage()->ZScan(key, next_cursor, "*", MAX_MEMBERS_NUM, &score_members, &next_cursor);
if (s.ok()) {
if (score_members.empty()) {
break;
}
net::RedisCmdArgsType argv;
std::string cmd;
argv.emplace_back("ZADD");
argv.emplace_back(key);
for (const auto &score_member : score_members) {
argv.emplace_back(std::to_string(score_member.score));
argv.emplace_back(score_member.member);
}
net::SerializeRedisCommand(argv, &cmd);
wbuf_str.append(cmd);
command_num++;
} else if (s.IsNotFound()) {
wbuf_str.clear();
return 0;
} else {
wbuf_str.clear();
return -1;
}
} while (next_cursor > 0);
return command_num;
}
// return -1 is error; 0 don't migrate; >0 the number of commond
int PikaMigrate::ParseHKey(const std::string& key, std::string& wbuf_str, const std::shared_ptr<DB>& db) {
int64_t next_cursor = 0;
int command_num = 0;
std::vector<storage::FieldValue> field_values;
do {
field_values.clear();
rocksdb::Status s = db->storage()->HScan(key, next_cursor, "*", MAX_MEMBERS_NUM, &field_values, &next_cursor);
if (s.ok()) {
if (field_values.empty()) {
break;
}
net::RedisCmdArgsType argv;
std::string cmd;
argv.emplace_back("HMSET");
argv.emplace_back(key);
for (const auto &field_value : field_values) {
argv.emplace_back(field_value.field);
argv.emplace_back(field_value.value);
}
net::SerializeRedisCommand(argv, &cmd);
wbuf_str.append(cmd);
command_num++;
} else if (s.IsNotFound()) {
wbuf_str.clear();
return 0;
} else {
wbuf_str.clear();
return -1;
}
} while (next_cursor > 0);
return command_num;
}
// return -1 is error; 0 don't migrate; >0 the number of commond
int PikaMigrate::ParseSKey(const std::string& key, std::string& wbuf_str, const std::shared_ptr<DB>& db) {
int command_num = 0;
int64_t next_cursor = 0;
std::vector<std::string> members;
do {
members.clear();
rocksdb::Status s = db->storage()->SScan(key, next_cursor, "*", MAX_MEMBERS_NUM, &members, &next_cursor);
if (s.ok()) {
if (members.empty()) {
break;
}
net::RedisCmdArgsType argv;
std::string cmd;
argv.emplace_back("SADD");
argv.emplace_back(key);
for (const auto &member : members) {
argv.emplace_back(member);
}
net::SerializeRedisCommand(argv, &cmd);
wbuf_str.append(cmd);
command_num++;
} else if (s.IsNotFound()) {
wbuf_str.clear();
return 0;
} else {
wbuf_str.clear();
return -1;
}
} while (next_cursor > 0);
return command_num;
}
// return -1 is error; 0 don't migrate; >0 the number of commond
int PikaMigrate::ParseLKey(const std::string& key, std::string& wbuf_str, const std::shared_ptr<DB>& db) {
int64_t left = 0;
int command_num = 0;
std::vector<std::string> values;
net::RedisCmdArgsType argv;
std::string cmd;
// del old key, before migrate list; prevent redo when failed
argv.emplace_back("DEL");
argv.emplace_back(key);
net::SerializeRedisCommand(argv, &cmd);
wbuf_str.append(cmd);
command_num++;
do {
values.clear();
rocksdb::Status s = db->storage()->LRange(key, left, left + (MAX_MEMBERS_NUM - 1), &values);
if (s.ok()) {
if (values.empty()) {
break;
}
net::RedisCmdArgsType argv;
std::string cmd;
argv.emplace_back("RPUSH");
argv.emplace_back(key);
for (const auto &value : values) {
argv.emplace_back(value);
}
net::SerializeRedisCommand(argv, &cmd);
wbuf_str.append(cmd);
command_num++;
left += MAX_MEMBERS_NUM;
} else if (s.IsNotFound()) {
wbuf_str.clear();
return 0;
} else {
wbuf_str.clear();
return -1;
}
} while (!values.empty());
if (command_num == 1) {
wbuf_str.clear();
command_num = 0;
}
return command_num;
}
/* *
* do migrate a key-value for slotsmgrt/slotsmgrtone commands
* return value:
* -1 - error happens
* >=0 - # of success migration (0 or 1)
* */
static int SlotsMgrtOne(const std::string &host, const int port, int timeout, const std::string& key, const char type,
std::string& detail, const std::shared_ptr<DB>& db) {
int send_command_num = 0;
rocksdb::Status s;
std::map<storage::DataType, rocksdb::Status> type_status;
send_command_num = g_pika_server->pika_migrate_->MigrateKey(host, port, timeout, key, type, detail, db);
// the key is migrated to target, delete key and slotsinfo
if (send_command_num >= 1) {
std::vector<std::string> keys;
keys.emplace_back(key);
int64_t count = db->storage()->Del(keys, &type_status);
if (count > 0) {
WriteDelKeyToBinlog(key, db);
}
// del slots info
RemSlotKeyByType(std::string(1, type), key, db);
return 1;
}
// key is not existed, only del slotsinfo
if (send_command_num == 0) {
// del slots info
RemSlotKeyByType(std::string(1, type), key, db);
return 0;
}
return -1;
}
void RemSlotKeyByType(const std::string& type, const std::string& key, const std::shared_ptr<DB>& db) {
uint32_t crc;
int hastag;
uint32_t slotNum = GetSlotsID(g_pika_conf->default_slot_num(), key, &crc, &hastag);
std::string slot_key = GetSlotKey(slotNum);
int32_t res = 0;
std::vector<std::string> members;
members.emplace_back(type + key);
rocksdb::Status s = db->storage()->SRem(slot_key, members, &res);
if (!s.ok()) {
LOG(ERROR) << "srem key[" << key << "] from slotKey[" << slot_key << "] failed, error: " << s.ToString();
return;
}
if (hastag) {
std::string tag_key = GetSlotsTagKey(crc);
s = db->storage()->SRem(tag_key, members, &res);
if (!s.ok()) {
LOG(ERROR) << "srem key[" << key << "] from tagKey[" << tag_key << "] failed, error: " << s.ToString();
return;
}
}
}
/* *
* do migrate mutli key-value(s) for {slotsmgrt/slotsmgrtone}with tag commands
* return value:
* -1 - error happens
* >=0 - # of success migration
* */
static int SlotsMgrtTag(const std::string& host, const int port, int timeout, const std::string& key, const char type,
std::string& detail, const std::shared_ptr<DB>& db) {
int count = 0;
uint32_t crc;
int hastag;
GetSlotsID(g_pika_conf->default_slot_num(), key, &crc, &hastag);
if (!hastag) {
if (type == 0) {
return 0;
}
return SlotsMgrtOne(host, port, timeout, key, type, detail, db);
}
std::string tag_key = GetSlotsTagKey(crc);
std::vector<std::string> members;
// get all keys that have the same crc
rocksdb::Status s = db->storage()->SMembers(tag_key, &members);
if (!s.ok()) {
return -1;
}
auto iter = members.begin();
for (; iter != members.end(); iter++) {
std::string key = *iter;
char type = key.at(0);
key.erase(key.begin());
int ret = SlotsMgrtOne(host, port, timeout, key, type, detail, db);
// the key is migrated to target
if (ret == 1) {
count++;
continue;
}
if (ret == 0) {
LOG(WARNING) << "slots migrate tag failed, key: " << key << ", detail: " << detail;
continue;
}
return -1;
}
return count;
}
std::string GetSlotKey(uint32_t slot) {
return SlotKeyPrefix + std::to_string(slot);
}
// add key to slotkey
void AddSlotKey(const std::string& type, const std::string& key, const std::shared_ptr<DB>& db) {
if (g_pika_conf->slotmigrate() != true) {
return;
}
rocksdb::Status s;
int32_t res = -1;
uint32_t crc;
int hastag;
uint32_t slotID = GetSlotsID(g_pika_conf->default_slot_num(), key, &crc, &hastag);
std::string slot_key = GetSlotKey(slotID);
std::vector<std::string> members;
members.emplace_back(type + key);
s = db->storage()->SAdd(slot_key, members, &res);
if (!s.ok()) {
LOG(ERROR) << "sadd key[" << key << "] to slotKey[" << slot_key << "] failed, error: " << s.ToString();
return;
}
// if res == 0, indicate the key is existed; may return,
// prevent write slot_key success, but write tag_key failed, so always write tag_key
if (hastag) {
std::string tag_key = GetSlotsTagKey(crc);
s = db->storage()->SAdd(tag_key, members, &res);
if (!s.ok()) {
LOG(ERROR) << "sadd key[" << key << "] to tagKey[" << tag_key << "] failed, error: " << s.ToString();
return;
}
}
}
// del key from slotkey
void RemSlotKey(const std::string& key, const std::shared_ptr<DB>& db) {
if (g_pika_conf->slotmigrate() != true) {
return;
}
std::string type;
if (GetKeyType(key, type, db) < 0) {
LOG(WARNING) << "SRem key: " << key << " from slotKey error";
return;
}
std::string slotKey = GetSlotKey(GetSlotID(g_pika_conf->default_slot_num(), key));
int32_t count = 0;
std::vector<std::string> members(1, type + key);
rocksdb::Status s = db->storage()->SRem(slotKey, members, &count);
if (!s.ok()) {
LOG(WARNING) << "SRem key: " << key << " from slotKey, error: " << s.ToString();
return;
}
}
int GetKeyType(const std::string& key, std::string& key_type, const std::shared_ptr<DB>& db) {
std::vector<std::string> type_str(1);
rocksdb::Status s = db->storage()->GetType(key, true, type_str);
if (!s.ok()) {
LOG(WARNING) << "Get key type error: " << key << " " << s.ToString();
key_type = "";
return -1;
}
if (type_str[0] == "string") {
key_type = "k";
} else if (type_str[0] == "hash") {
key_type = "h";
} else if (type_str[0] == "list") {
key_type = "l";
} else if (type_str[0] == "set") {
key_type = "s";
} else if (type_str[0] == "zset") {
key_type = "z";
} else {
LOG(WARNING) << "Get key type error: " << key;
key_type = "";
return -1;
}
return 1;
}
// get slotstagkey by key
std::string GetSlotsTagKey(uint32_t crc) {
return SlotTagPrefix + std::to_string(crc);
}
// delete key from db && cache
int DeleteKey(const std::string& key, const char key_type, const std::shared_ptr<DB>& db) {
int32_t res = 0;
std::string slotKey = GetSlotKey(GetSlotID(g_pika_conf->default_slot_num(), key));
// delete slotkey
std::vector<std::string> members;
members.emplace_back(key_type + key);
rocksdb::Status s = db->storage()->SRem(slotKey, members, &res);
if (!s.ok()) {
if (s.IsNotFound()) {
LOG(INFO) << "Del key Srem key " << key << " not found";
return 0;
} else {
LOG(WARNING) << "Del key Srem key: " << key << " from slotKey, error: " << strerror(errno);
return -1;
}
}
// delete from cache
if (PIKA_CACHE_NONE != g_pika_conf->cache_model()
&& PIKA_CACHE_STATUS_OK == db->cache()->CacheStatus()) {
db->cache()->Del(members);
}
// delete key from db
members.clear();
members.emplace_back(key);
std::map<storage::DataType, storage::Status> type_status;
int64_t del_nums = db->storage()->Del(members, &type_status);
if (0 > del_nums) {
LOG(WARNING) << "Del key: " << key << " at slot " << GetSlotID(g_pika_conf->default_slot_num(), key) << " error";
return -1;
}
return 1;
}
void SlotsMgrtTagSlotCmd::DoInitial() {
if (!CheckArg(argv_.size())) {
res_.SetRes(CmdRes::kWrongNum, kCmdNameSlotsMgrtTagSlot);
return;
}
// Remember the first args is the opt name
auto it = argv_.begin() + 1;
dest_ip_ = *it++;
pstd::StringToLower(dest_ip_);
std::string str_dest_port = *it++;
if (!pstd::string2int(str_dest_port.data(), str_dest_port.size(), &dest_port_)) {
std::string detail = "invalid port number " + std::to_string(dest_port_);
res_.SetRes(CmdRes::kErrOther, detail);
return;
}
if (dest_port_ < 0 || dest_port_ > 65535) {
std::string detail = "invalid port number " + std::to_string(dest_port_);
res_.SetRes(CmdRes::kErrOther, detail);
return;
}
if ((dest_ip_ == "127.0.0.1" || dest_ip_ == g_pika_server->host()) && dest_port_ == g_pika_server->port()) {
res_.SetRes(CmdRes::kErrOther, "destination address error");
return;
}
std::string str_timeout_ms = *it++;
if (!pstd::string2int(str_timeout_ms.data(), str_timeout_ms.size(), &timeout_ms_)) {
res_.SetRes(CmdRes::kInvalidInt);
return;
}
if (timeout_ms_ < 0) {
std::string detail = "invalid timeout number " + std::to_string(timeout_ms_);
res_.SetRes(CmdRes::kErrOther, detail);
return;
}
if (timeout_ms_ == 0) {
timeout_ms_ = 100;
}
std::string str_slot_num = *it++;
if (!pstd::string2int(str_slot_num.data(), str_slot_num.size(), &slot_id_)) {
res_.SetRes(CmdRes::kInvalidInt);
return;
}
if (slot_id_ < 0 || slot_id_ >= g_pika_conf->default_slot_num()) {
std::string detail = "invalid slot number " + std::to_string(slot_id_);
res_.SetRes(CmdRes::kErrOther, detail);
return;
}
}
void SlotsMgrtTagSlotCmd::Do() {
if (g_pika_conf->slotmigrate() != true) {
LOG(WARNING) << "Not in slotmigrate mode";
res_.SetRes(CmdRes::kErrOther, "not set slotmigrate");
return;
}
int32_t len = 0;
int ret = 0;
std::string detail;
std::string slot_key = GetSlotKey(static_cast<int32_t>(slot_id_));
// first, get the count of slot_key, prevent to sscan key very slowly when the key is not found
rocksdb::Status s = db_->storage()->SCard(slot_key, &len);
if (len < 0) {
detail = "Get the len of slot Error";
}
// mutex between SlotsMgrtTagSlotCmd、SlotsMgrtTagOneCmd and migrator_thread
if (len > 0 && g_pika_server->pika_migrate_->Trylock()) {
g_pika_server->pika_migrate_->CleanMigrateClient();
int64_t next_cursor = 0;
std::vector<std::string> members;
rocksdb::Status s = db_->storage()->SScan(slot_key, 0, "*", 1, &members, &next_cursor);
if (s.ok()) {
for (const auto &member : members) {
std::string key = member;
char type = key.at(0);
key.erase(key.begin());
ret = SlotsMgrtTag(dest_ip_, static_cast<int32_t>(dest_port_), static_cast<int32_t>(timeout_ms_), key, type, detail, db_);
}
}
// unlock
g_pika_server->pika_migrate_->Unlock();
} else {
LOG(WARNING) << "pika migrate is running, try again later, slot_id_: " << slot_id_;
}
if (ret == 0) {
LOG(WARNING) << "slots migrate without tag failed, slot_id_: " << slot_id_ << ", detail: " << detail;
}
if (len >= 0 && ret >= 0) {
res_.AppendArrayLen(2);
// the number of keys migrated
res_.AppendInteger(ret);
// the number of keys remained
res_.AppendInteger(len - ret);
} else {
res_.SetRes(CmdRes::kErrOther, detail);
}
return;
}
// check key type
int SlotsMgrtTagOneCmd::KeyTypeCheck(const std::shared_ptr<DB>& db) {
std::vector<std::string> type_str(1);
rocksdb::Status s = db->storage()->GetType(key_, true, type_str);
if (!s.ok()) {
if (s.IsNotFound()) {
LOG(WARNING) << "Migrate slot key " << key_ << " not found";
res_.AppendInteger(0);
} else {
LOG(WARNING) << "Migrate slot key: " << key_ << " error: " << s.ToString();
res_.SetRes(CmdRes::kErrOther, "migrate slot error");
}
return -1;
}
if (type_str[0] == "string") {
key_type_ = 'k';
} else if (type_str[0] == "hash") {
key_type_ = 'h';
} else if (type_str[0] == "list") {
key_type_ = 'l';
} else if (type_str[0] == "set") {
key_type_ = 's';
} else if (type_str[0] == "zset") {
key_type_ = 'z';
} else {
LOG(WARNING) << "Migrate slot key: " << key_ << " not found";
res_.AppendInteger(0);
return -1;
}
return 0;
}
void SlotsMgrtTagOneCmd::DoInitial() {
if (!CheckArg(argv_.size())) {
res_.SetRes(CmdRes::kWrongNum, kCmdNameSlotsMgrtTagSlot);
return;
}
// Remember the first args is the opt name
auto it = argv_.begin() + 1;
dest_ip_ = *it++;
pstd::StringToLower(dest_ip_);
std::string str_dest_port = *it++;
if (!pstd::string2int(str_dest_port.data(), str_dest_port.size(), &dest_port_)) {
std::string detail = "invalid port number " + std::to_string(dest_port_);
res_.SetRes(CmdRes::kErrOther, detail);
return;
}
if (dest_port_ < 0 || dest_port_ > 65535) {
std::string detail = "invalid port number " + std::to_string(dest_port_);
res_.SetRes(CmdRes::kErrOther, detail);
return;
}
if ((dest_ip_ == "127.0.0.1" || dest_ip_ == g_pika_server->host()) && dest_port_ == g_pika_server->port()) {
res_.SetRes(CmdRes::kErrOther, "destination address error");
return;
}
std::string str_timeout_ms = *it++;
if (!pstd::string2int(str_timeout_ms.data(), str_timeout_ms.size(), &timeout_ms_)) {
res_.SetRes(CmdRes::kInvalidInt);
return;
}
if (timeout_ms_ < 0) {
std::string detail = "invalid timeout number " + std::to_string(timeout_ms_);
res_.SetRes(CmdRes::kErrOther, detail);
return;
}
if (timeout_ms_ == 0) {
timeout_ms_ = 100;
}
key_ = *it++;
}
void SlotsMgrtTagOneCmd::Do() {
if (!g_pika_conf->slotmigrate()) {
LOG(WARNING) << "Not in slotmigrate mode";
res_.SetRes(CmdRes::kErrOther, "not set slotmigrate");
return;
}