-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredisxslot.c
1338 lines (1204 loc) · 46.6 KB
/
redisxslot.c
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) 2023, weedge <weege007 at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "redisxslot.h"
slots_meta_info g_slots_meta_info;
db_slot_info* db_slot_infos;
// declare defined static var to inner use (private prototypes)
static RedisModuleDict* slotsmgrt_cached_ctx_connects;
static pthread_mutex_t slotsmgrt_cached_ctx_connects_lock
= PTHREAD_MUTEX_INITIALIZER;
// rm_call big locker, need change redis struct to support multi threads :|
// so (*mgrt*)/restore job should async block run,
// splite batch todo, don't or less block other cmd run :)
// if change redis struct, use RedisModule_ThreadSafeContextLock GIL instead it.
// static pthread_mutex_t rm_call_lock = PTHREAD_MUTEX_INITIALIZER;
// declare static function to inner use (private prototypes)
static const char* slots_tag(const char* s, int* plen);
uint64_t dictModuleStrHash(const void* key) {
size_t len;
const char* buf = RedisModule_StringPtrLen(key, &len);
return m_dictGenHashFunction(buf, (int)len);
}
int dictModuleStrKeyCompare(void* privdata, const void* key1,
const void* key2) {
size_t l1, l2;
DICT_NOTUSED(privdata);
const char* buf1 = RedisModule_StringPtrLen(key1, &l1);
const char* buf2 = RedisModule_StringPtrLen(key2, &l2);
if (l1 != l2)
return 0;
return memcmp(buf1, buf2, l1) == 0;
}
void dictModuleKeyDestructor(void* privdata, void* val) {
DICT_NOTUSED(privdata);
if (val) {
RedisModule_FreeString(NULL, val);
}
}
void dictModuleValueDestructor(void* privdata, void* val) {
DICT_NOTUSED(privdata);
if (val) {
RedisModule_FreeString(NULL, val);
}
}
m_dictType hashSlotDictType = {
dictModuleStrHash, /* hash function */
NULL, /* key dup */
NULL, /* val dup */
dictModuleStrKeyCompare, /* key compare */
dictModuleKeyDestructor, /* key destructor */
dictModuleValueDestructor /* val destructor */
};
void Slots_Init(RedisModuleCtx* ctx, uint32_t hash_slots_size, int databases,
int num_threads, int activerehashing, int async,
const char* async_cpulist) {
crc32_init();
g_slots_meta_info.hash_slots_size = hash_slots_size;
g_slots_meta_info.databases = databases;
g_slots_meta_info.async = async;
g_slots_meta_info.async_cpulist = async_cpulist;
g_slots_meta_info.activerehashing = activerehashing;
g_slots_meta_info.cronloops = 0;
// worker thread pool for each indepence task, less mutex case.
// if more mutex, maybe don't use it. want to learn, open it :)
// g_slots_meta_info.slots_dump_threads = num_threads;
g_slots_meta_info.slots_mgrt_threads = num_threads;
// g_slots_meta_info.slots_restore_threads = num_threads;
/* like bio define diff type job thread, just one type job thread todo. no
* mutex, but no wait, so use async job, such as async net/disk io */
db_slot_infos = RedisModule_Alloc(sizeof(db_slot_info) * databases);
for (int j = 0; j < databases; j++) {
db_slot_infos[j].slotkey_tables
= RedisModule_Alloc(sizeof(dict*) * hash_slots_size);
db_slot_infos[j].slotkey_table_rwlocks
= RedisModule_Alloc(sizeof(pthread_rwlock_t) * hash_slots_size);
for (uint32_t i = 0; i < hash_slots_size; i++) {
db_slot_infos[j].slotkey_tables[i]
= m_dictCreate(&hashSlotDictType, NULL);
pthread_rwlock_init(&(db_slot_infos[j].slotkey_table_rwlocks[i]),
NULL);
}
db_slot_infos[j].slotkey_table_rehashing = 0;
db_slot_infos[j].tagged_key_list = m_zslCreate();
pthread_rwlock_init(&(db_slot_infos[j].tagged_key_list_rwlock), NULL);
}
slotsmgrt_cached_ctx_connects = RedisModule_CreateDict(ctx);
}
void Slots_Free(RedisModuleCtx* ctx) {
RedisModule_Log(ctx, "notice", "slots free");
for (int j = 0; j < g_slots_meta_info.databases; j++) {
if (db_slot_infos != NULL && db_slot_infos[j].slotkey_tables != NULL) {
for (uint32_t i = 0; i < g_slots_meta_info.hash_slots_size; i++) {
pthread_rwlock_wrlock(
&(db_slot_infos[j].slotkey_table_rwlocks[i]));
m_dictRelease(db_slot_infos[j].slotkey_tables[i]);
pthread_rwlock_unlock(
&(db_slot_infos[j].slotkey_table_rwlocks[i]));
pthread_rwlock_destroy(
&(db_slot_infos[j].slotkey_table_rwlocks[i]));
}
RedisModule_Free(db_slot_infos[j].slotkey_tables);
db_slot_infos[j].slotkey_tables = NULL;
RedisModule_Free(db_slot_infos[j].slotkey_table_rwlocks);
db_slot_infos[j].slotkey_table_rwlocks = NULL;
}
if (db_slot_infos != NULL && db_slot_infos[j].tagged_key_list != NULL) {
pthread_rwlock_wrlock(&(db_slot_infos[j].tagged_key_list_rwlock));
m_zslFree(db_slot_infos[j].tagged_key_list);
pthread_rwlock_unlock(&(db_slot_infos[j].tagged_key_list_rwlock));
db_slot_infos[j].tagged_key_list = NULL;
pthread_rwlock_destroy(&(db_slot_infos[j].tagged_key_list_rwlock));
}
}
if (db_slot_infos != NULL) {
RedisModule_Free(db_slot_infos);
db_slot_infos = NULL;
}
if (slotsmgrt_cached_ctx_connects != NULL) {
RedisModule_FreeDict(ctx, slotsmgrt_cached_ctx_connects);
slotsmgrt_cached_ctx_connects = NULL;
}
}
/*
* params s key, pcrc crc32 sum, phastag has tag
* return slot num
*/
int slots_num(const char* s, uint32_t* pcrc, int* phastag) {
int taglen;
int hastag = 0;
const char* tag = slots_tag(s, &taglen);
if (tag == NULL) {
tag = s, taglen = strlen(s);
} else {
hastag = 1;
}
uint32_t crc = crc32_checksum(tag, taglen);
if (pcrc != NULL) {
*pcrc = crc;
}
if (phastag != NULL) {
*phastag = hastag;
}
return crc & (g_slots_meta_info.hash_slots_size - 1);
}
/*
* params s key, plen tag len
* return tag start pos char *
*/
static const char* slots_tag(const char* s, int* plen) {
int i, j, n = strlen(s);
for (i = 0; i < n && s[i] != '{'; i++) {
}
if (i == n) {
return NULL;
}
i++;
for (j = i; j < n && s[j] != '}'; j++) {
}
if (j == n) {
return NULL;
}
if (plen != NULL) {
*plen = j - i;
}
return s + i;
}
static time_t get_unixtime(void) {
#if (REDIS_VERSION == 70200)
return (time_t)(RedisModule_CachedMicroseconds() / 1e6);
#endif
return (time_t)(RedisModule_Milliseconds() / 1e3);
}
static long long getTid() {
#ifdef __APPLE__
__uint64_t tid;
pthread_threadid_np(NULL, &tid);
return (long long)tid;
#else
return (long long)syscall(__NR_gettid);
#endif
}
// getConnName
// return {host}:{port}@{thread_id}
static sds getConnName(const sds host, const sds port) {
sds name = sdsempty();
name = sdscatlen(name, host, sdslen(host));
name = sdscatlen(name, ":", 1);
name = sdscatlen(name, port, sdslen(port));
char buf[REDIS_LONGSTR_SIZE];
long long tid = getTid();
// long long tid = (long long)pthread_self();
m_ll2string(buf, sizeof(buf), tid);
name = sdscatlen(name, "@", 1);
name = sdscatlen(name, buf, strlen(buf));
return name;
}
static db_slot_mgrt_connect* SlotsMGRT_GetConnCtx(RedisModuleCtx* ctx,
slot_mgrt_connet_meta* meta) {
time_t unixtime = get_unixtime();
sds name = getConnName(meta->host, meta->port);
db_slot_mgrt_connect* conn = NULL;
pthread_mutex_lock(&slotsmgrt_cached_ctx_connects_lock);
// conn = m_dictFetchValue(slotsmgrt_cached_ctx_connects, name);
conn = RedisModule_DictGetC(slotsmgrt_cached_ctx_connects, (void*)name,
sdslen(name), NULL);
pthread_mutex_unlock(&slotsmgrt_cached_ctx_connects_lock);
if (conn != NULL) {
sdsfree(name);
conn->last_time = unixtime;
return conn;
}
redisContext* c = redisConnect(meta->host, atoi(meta->port));
if (c->err) {
char errLog[200];
sprintf(errLog, "Err: slotsmgrt connect to target %s, error = '%s'",
name, c->errstr);
RedisModule_Log(ctx, "warning", "%s", errLog);
sdsfree(name);
return NULL;
}
redisSetTimeout(c, meta->timeout);
RedisModule_Log(
ctx, "notice", "slotsmgrt: connect to target %s set timeout: %ld.%ld s",
name, meta->timeout.tv_sec, (long int)meta->timeout.tv_usec);
conn = RedisModule_Alloc(sizeof(db_slot_mgrt_connect));
conn->conn_ctx = c;
conn->last_time = unixtime;
conn->meta = meta;
pthread_mutex_lock(&slotsmgrt_cached_ctx_connects_lock);
// m_dictAdd(slotsmgrt_cached_ctx_connects, name, conn);
RedisModule_DictSetC(slotsmgrt_cached_ctx_connects, (void*)name,
sdslen(name), conn);
pthread_mutex_unlock(&slotsmgrt_cached_ctx_connects_lock);
sdsfree(name);
return conn;
}
static void SlotsMGRT_CloseConn(RedisModuleCtx* ctx,
slot_mgrt_connet_meta* meta) {
sds name = getConnName(meta->host, meta->port);
pthread_mutex_lock(&slotsmgrt_cached_ctx_connects_lock);
// db_slot_mgrt_connect* conn =
// m_dictFetchValue(slotsmgrt_cached_ctx_connects, name);
db_slot_mgrt_connect* conn = RedisModule_DictGetC(
slotsmgrt_cached_ctx_connects, (void*)name, sdslen(name), NULL);
pthread_mutex_unlock(&slotsmgrt_cached_ctx_connects_lock);
if (conn == NULL) {
RedisModule_Log(ctx, "warning", "slotsmgrt: close target %s again",
name);
sdsfree(name);
return;
}
RedisModule_Log(ctx, "notice", "slotsmgrt: close target %s ok", name);
pthread_mutex_lock(&slotsmgrt_cached_ctx_connects_lock);
// m_dictDelete(slotsmgrt_cached_ctx_connects, name);
RedisModule_DictDelC(slotsmgrt_cached_ctx_connects, (void*)name,
sdslen(name), NULL);
pthread_mutex_unlock(&slotsmgrt_cached_ctx_connects_lock);
redisFree(conn->conn_ctx);
RedisModule_Free(conn);
conn = NULL;
sdsfree(name);
}
// SlotsMGRT_CloseTimedoutConns
// like migrateCloseTimedoutSockets
// for server cron job to check timeout connect
void SlotsMGRT_CloseTimedoutConns(RedisModuleCtx* ctx) {
// maybe use cached server cron time, a little faster.
time_t unixtime = get_unixtime();
pthread_mutex_lock(&slotsmgrt_cached_ctx_connects_lock);
// m_dictIterator* di =
// m_dictGetSafeIterator(slotsmgrt_cached_ctx_connects);
RedisModuleDictIter* di = RedisModule_DictIteratorStartC(
slotsmgrt_cached_ctx_connects, "^", NULL, 0);
void* k;
db_slot_mgrt_connect* conn;
// m_dictEntry* de;
// while ((de = dictNext(di)) != NULL) {
// k = dictGetKey(de);
// conn = dictGetVal(de);
size_t keyLen;
while ((k = RedisModule_DictNextC(di, &keyLen, (void**)&conn))) {
if ((unixtime - conn->last_time) > MGRT_BATCH_KEY_TIMEOUT) {
RedisModule_Log(
ctx, "notice",
"slotsmgrt: timeout target %s, lasttime = %ld, now = %ld",
(sds)k, conn->last_time, unixtime);
// m_dictDelete(slotsmgrt_cached_ctx_connects, k);
RedisModule_DictDelC(slotsmgrt_cached_ctx_connects, k,
strlen((sds)k), NULL);
redisFree(conn->conn_ctx);
RedisModule_Free(conn);
conn = NULL;
}
}
// m_dictReleaseIterator(di);
RedisModule_DictIteratorStop(di);
pthread_mutex_unlock(&slotsmgrt_cached_ctx_connects_lock);
}
static void freeHiRedisSlotsRestoreArgs(char** argv, size_t* argvlen, int n) {
for (int i = 0; i < n; i++) {
RedisModule_Free(argv[i * 3 + 1]);
}
RedisModule_Free(argv);
RedisModule_Free(argvlen);
}
/*
* err return SLOTS_MGRT_ERR, ok return obj cn,
*/
static int doSplitRestoreCommand(RedisModuleCtx* ctx,
db_slot_mgrt_connect* conn, char** argv,
size_t* argvlen, int start_pos, int end_pos) {
int obj_cn = end_pos - start_pos;
if (obj_cn <= 0) {
return SLOTS_MGRT_NOTHING;
}
// alloc with memory alignment, so sizeof(char*) * 3 * obj_cn + 1 is ok
char** sub_argv = RedisModule_Alloc(sizeof(char*) * (3 * obj_cn + 1));
size_t* sub_argvlen = RedisModule_Alloc(sizeof(size_t) * (3 * obj_cn + 1));
sub_argv[0] = "SLOTSRESTORE";
// cp pointer
memcpy(&sub_argv[1], &argv[start_pos * 3], sizeof(char*) * obj_cn * 3);
sub_argvlen[0] = strlen(sub_argv[0]);
memcpy(&sub_argvlen[1], &argvlen[start_pos * 3],
sizeof(size_t) * obj_cn * 3);
redisReply* rr
= redisCommandArgv(conn->conn_ctx, 3 * obj_cn + 1,
(const char**)sub_argv, (const size_t*)sub_argvlen);
if (conn->conn_ctx->err) {
RedisModule_Log(ctx, "warning", "errno %d errstr %s",
conn->conn_ctx->err, conn->conn_ctx->errstr);
freeHiRedisSlotsRestoreArgs(sub_argv, sub_argvlen, 0);
return SLOTS_MGRT_ERR;
}
if (rr == NULL) {
RedisModule_Log(ctx, "warning", "reply is NULL");
freeHiRedisSlotsRestoreArgs(sub_argv, sub_argvlen, 0);
return SLOTS_MGRT_ERR;
}
if (rr->type == REDIS_REPLY_ERROR) {
RedisModule_Log(ctx, "warning", "reply err %s", rr->str);
freeReplyObject(rr);
freeHiRedisSlotsRestoreArgs(sub_argv, sub_argvlen, 0);
return SLOTS_MGRT_ERR;
}
RedisModule_Log(ctx, "notice", "start_pos %d end_pos %d send ok", start_pos,
end_pos);
freeReplyObject(rr);
freeHiRedisSlotsRestoreArgs(sub_argv, sub_argvlen, 0);
return obj_cn;
}
static void doSplitRestoreCmdTask(void* arg) {
RedisModuleCtx* ctx = RedisModule_GetThreadSafeContext(NULL);
slots_split_restore_params* params = (slots_split_restore_params*)arg;
db_slot_mgrt_connect* conn = SlotsMGRT_GetConnCtx(ctx, params->meta);
if (conn == NULL) {
params->result_code = SLOTS_MGRT_ERR;
return;
}
// todo auth
redisReply* rr;
rr = redisCommand(conn->conn_ctx, "SELECT %d", params->meta->db);
if (rr == NULL || rr->type == REDIS_REPLY_ERROR) {
if (rr != NULL) {
freeReplyObject(rr);
}
params->result_code = SLOTS_MGRT_ERR;
return;
}
freeReplyObject(rr);
params->result_code
= doSplitRestoreCommand(ctx, conn, params->argv, params->argvlen,
params->start_pos, params->end_pos);
conn->last_time = get_unixtime();
SlotsMGRT_CloseConn(ctx, params->meta);
RedisModule_FreeThreadSafeContext(ctx);
}
static int BatchSendWithThreadPool_SlotsRestore(RedisModuleCtx* ctx,
slot_mgrt_connet_meta* meta,
rdb_dump_obj* objs[], int n) {
UNUSED(ctx);
threadpool thpool = thpool_init(g_slots_meta_info.slots_mgrt_threads);
slots_split_restore_params* params
= RedisModule_Alloc(sizeof(slots_split_restore_params) * n);
int params_cn = 0;
// char* argv[3 * n];
char** argv = RedisModule_Alloc(sizeof(char*) * 3 * n);
// size_t argvlen[3 * n];
size_t* argvlen = RedisModule_Alloc(sizeof(size_t) * 3 * n);
char buf[REDIS_LONGSTR_SIZE];
size_t cmd_size = 0;
int start_pos = 0;
for (int i = 0; i < n; i++) {
// split cmd (bigkey? if async block mgrt, maybe don't think this)
if (cmd_size > REDIS_MGRT_CMD_PARAMS_SIZE) {
params[params_cn].meta = meta;
params[params_cn].argv = argv;
params[params_cn].argvlen = argvlen;
params[params_cn].start_pos = start_pos;
params[params_cn].end_pos = i;
params[params_cn].result_code = 0;
thpool_add_work(thpool, doSplitRestoreCmdTask,
(void*)¶ms[params_cn]);
params_cn++;
cmd_size = 0;
start_pos = i;
}
size_t ksz, vsz;
argv[i * 3 + 0] = (char*)RedisModule_StringPtrLen(objs[i]->key, &ksz);
argvlen[i * 3 + 0] = ksz;
cmd_size += argvlen[i * 3 + 0];
time_t ttlms = objs[i]->ttlms > 0 ? objs[i]->ttlms : 0;
argvlen[i * 3 + 1] = m_ll2string(buf, sizeof(buf), (long long)ttlms);
argv[i * 3 + 1] = RedisModule_Strdup(buf);
cmd_size += argvlen[i * 3 + 1];
argv[i * 3 + 2] = (char*)RedisModule_StringPtrLen(objs[i]->val, &vsz);
argvlen[i * 3 + 2] = vsz;
cmd_size += argvlen[i * 3 + 2];
}
params[params_cn].meta = meta;
params[params_cn].argv = argv;
params[params_cn].argvlen = argvlen;
params[params_cn].start_pos = start_pos;
params[params_cn].end_pos = n;
params[params_cn].result_code = 0;
thpool_add_work(thpool, doSplitRestoreCmdTask, (void*)¶ms[params_cn]);
params_cn++;
thpool_wait(thpool);
thpool_destroy(thpool);
for (int i = 0; i < params_cn; i++) {
if (params[i].result_code == SLOTS_MGRT_ERR) {
freeHiRedisSlotsRestoreArgs(argv, argvlen, n);
RedisModule_Free(params);
return SLOTS_MGRT_ERR;
}
}
freeHiRedisSlotsRestoreArgs(argv, argvlen, n);
RedisModule_Free(params);
return n;
}
static int BatchSend_SlotsRestore(RedisModuleCtx* ctx,
db_slot_mgrt_connect* conn,
rdb_dump_obj* objs[], int n) {
// char* argv[3 * n];
char** argv = RedisModule_Alloc(sizeof(char*) * 3 * n);
// size_t argvlen[3 * n];
size_t* argvlen = RedisModule_Alloc(sizeof(size_t) * 3 * n);
char buf[REDIS_LONGSTR_SIZE];
size_t cmd_size = 0;
int start_pos = 0;
for (int i = 0; i < n; i++) {
// split cmd to send,(todo: bigkey)
if (cmd_size > REDIS_MGRT_CMD_PARAMS_SIZE) {
if (doSplitRestoreCommand(ctx, conn, argv, argvlen, start_pos, i)
== SLOTS_MGRT_ERR) {
freeHiRedisSlotsRestoreArgs(argv, argvlen, i - start_pos);
return SLOTS_MGRT_ERR;
}
cmd_size = 0;
start_pos = i;
}
size_t ksz, vsz;
argv[i * 3 + 0] = (char*)RedisModule_StringPtrLen(objs[i]->key, &ksz);
argvlen[i * 3 + 0] = ksz;
cmd_size += argvlen[i * 3 + 0];
time_t ttlms = objs[i]->ttlms > 0 ? objs[i]->ttlms : 0;
argvlen[i * 3 + 1] = m_ll2string(buf, sizeof(buf), (long long)ttlms);
argv[i * 3 + 1] = RedisModule_Strdup(buf);
cmd_size += argvlen[i * 3 + 1];
argv[i * 3 + 2] = (char*)RedisModule_StringPtrLen(objs[i]->val, &vsz);
argvlen[i * 3 + 2] = vsz;
cmd_size += argvlen[i * 3 + 2];
}
if (doSplitRestoreCommand(ctx, conn, argv, argvlen, start_pos, n)
== SLOTS_MGRT_ERR) {
freeHiRedisSlotsRestoreArgs(argv, argvlen, n);
return SLOTS_MGRT_ERR;
}
conn->last_time = get_unixtime();
freeHiRedisSlotsRestoreArgs(argv, argvlen, n);
return n;
}
static int doSplitPipelineGetReply(RedisModuleCtx* ctx,
db_slot_mgrt_connect* conn, int start_pos,
int end_pos) {
UNUSED(ctx);
int n = end_pos - start_pos;
if (n <= 0) {
return SLOTS_MGRT_NOTHING;
}
redisReply** rr = RedisModule_Alloc(sizeof(redisReply*) * n);
for (int i = 0; i < n; i++) {
int r = redisGetReply(conn->conn_ctx, (void*)&rr[i]);
if (r == REDIS_ERR) {
RedisModule_Log(
ctx, "warning",
"[%s %d] start_pos %d end_pos %d pos: %d pipeline send fail!",
__FILE__, __LINE__, start_pos, end_pos, i - 1);
for (int j = 0; j < i; j++)
freeReplyObject(rr[j]);
RedisModule_Free(rr);
return SLOTS_MGRT_ERR;
}
if (rr[i] == NULL) {
RedisModule_Log(
ctx, "warning",
"[%s %d] start_pos %d end_pos %d pos: %d pipeline send fail!",
__FILE__, __LINE__, start_pos, end_pos, i - 1);
for (int j = 0; j < i; j++)
freeReplyObject(rr[j]);
RedisModule_Free(rr);
return SLOTS_MGRT_ERR;
}
if (rr[i]->type == REDIS_REPLY_ERROR) {
RedisModule_Log(
ctx, "warning",
"[%s %d] start_pos %d end_pos %d pos: %d pipeline send fail!",
__FILE__, __LINE__, start_pos, end_pos, i);
for (int j = 0; j <= i; j++)
freeReplyObject(rr[j]);
RedisModule_Free(rr);
return SLOTS_MGRT_ERR;
}
}
for (int j = 0; j < n; j++) {
freeReplyObject(rr[j]);
}
RedisModule_Free(rr);
RedisModule_Log(ctx, "notice", "start_pos %d end_pos %d pipeline send ok",
start_pos, end_pos);
return n;
}
static int Pipeline_SlotsRestore(RedisModuleCtx* ctx,
db_slot_mgrt_connect* conn,
rdb_dump_obj* objs[], int n) {
UNUSED(ctx);
char buf[REDIS_LONGSTR_SIZE];
size_t cmd_size = 0, ksz = 0, vsz = 0, tsz = 0;
int start_pos = 0;
for (int i = 0; i < n; i++) {
// split cmd to send,(todo: bigkey)
if (cmd_size > REDIS_MGRT_CMD_PARAMS_SIZE) {
if (doSplitPipelineGetReply(ctx, conn, start_pos, i)
== SLOTS_MGRT_ERR) {
return SLOTS_MGRT_ERR;
}
cmd_size = 0;
start_pos = i;
}
const char* k = RedisModule_StringPtrLen(objs[i]->key, &ksz);
cmd_size += ksz;
const char* v = RedisModule_StringPtrLen(objs[i]->val, &vsz);
cmd_size += vsz;
time_t ttlms = objs[i]->ttlms > 0 ? objs[i]->ttlms : 0;
tsz = m_ll2string(buf, sizeof(buf), (long long)ttlms);
cmd_size += tsz;
redisAppendCommand(conn->conn_ctx, "SLOTSRESTORE %b %ld %b", k, ksz,
ttlms, v, vsz);
}
if (doSplitPipelineGetReply(ctx, conn, start_pos, n) == SLOTS_MGRT_ERR) {
return SLOTS_MGRT_ERR;
}
return n;
}
// MGRT
// batch migrate send to host:port with r/w timeout,
// use withpipeline use redis self restore to migrate,
// default with SlotsRestore.
// return value:
// -1 - error happens
// >=0 - # of success migration (0 or n)
static int MGRT(RedisModuleCtx* ctx, const sds host, const sds port,
time_t timeoutMS, rdb_dump_obj* objs[], int n, sds mgrtType) {
int db = RedisModule_GetSelectedDb(ctx);
struct timeval timeout
= {.tv_sec = timeoutMS / 1000, .tv_usec = (timeoutMS % 1000) * 1000};
slot_mgrt_connet_meta meta
= {.db = db, .host = host, .port = port, .timeout = timeout};
// if use thread pool, each worker thread new one connect to mgrt
if (g_slots_meta_info.slots_mgrt_threads > 0) {
int ret = BatchSendWithThreadPool_SlotsRestore(ctx, &meta, objs, n);
return ret;
}
db_slot_mgrt_connect* conn = SlotsMGRT_GetConnCtx(ctx, &meta);
if (conn == NULL) {
return SLOTS_MGRT_ERR;
}
// todo auth
redisReply* rr;
rr = redisCommand(conn->conn_ctx, "SELECT %d", db);
if (rr == NULL || rr->type == REDIS_REPLY_ERROR) {
if (rr != NULL) {
freeReplyObject(rr);
}
SlotsMGRT_CloseConn(ctx, &meta);
return SLOTS_MGRT_ERR;
}
freeReplyObject(rr);
if (mgrtType != NULL && strcasecmp(mgrtType, "withpipeline") == 0
&& !g_slots_meta_info.async) {
int ret = Pipeline_SlotsRestore(ctx, conn, objs, n);
SlotsMGRT_CloseConn(ctx, &meta);
return ret;
}
int ret = BatchSend_SlotsRestore(ctx, conn, objs, n);
SlotsMGRT_CloseConn(ctx, &meta);
return ret;
}
// dumpObj
// return 0 nothing todo -1 error happens; if dump ok, return a new dump obj
static int dumpObj(RedisModuleCtx* ctx, RedisModuleString* key,
rdb_dump_obj** obj) {
ASYNC_LOCK(ctx);
RedisModuleCallReply* reply = RedisModule_Call(ctx, "DUMP", "s", key);
ASYNC_UNLOCK(ctx);
if (reply == NULL)
return SLOTS_MGRT_NOTHING;
int type = RedisModule_CallReplyType(reply);
if (type == REDISMODULE_REPLY_NULL) {
RedisModule_FreeCallReply(reply);
return SLOTS_MGRT_NOTHING;
}
if (type != REDISMODULE_REPLY_STRING) {
RedisModule_FreeCallReply(reply);
return SLOTS_MGRT_ERR;
}
RedisModuleString* val = RedisModule_CreateStringFromCallReply(reply);
RedisModule_FreeCallReply(reply);
ASYNC_LOCK(ctx);
reply = RedisModule_Call(ctx, "PTTL", "s", key);
ASYNC_UNLOCK(ctx);
if (reply == NULL)
return SLOTS_MGRT_NOTHING;
type = RedisModule_CallReplyType(reply);
if (type == REDISMODULE_REPLY_NULL) {
RedisModule_FreeCallReply(reply);
return SLOTS_MGRT_NOTHING;
}
if (type != REDISMODULE_REPLY_INTEGER) {
RedisModule_FreeCallReply(reply);
return SLOTS_MGRT_ERR;
}
long long ttlms = RedisModule_CallReplyInteger(reply);
RedisModule_FreeCallReply(reply);
rdb_dump_obj* a_obj = RedisModule_Alloc(sizeof(rdb_dump_obj));
a_obj->key = key;
a_obj->ttlms = ttlms;
a_obj->val = val;
*obj = a_obj;
return 1;
}
static void dumpObjTask(void* arg) {
dump_obj_params* params = (dump_obj_params*)arg;
RedisModuleCtx* ctx = RedisModule_GetThreadSafeContext(NULL);
params->result_code = dumpObj(ctx, params->key, params->obj);
RedisModule_FreeThreadSafeContext(ctx);
}
static int getRdbDumpObjsWithThreadPool(RedisModuleCtx* ctx,
RedisModuleString* keys[], int n,
rdb_dump_obj** objs) {
UNUSED(ctx);
if (n <= 0) {
return 0;
}
int num_threads = n > g_slots_meta_info.slots_dump_threads
? g_slots_meta_info.slots_dump_threads
: n;
dump_obj_params* params = RedisModule_Alloc(sizeof(dump_obj_params) * n);
threadpool thpool = thpool_init(num_threads);
for (int i = 0; i < n; i++) {
params[i].key = keys[i];
params[i].obj = &objs[i];
params[i].result_code = SLOTS_MGRT_NOTHING;
thpool_add_work(thpool, dumpObjTask, (void*)¶ms[i]);
}
thpool_wait(thpool);
thpool_destroy(thpool);
int j = 0;
for (int i = 0; i < n; i++) {
if (params[i].result_code == SLOTS_MGRT_NOTHING)
continue;
if (params[i].result_code == SLOTS_MGRT_ERR) {
RedisModule_Free(params);
return SLOTS_MGRT_ERR;
}
j++;
}
RedisModule_Free(params);
return j;
}
// SlotsMGRT_GetRdbDumpObjs
// return value:
// -1 - error happens
// >=0 - # of success get rdb_dump_objs num (0 or n)
// rdb_dump_obj* objs[] outsied alloc to fill rdb_dump_obj, use over to free.
static int getRdbDumpObjs(RedisModuleCtx* ctx, RedisModuleString* keys[], int n,
rdb_dump_obj** objs) {
if (n <= 0) {
return SLOTS_MGRT_NOTHING;
}
if (g_slots_meta_info.slots_dump_threads > 0) {
return getRdbDumpObjsWithThreadPool(ctx, keys, n, objs);
}
int j = 0;
for (int i = 0; i < n; i++) {
int r = dumpObj(ctx, keys[i], &objs[i]);
if (r == SLOTS_MGRT_NOTHING)
continue;
if (r == SLOTS_MGRT_ERR)
return SLOTS_MGRT_ERR;
j++;
}
return j;
}
static int delKeys(RedisModuleCtx* ctx, RedisModuleString* keys[], int n) {
RedisModuleCallReply* reply;
int ret = 0;
for (int i = 0; i < n; i++) {
ASYNC_LOCK(ctx);
// reply = RedisModule_Call(ctx, "DEL", "s", keys[i]);
reply = RedisModule_Call(ctx, "UNLINK", "s!", keys[i]);
ASYNC_UNLOCK(ctx);
int type = RedisModule_CallReplyType(reply);
if (reply == NULL)
continue;
if (type == REDISMODULE_REPLY_NULL) {
RedisModule_FreeCallReply(reply);
continue;
}
if (type != REDISMODULE_REPLY_INTEGER) {
RedisModule_FreeCallReply(reply);
return SLOTS_MGRT_ERR;
}
RedisModule_FreeCallReply(reply);
ret++;
}
return ret;
}
void FreeDumpObjs(RedisModuleCtx* ctx, rdb_dump_obj** objs, int n) {
for (int i = 0; i < n; i++) {
if (objs[i] != NULL) {
if (objs[i]->val != NULL) {
RedisModule_FreeString(ctx, objs[i]->val);
objs[i]->val = NULL;
}
RedisModule_Free(objs[i]);
objs[i] = NULL;
}
}
if (objs != NULL) {
RedisModule_Free(objs);
objs = NULL;
}
}
static double get_us(struct timeval t) {
return (t.tv_sec * 1000000 + t.tv_usec);
}
static int migrateKeys(RedisModuleCtx* ctx, const sds host, const sds port,
time_t timeoutMS, RedisModuleString* keys[], int n,
const sds mgrtType) {
if (n <= 0) {
return 0;
}
struct timeval start_time, stop_time;
// get rdb dump objs
gettimeofday(&start_time, NULL);
rdb_dump_obj** objs = RedisModule_Alloc(sizeof(rdb_dump_obj*) * n);
int ret = getRdbDumpObjs(ctx, keys, n, objs);
if (ret == SLOTS_MGRT_NOTHING) {
FreeDumpObjs(ctx, objs, ret);
return 0;
}
if (ret == SLOTS_MGRT_ERR) {
FreeDumpObjs(ctx, objs, ret);
return SLOTS_MGRT_ERR;
}
gettimeofday(&stop_time, NULL);
RedisModule_Log(ctx, "notice", "%d objs dump cost %f ms", ret,
(get_us(stop_time) - get_us(start_time)) / 1000);
// migrate
gettimeofday(&start_time, NULL);
int m_ret = MGRT(ctx, host, port, timeoutMS, objs, ret, mgrtType);
if (m_ret == SLOTS_MGRT_ERR) {
FreeDumpObjs(ctx, objs, ret);
return SLOTS_MGRT_ERR;
}
if (m_ret == 0) {
FreeDumpObjs(ctx, objs, ret);
return m_ret;
}
FreeDumpObjs(ctx, objs, ret);
gettimeofday(&stop_time, NULL);
RedisModule_Log(ctx, "notice", "%d objs mgrt cost %f ms", m_ret,
(get_us(stop_time) - get_us(start_time)) / 1000);
// del (unlink async del)
gettimeofday(&start_time, NULL);
ret = delKeys(ctx, keys, n);
if (ret == SLOTS_MGRT_ERR) {
return SLOTS_MGRT_ERR;
}
gettimeofday(&stop_time, NULL);
RedisModule_Log(ctx, "notice", "%d keys del cost %f ms", ret,
(get_us(stop_time) - get_us(start_time)) / 1000);
return ret;
}
// SlotsMGRT_OneKey
// do migrate a key-value for slotsmgrt/slotsmgrtone commands
// 1.dump key rdb obj val
// 2.batch migrate send to host:port with r/w timeout
// 3.if migrate ok, remove key
// return value:
// -1 - error happens
// >=0 - # of success migration (0 or 1)
int SlotsMGRT_OneKey(RedisModuleCtx* ctx, const char* host, const char* port,
time_t timeout, RedisModuleString* key,
const char* mgrtType) {
return migrateKeys(ctx, (const sds)host, (const sds)port, timeout,
(RedisModuleString*[]){key}, 1, (const sds)mgrtType);
}
static void notifyOne(RedisModuleCtx* ctx, RedisModuleString* key) {
ASYNC_LOCK(ctx);
RedisModuleKey* okey
= RedisModule_OpenKey(ctx, key, REDISMODULE_READ | REDISMODULE_WRITE);
// inner type notify
if (RedisModule_KeyType(okey) == REDISMODULE_KEYTYPE_STRING) {
RedisModule_NotifyKeyspaceEvent(ctx, REDISMODULE_NOTIFY_STRING,
"slotsmgrt-restore", key);
}
if (RedisModule_KeyType(okey) == REDISMODULE_KEYTYPE_HASH) {
RedisModule_NotifyKeyspaceEvent(ctx, REDISMODULE_NOTIFY_HASH,
"slotsmgrt-restore", key);
}
if (RedisModule_KeyType(okey) == REDISMODULE_KEYTYPE_LIST) {
RedisModule_NotifyKeyspaceEvent(ctx, REDISMODULE_NOTIFY_LIST,
"slotsmgrt-restore", key);
}
if (RedisModule_KeyType(okey) == REDISMODULE_KEYTYPE_SET) {
RedisModule_NotifyKeyspaceEvent(ctx, REDISMODULE_NOTIFY_SET,
"slotsmgrt-restore", key);
}
if (RedisModule_KeyType(okey) == REDISMODULE_KEYTYPE_ZSET) {
RedisModule_NotifyKeyspaceEvent(ctx, REDISMODULE_NOTIFY_ZSET,
"slotsmgrt-restore", key);
}
// todo if use outside 3rd extra type
// need to register keyspace notify and sub event
RedisModule_CloseKey(okey);
ASYNC_UNLOCK(ctx);
}
static int restoreOneWithReplace(RedisModuleCtx* ctx, rdb_dump_obj* obj) {
if (obj->ttlms < 0) {
obj->ttlms = 0;
}
const char* k = RedisModule_StringPtrLen(obj->key, NULL);
size_t vsz;
const char* v = RedisModule_StringPtrLen(obj->val, &vsz);
ASYNC_LOCK(ctx);
RedisModuleCallReply* reply = RedisModule_Call(
ctx, "RESTORE", "clbc", k, obj->ttlms, v, vsz, "replace");
ASYNC_UNLOCK(ctx);
if (reply == NULL) {
return 0;
}
int type = RedisModule_CallReplyType(reply);
if (type == REDISMODULE_REPLY_NULL) {
RedisModule_FreeCallReply(reply);
return 0;
}
if (RedisModule_CallReplyType(reply) == REDISMODULE_REPLY_ERROR) {
RedisModule_FreeCallReply(reply);
return SLOTS_MGRT_ERR;
}
notifyOne(ctx, obj->key);
RedisModule_FreeCallReply(reply);
return 1;