forked from RedisLabs/redisraft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cluster.c
1223 lines (1014 loc) · 39.2 KB
/
cluster.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
/*
* This file is part of RedisRaft.
*
* Copyright (c) 2020-2021 Redis Ltd.
*
* RedisRaft is licensed under the Redis Source Available License (RSAL).
*/
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include "redisraft.h"
#include "crc16.h"
/* -----------------------------------------------------------------------------
* Hashing code - copied directly from Redis.
* -------------------------------------------------------------------------- */
/* We have 16384 hash slots. The hash slot of a given key is obtained
* as the least significant 14 bits of the crc16 of the key.
*
* However if the key contains the {...} pattern, only the part between
* { and } is hashed. This may be useful in the future to force certain
* keys to be in the same node (assuming no resharding is in progress). */
unsigned int keyHashSlot(const char *key, int keylen) {
int s, e; /* start-end indexes of { and } */
for (s = 0; s < keylen; s++)
if (key[s] == '{') break;
/* No '{' ? Hash the whole key. This is the base case. */
if (s == keylen) return crc16_ccitt(key,keylen) & 0x3FFF;
/* '{' found? Check if we have the corresponding '}'. */
for (e = s+1; e < keylen; e++)
if (key[e] == '}') break;
/* No '}' or nothing between {} ? Hash the whole key. */
if (e == keylen || e == s+1) return crc16_ccitt(key,keylen) & 0x3FFF;
/* If we are here there is both a { and a } on its right. Hash
* what is in the middle between { and }. */
return crc16_ccitt(key+s+1,e-s-1) & 0x3FFF;
}
/* -----------------------------------------------------------------------------
* ShardGroup Handling
* -------------------------------------------------------------------------- */
/* ShardGroup serialization and deserialization is used in Raft log entries
* of type RAFT_LOGTYPE_ADD_SHARDGROUP.
*
* The format is as follows:
* <id>:<start-slot>:<end-slot>:<number-of-nodes>\n
* <node-uid>:<node host>:<node port>\n
* ...
*/
/* Serialize a ShardGroup. Returns a newly allocated null terminated buffer
* that contains the serialized form.
*/
char *ShardGroupSerialize(ShardGroup *sg)
{
size_t buf_size = SHARDGROUP_MAXLEN + (SHARDGROUPNODE_MAXLEN * sg->nodes_num) + 1;
char *buf = RedisModule_Calloc(1, buf_size);
char *p = buf;
p = catsnprintf(p, &buf_size, "%u:%u:%u:%u\n", sg->id, sg->start_slot, sg->end_slot, sg->nodes_num);
for (int i = 0; i < sg->nodes_num; i++) {
NodeAddr *addr = &sg->nodes[i].addr;
p = catsnprintf(p, &buf_size, "%s:%s:%d\n", sg->nodes[i].node_id, addr->host, addr->port);
}
return buf;
}
/* Deserialize a ShardGroup from the specified buffer. The target ShardGroup is assumed
* to be uninitialized, and the nodes array will be allocated on demand.
*/
RRStatus ShardGroupDeserialize(const char *buf, size_t buf_len, ShardGroup *sg)
{
/* Make a mutable, null terminated copy */
char str[buf_len + 1];
memcpy(str, buf, buf_len);
str[buf_len] = '\0';
char *s = str;
/* Find and null terminate header */
char *nl = strchr(str, '\n');
if (!nl) goto error;
*nl = '\0';
memset(sg, 0, sizeof(*sg));
if (sscanf(s, "%u:%u:%u:%u", &sg->id, &sg->start_slot, &sg->end_slot, &sg->nodes_num) != 4)
goto error;
s = nl + 1;
sg->nodes = RedisModule_Alloc(sizeof(ShardGroupNode) * sg->nodes_num);
for (int i = 0; i < sg->nodes_num; i++) {
ShardGroupNode *n = &sg->nodes[i];
nl = strchr(s, '\n');
if (!nl) goto error;
*nl = '\0';
/* Validate node id */
char *p = strchr(s, ':');
if (!p || p - s > RAFT_SHARDGROUP_NODEID_LEN)
goto error;
/* Copy node id */
int len = p - s;
memcpy(n->node_id, s, len);
n->node_id[len] = '\0';
/* Parse node address */
s = p + 1;
if (!NodeAddrParse(s, strlen(s), &n->addr))
goto error;
s = nl + 1;
}
return RR_OK;
error:
ShardGroupFree(sg);
return RR_ERROR;
}
/* Initialize a (previously allocated) shardgroup structure.
* Basically just zero-initializing everything, but a place holder
* for the future.
*/
void ShardGroupInit(ShardGroup *sg) {
memset(sg, 0, sizeof(ShardGroup));
}
/* Free internal allocations of a ShardGroup.
*/
void ShardGroupFree(ShardGroup *sg)
{
if (sg->conn) {
ConnAsyncTerminate(sg->conn);
sg->conn = NULL;
}
if (sg->nodes) {
RedisModule_Free(sg->nodes);
sg->nodes = NULL;
}
}
/* -----------------------------------------------------------------------------
* ShardGroup synchronization
* -------------------------------------------------------------------------- */
/* Compare two shardgroup entities and return an integer less than, equal
* or greater than zero following common convention.
*
* FIXME: We currently only compare node configuration! This is because all
* shardgroup configuration changes are expected to only involve nodes
* anyway.
*/
int compareShardGroups(ShardGroup *a, ShardGroup *b)
{
if (a->nodes_num != b->nodes_num) {
return a->nodes_num - b->nodes_num;
}
for (int i = 0; i < a->nodes_num; i++) {
int ret = strcmp(a->nodes[i].node_id, b->nodes[i].node_id);
if (ret != 0) {
return ret;
}
ret = strcmp(a->nodes[i].addr.host, b->nodes[i].addr.host);
if (ret != 0) {
return ret;
}
if (a->nodes[i].addr.port != b->nodes[i].addr.port) {
return a->nodes[i].addr.port - b->nodes[i].addr.port;
}
}
return 0;
}
/* Parse the reply of a RAFT.SHARDGROUP GET command, expressed
* as a hiredis redisReply struct, and returns a ShardGroup object.
*
* This implements the same logic as ShardGroupParse() but operates
* on a hiredis reply and not a RedisModuleString argv.
*/
RRStatus parseShardGroupReply(redisReply *reply, ShardGroup *sg)
{
if (reply->type != REDIS_REPLY_ARRAY || reply->elements < 3) {
return RR_ERROR;
}
/* Start and end slots */
if (reply->element[0]->type != REDIS_REPLY_INTEGER ||
reply->element[1]->type != REDIS_REPLY_INTEGER) {
return RR_ERROR;
}
/* Validate node arguments count is correct */
int num_nodes = (reply->elements - 2) / 2;
if ((reply->elements - 2) != num_nodes * 2) {
return RR_ERROR;
}
int elemidx = 2; /* Next element to consume */
sg->start_slot = reply->element[0]->integer;
sg->end_slot = reply->element[1]->integer;
sg->nodes_num = num_nodes;
sg->nodes = RedisModule_Alloc(sizeof(ShardGroupNode) * num_nodes);
/* Parse nodes */
for (int i = 0; i < num_nodes; i++) {
redisReply *elem = reply->element[elemidx++];
if (elem->type != REDIS_REPLY_STRING ||
elem->len != RAFT_SHARDGROUP_NODEID_LEN) {
goto error;
}
memcpy(sg->nodes[i].node_id, elem->str, elem->len);
sg->nodes[i].node_id[elem->len] = '\0';
/* Advance to node address and port */
elem = reply->element[elemidx++];
if (elem->type != REDIS_REPLY_STRING ||
!NodeAddrParse(elem->str, elem->len, &sg->nodes[i].addr)) {
goto error;
}
}
return RR_OK;
error:
RedisModule_Free(sg->nodes);
sg->nodes = NULL;
return RR_ERROR;
}
/* Create and append a shardgroup update log entry to the Raft log.
*
* We handle both RAFT_LOGTYPE_UPDATE_SHARDGROUP and RAFT_LOGTYPE_ADD_SHARDGROUP.
*
* The caller may specify a user_data value, so in case the operation has
* a bound RaftReq and a client waiting for acknowledgements it will be handled.
*/
RRStatus ShardGroupAppendLogEntry(RedisRaftCtx *rr, ShardGroup *sg, int type, void *user_data)
{
/* Make sure we're still a leader, could have changed... */
if (!raft_is_leader(rr->raft)) {
return RR_ERROR;
}
/* Serialize */
char *payload = ShardGroupSerialize(sg);
if (!payload) {
return RR_ERROR;
}
raft_entry_t *entry = raft_entry_new(strlen(payload));
entry->type = type;
entry->id = rand();
entry->user_data = user_data;
memcpy(entry->data, payload, strlen(payload));
RedisModule_Free(payload);
/* Submit */
msg_entry_response_t response;
int e = raft_recv_entry(rr->raft, entry, &response);
raft_entry_release(entry);
if (e != 0) {
LOG_ERROR("Failed to append shardgroup entry, error %d", e);
return RR_ERROR;
}
return RR_OK;
}
/* A hiredis callback that handles the Redis reply after sending a
* RAFT.SHARDGROUP GET command.
*
* FIXME: Some error handling paths may not be accurate and may require
* some cleanup here.
*/
static void handleShardGroupResponse(redisAsyncContext *c, void *r, void *privdata)
{
UNUSED(c);
redisReply *reply = r;
Connection *conn = (Connection *) privdata;
ShardGroup *sg = ConnGetPrivateData(conn);
if (!reply) {
LOG_ERROR("RAFT.SHARDGROUP GET failed: connection dropped.");
} else if (reply->type == REDIS_REPLY_ERROR) {
/* -MOVED? */
if (strlen(reply->str) > 6 && !strncmp(reply->str, "MOVED ", 6)) {
if (!parseMovedReply(reply->str, &sg->conn_addr)) {
LOG_ERROR("RAFT.SHARDGROUP GET failed: invalid MOVED response: %s", reply->str);
} else {
LOG_VERBOSE("RAFT.SHARDGROUP GET redirected to leader: %s:%d",
sg->conn_addr.host, sg->conn_addr.port);
sg->use_conn_addr = true;
}
} else {
LOG_ERROR("RAFT.SHARDGROUP GET failed: %s", reply->str);
}
} else {
ShardGroup recv_sg;
ShardGroupInit(&recv_sg);
if (parseShardGroupReply(reply, &recv_sg) == RR_ERROR) {
LOG_ERROR("RAFT.SHARDGROUP GET invalid reply.");
} else {
LOG_DEBUG("Received shardgroup %u reply.", sg->id);
sg->use_conn_addr = true;
sg->last_updated = RedisModule_Milliseconds();
sg->update_in_progress = false;
/* Issue update */
recv_sg.id = sg->id; /* Copy ID to allow correlation */
if (compareShardGroups(sg, &recv_sg) != 0) {
ShardGroupAppendLogEntry(ConnGetRedisRaftCtx(conn), &recv_sg,
RAFT_LOGTYPE_UPDATE_SHARDGROUP, NULL);
}
ShardGroupFree(&recv_sg);
return;
}
}
/* Mark connection as disconnected and prepare to connect to another
* node.
*/
ConnMarkDisconnected(conn);
}
/* Issue a RAFT.SHARDGROUP GET command on an active connection and register
* a callback to process the reply.
*/
static void sendShardGroupRequest(Connection *conn)
{
/* Failed to connect? Advance node_idx to attempt another node. */
if (!ConnIsConnected(conn)) {
return;
}
/* Request configuration */
redisAsyncContext *rc = ConnGetRedisCtx(conn);
if (redisAsyncCommand(rc, handleShardGroupResponse, conn,
"RAFT.SHARDGROUP %s", "GET") != REDIS_OK) {
redisAsyncDisconnect(rc);
ConnMarkDisconnected(conn);
return;
}
/* We'll be back with handleShardGroupResponse */
}
/* Initiate a connection using an existing Connection object already
* associated with a shardgroup.
*
* This is called periodically as an idle callback to address the
* initial connection and future re-connects.
*/
static void establishShardGroupConn(Connection *conn)
{
ShardGroup *sg = ConnGetPrivateData(conn);
RedisRaftCtx *rr = ConnGetRedisRaftCtx(conn);
NodeAddr *addr;
/* Only establish the connection if we're a leader, and if it's already
* time to update.
*/
if (!raft_is_leader(rr->raft) ||
RedisModule_Milliseconds() - sg->last_updated < rr->config->shardgroup_update_interval) {
return;
}
if (sg->use_conn_addr) {
addr = &sg->conn_addr;
} else {
if (sg->node_conn_idx >= sg->nodes_num) {
sg->node_conn_idx = 0;
}
addr = &sg->nodes[sg->node_conn_idx++].addr;
sg->conn_addr = *addr;
}
LOG_DEBUG("Initiating shardgroup(%u) connection to %s:%u", sg->id, addr->host, addr->port);
sg->update_in_progress = true;
ConnConnect(conn, addr, sendShardGroupRequest);
/* Disable use_conn_addr, as by default we'll try the next address on a
* reconnect. It will be reset to true if the connection was successful, or
* if conn_addr was populated by a -MOVED reply.
*/
sg->use_conn_addr = false;
}
/* Called periodically by the main loop when sharding is enabled.
*
* Currently we use this to iterate all shardgroups and trigger an
* update for shardgroups that have not been updated recently.
*/
void ShardingPeriodicCall(RedisRaftCtx *rr)
{
/* See if we have any shardgroups that need a refresh.
*/
if (!raft_is_leader(rr->raft)) {
return;
}
long long mstime = RedisModule_Milliseconds();
ShardingInfo *si = rr->sharding_info;
for (int i = 0; i < si->shard_groups_num; i++) {
ShardGroup *sg = si->shard_groups[i];
if (!sg->nodes_num || !sg->conn || mstime - sg->last_updated < rr->config->shardgroup_update_interval ||
!ConnIsConnected(sg->conn) || sg->update_in_progress) {
continue;
}
sendShardGroupRequest(sg->conn);
}
}
/* -----------------------------------------------------------------------------
* ShardingInfo Handling
* -------------------------------------------------------------------------- */
/* Save ShardingInfo to RDB during snapshotting. This gets invoked by rdbSaveSnapshotInfo
* which uses a pseudo key to get triggered.
*
* We skip writing the first shardgroup that represents our local cluster.
*/
void ShardingInfoRDBSave(RedisModuleIO *rdb)
{
RedisRaftCtx *rr = &redis_raft;
ShardingInfo *si = rr->sharding_info;
/* If no ShardingInfo, write a zero count and abort. */
if (!si) {
RedisModule_SaveUnsigned(rdb, 0);
return;
}
/* When saving, skip shardgroup #1 which is the local cluster */
RedisModule_SaveUnsigned(rdb, si->shard_groups_num - 1);
for (int i = 1; i < si->shard_groups_num; i++) {
ShardGroup *sg = si->shard_groups[i];
RedisModule_SaveUnsigned(rdb, sg->id);
RedisModule_SaveUnsigned(rdb, sg->start_slot);
RedisModule_SaveUnsigned(rdb, sg->end_slot);
RedisModule_SaveUnsigned(rdb, sg->nodes_num);
for (int j = 0; j < sg->nodes_num; j++) {
ShardGroupNode *n = &sg->nodes[j];
RedisModule_SaveStringBuffer(rdb, n->node_id, strlen(n->node_id));
RedisModule_SaveStringBuffer(rdb, n->addr.host, strlen(n->addr.host));
RedisModule_SaveUnsigned(rdb, n->addr.port);
}
}
}
/* Load ShardingInfo from RDB. This gets invoked by rdbLoadSnapshotInfo which uses a
* pseudo key to get triggered.
*
* NOTE: Some attention to sequence of events is required here. When a snapshot is
* loaded, the RDB loading is guaranteed to take place when everything is already
* well initialized.
*
* However, we need to also consider the initial loading of RDB, which can take
* place after the module has been loaded but before RedisRaft has initialized
* completely. This logic has already been implemented correctly for SnapshotInfo
* and we need to consider consolidating everything and possibly move to more
* modern Module API capabilities that can let us avoid piggybacking on keys.
*/
void ShardingInfoRDBLoad(RedisModuleIO *rdb)
{
RedisRaftCtx *rr = &redis_raft;
ShardingInfo *si = rr->sharding_info;
/* Always read the shards_group_num, because it's always written (but may
* be zero).
*/
unsigned int rdb_shard_groups_num = RedisModule_LoadUnsigned(rdb);
if (!rdb_shard_groups_num) {
/* No shardgroups. This could mean no sharding, or simply no shardgroups
* to read. If we have ShardingInfo we'll reset it.
*/
if (si)
ShardingInfoReset(rr);
return;
}
/* If we have something to load, we need to reset ShardingInfo first.
* We also need to be sure we're in cluster mode, i.e. that si was
* initialized.
*/
RedisModule_Assert(si != NULL);
ShardingInfoReset(rr);
/* Load individual shard groups */
for (int i = 0; i < rdb_shard_groups_num; i++) {
ShardGroup sg;
ShardGroupInit(&sg);
sg.id = RedisModule_LoadUnsigned(rdb);
sg.start_slot = RedisModule_LoadUnsigned(rdb);
sg.end_slot = RedisModule_LoadUnsigned(rdb);
sg.nodes_num = RedisModule_LoadUnsigned(rdb);
/* Load nodes */
sg.nodes = RedisModule_Calloc(sg.nodes_num, sizeof(ShardGroupNode));
for (int j = 0; j < sg.nodes_num; j++) {
ShardGroupNode *n = &sg.nodes[j];
size_t len;
char *buf = RedisModule_LoadStringBuffer(rdb, &len);
RedisModule_Assert(len < sizeof(n->node_id));
memcpy(n->node_id, buf, len);
n->node_id[len] = '\0';
RedisModule_Free(buf);
buf = RedisModule_LoadStringBuffer(rdb, &len);
RedisModule_Assert(len < sizeof(n->addr.host));
memcpy(n->addr.host, buf, len);
n->addr.host[len] = '\0';
RedisModule_Free(buf);
n->addr.port = RedisModule_LoadUnsigned(rdb);
}
/* This also handles all validation so serious violations, although
* should never exist, will be caught.
*/
RRStatus ret = ShardingInfoAddShardGroup(rr, &sg);
RedisModule_Assert(ret == RR_OK);
ShardGroupFree(&sg);
}
}
/* Validate a new shardgroup and make sure there are no conflicts with
* current ShardingInfo configuration.
*
* Currently we check:
* 1. Slot range is valid.
* 2. All specified slots are currently unassigned.
*/
RRStatus ShardingInfoValidateShardGroup(RedisRaftCtx *rr, ShardGroup *new_sg)
{
ShardingInfo *si = rr->sharding_info;
/* Verify all specified slots are available */
if (!HashSlotRangeValid(new_sg->start_slot, new_sg->end_slot)) {
LOG_ERROR("Invalid shardgroup: bad slots range %u-%u",
new_sg->start_slot, new_sg->end_slot);
return RR_ERROR;
}
for (int i = new_sg->start_slot; i <= new_sg->end_slot; i++) {
if (si->hash_slots_map[i] != 0) {
LOG_ERROR("Invalid shardgroup: hash slot already mapped: %u", i);
return RR_ERROR;
}
}
return RR_OK;
}
/* Update an existing ShardGroup in the active ShardingInfo.
*
* FIXME: We currently only handle updating nodes but don't support remapping
* hash slots.
*/
RRStatus ShardingInfoUpdateShardGroup(RedisRaftCtx *rr, ShardGroup *new_sg)
{
ShardingInfo *si = rr->sharding_info;
if (new_sg->id < 1 || new_sg->id > si->shard_groups_num)
return RR_ERROR;
ShardGroup *sg = si->shard_groups[new_sg->id - 1];
sg->nodes_num = new_sg->nodes_num;
sg->nodes = RedisModule_Realloc(sg->nodes, sizeof(ShardGroupNode) * sg->nodes_num);
memcpy(sg->nodes, new_sg->nodes, sizeof(ShardGroupNode) * sg->nodes_num);
return RR_OK;
}
/* Add a new ShardGroup to the active ShardingInfo. Validation is done according to
* ShardingInfoValidateShardGroup() above.
*/
RRStatus ShardingInfoAddShardGroup(RedisRaftCtx *rr, ShardGroup *new_sg)
{
ShardingInfo *si = rr->sharding_info;
/* Validate first */
if (ShardingInfoValidateShardGroup(rr, new_sg) != RR_OK)
return RR_ERROR;
si->shard_groups_num++;
si->shard_groups = RedisModule_Realloc(si->shard_groups, sizeof(ShardGroup *) * si->shard_groups_num);
ShardGroup *sg = si->shard_groups[si->shard_groups_num-1] = RedisModule_Alloc(sizeof(ShardGroup));
sg->id = si->shard_groups_num;
sg->start_slot = new_sg->start_slot;
sg->end_slot = new_sg->end_slot;
sg->nodes_num = new_sg->nodes_num;
sg->next_redir = 0;
sg->use_conn_addr = false;
sg->node_conn_idx = 0;
sg->conn = NULL;
sg->nodes = RedisModule_Alloc(sizeof(ShardGroupNode) * new_sg->nodes_num);
memcpy(sg->nodes, new_sg->nodes, sizeof(ShardGroupNode) * new_sg->nodes_num);
/* Do slot mapping */
for (int i = new_sg->start_slot; i <= new_sg->end_slot; i++) {
si->hash_slots_map[i] = si->shard_groups_num;
}
/* Create a connection object for syncing. We assume that if nodes_num is zero
* this is the shardgroup entry for our local cluster so it can be skipped.
* */
if (sg->nodes_num > 0) {
sg->conn = ConnCreate(rr, sg, establishShardGroupConn, NULL);
}
return RR_OK;
}
/* Parse a ShardGroup specification as passed directly to RAFT.SHARDGROUP ADD.
* Shard group syntax is as follows:
*
* [start slot] [end slot] [node-uid node-addr:node-port] [node-uid node-addr:node-port...]
*
* If parsing errors are encountered, an error reply is generated on the supplied RedisModuleCtx,
* and RR_ERROR is returned.
*/
RRStatus ShardGroupParse(RedisModuleCtx *ctx, RedisModuleString **argv, int argc, ShardGroup *sg)
{
long long start_slot, end_slot;
ShardGroupInit(sg);
/* Slot range */
if (RedisModule_StringToLongLong(argv[0], &start_slot) != REDISMODULE_OK ||
RedisModule_StringToLongLong(argv[1], &end_slot) != REDISMODULE_OK ||
!HashSlotRangeValid(start_slot, end_slot)) {
RedisModule_ReplyWithError(ctx, "ERR invalid slot range");
goto error;
}
/* Validate node arguments count is correct */
int num_nodes = (argc - 2) / 2;
if ((argc - 2) != num_nodes * 2) {
RedisModule_WrongArity(ctx);
goto error;
}
int argidx = 2; /* Next arg to consume */
/* Parse nodes */
sg->start_slot = start_slot;
sg->end_slot = end_slot;
sg->nodes_num = num_nodes;
sg->nodes = RedisModule_Alloc(sizeof(ShardGroupNode) * num_nodes);
for (int i = 0; i < num_nodes; i++) {
size_t len;
const char *str = RedisModule_StringPtrLen(argv[argidx++], &len);
if (len != RAFT_SHARDGROUP_NODEID_LEN) {
RedisModule_ReplyWithError(ctx, "ERR invalid node id length");
goto error;
}
memcpy(sg->nodes[i].node_id, str, len);
sg->nodes[i].node_id[len] = '\0';
str = RedisModule_StringPtrLen(argv[argidx++], &len);
if (!NodeAddrParse(str, len, &sg->nodes[i].addr)) {
RedisModule_ReplyWithError(ctx, "ERR invalid node address/port");
goto error;
}
}
return RR_OK;
error:
ShardGroupFree(sg);
return RR_ERROR;
}
/* Initialize ShardingInfo and add our local RedisRaft cluster as the first
* ShardGroup.
*/
void ShardingInfoInit(RedisRaftCtx *rr)
{
rr->sharding_info = RedisModule_Calloc(1, sizeof(ShardingInfo));
ShardingInfoReset(rr);
}
/* Free and reset the ShardingInfo structure.
*
* This is called after ShardingInfo has already been allocated, and typically
* right before loading serialized ShardGroups from a snapshot.
*/
void ShardingInfoReset(RedisRaftCtx *rr)
{
ShardingInfo *si = rr->sharding_info;
for (int i = 0; i < si->shard_groups_num; i++) {
ShardGroupFree(si->shard_groups[i]);
RedisModule_Free(si->shard_groups[i]);
si->shard_groups[i] = NULL;
}
if (si->shard_groups)
RedisModule_Free(si->shard_groups);
si->shard_groups = NULL;
si->shard_groups_num = 0;
/* Reset array */
for (int i = 0; i < REDIS_RAFT_HASH_SLOTS; i++)
si->hash_slots_map[i] = 0;
/* Add our local mapping */
ShardGroup sg = {
.start_slot = rr->config->sharding_start_hslot,
.end_slot = rr->config->sharding_end_hslot,
.nodes_num = 0,
.nodes = NULL
};
RRStatus ret = ShardingInfoAddShardGroup(rr, &sg);
RedisModule_Assert(ret == RR_OK);
}
/* Compute the hash slot for a RaftRedisCommandArray list of commands and update
* the entry.
*/
RRStatus computeHashSlot(RedisRaftCtx *rr, RaftReq *req)
{
int slot = -1;
RaftRedisCommandArray *cmds = &req->r.redis.cmds;
for (int i = 0; i < cmds->len; i++) {
RaftRedisCommand *cmd = cmds->commands[i];
/* Iterate command keys */
int num_keys = 0;
int *keyindex = RedisModule_GetCommandKeys(rr->ctx, cmd->argv, cmd->argc, &num_keys);
for (int j = 0; j < num_keys; j++) {
size_t key_len;
const char *key = RedisModule_StringPtrLen(cmd->argv[keyindex[j]], &key_len);
int thisslot = keyHashSlot(key, key_len);
if (slot == -1) {
/* First key */
slot = thisslot;
} else {
if (slot != thisslot) {
RedisModule_Free(keyindex);
return RR_ERROR;
}
}
}
RedisModule_Free(keyindex);
}
req->r.redis.hash_slot = slot;
return RR_OK;
}
/* Produces a CLUSTER SLOTS compatible reply entry for the specified local cluster node.
*/
static int addClusterSlotNodeReply(RedisRaftCtx *rr, RedisModuleCtx *ctx, raft_node_t *raft_node)
{
Node *node = raft_node_get_udata(raft_node);
NodeAddr *addr;
char node_id[RAFT_SHARDGROUP_NODEID_LEN+1];
/* Stale nodes should not exist but we prefer to be defensive.
* Our own node doesn't have a connection so we don't expect a Node object.
*/
if (node) {
addr = &node->addr;
} else if (raft_get_my_node(rr->raft) == raft_node) {
addr = &rr->config->addr;
} else {
return 0;
}
/* Create a three-element reply:
* 1) Address
* 2) Port
* 3) Node ID
*/
RedisModule_ReplyWithArray(ctx, 3);
RedisModule_ReplyWithCString(ctx, addr->host);
RedisModule_ReplyWithLongLong(ctx, addr->port);
snprintf(node_id, sizeof(node_id), "%.32s%08x", rr->log->dbid, raft_node_get_id(raft_node));
RedisModule_ReplyWithCString(ctx, node_id);
return 1;
}
/* Produce a CLUSTER SLOTS compatible reply entry for the specified shardgroup node.
*/
static int addClusterSlotShardGroupNodeReply(RedisRaftCtx *rr, RedisModuleCtx *ctx, ShardGroupNode *sgn)
{
UNUSED(rr);
/* Create a three-element reply:
* 1) Address
* 2) Port
* 3) Node ID
*/
RedisModule_ReplyWithArray(ctx, 3);
RedisModule_ReplyWithCString(ctx, sgn->addr.host);
RedisModule_ReplyWithLongLong(ctx, sgn->addr.port);
RedisModule_ReplyWithCString(ctx, sgn->node_id);
return 1;
}
/* Returns a string representation of the hash slot range assigned to the
* specified shardgroup.
*
* Currently doesn't handle handle mutiple slot ranges or importing/migrating
* yet.
*/
RedisModuleString *generateSlots(RedisModuleCtx *ctx, ShardGroup *sg)
{
if (sg->start_slot != sg->end_slot) {
return RedisModule_CreateStringPrintf(ctx, "%d-%d", sg->start_slot, sg->end_slot);
} else {
return RedisModule_CreateStringPrintf(ctx, "%d", sg->start_slot);
}
}
/* Formats a CLUSTER NODES line and appends it to ret */
static void appendClusterNodeString(RedisModuleString *ret, char node_id[41], NodeAddr *addr, const char *flags,
const char *master, int ping_sent, int pong_recv, raft_term_t epoch, const char *link_state,
RedisModuleString *slots)
{
size_t len;
const char *temp;
size_t slots_len;
const char *slots_str;
slots_str = RedisModule_StringPtrLen(slots, &slots_len);
RedisModuleString* str = RedisModule_CreateStringPrintf(NULL,
"%s %s:%d@%d %s %s %d %d %ld %s %.*s\r\n",
node_id,
addr->host,
addr->port,
addr->port,
flags,
master,
ping_sent,
pong_recv,
epoch,
link_state,
(int) slots_len, slots_str);
temp = RedisModule_StringPtrLen(str, &len);
RedisModule_StringAppendBuffer(NULL, ret, temp, len);
RedisModule_FreeString(NULL, str);
}
/* Formats a CLUSTER NODES line from a raft node structure and appends it to ret. */
static void addClusterNodeReplyFromNode(RedisRaftCtx *rr,
RedisModuleString *ret,
raft_node_t *raft_node,
RedisModuleString *slots)
{
Node *node = raft_node_get_udata(raft_node);
NodeAddr *addr;
int leader = (raft_node_get_id(raft_node) == raft_get_leader_id(rr->raft));
int self = (raft_node_get_id(raft_node) == raft_get_nodeid(rr->raft));
/* Stale nodes should not exist but we prefer to be defensive.
* Our own node doesn't have a connection so we don't expect a Node object.
*/
if (node) {
addr = &node->addr;
} else if (raft_get_my_node(rr->raft) == raft_node) {
addr = &rr->config->addr;
} else {
return;
}
/* should we record heartbeat and reply times for ping/pong */
char *flags = self ? "myself" : "noflags";
char *master = leader ? "master" : "slave";
int ping_sent = 0;
int pong_recv = 0;
char node_id[RAFT_SHARDGROUP_NODEID_LEN+1];
snprintf(node_id, sizeof(node_id), "%.32s%08x", rr->log->dbid, raft_node_get_id(raft_node));
raft_term_t epoch = raft_get_current_term(redis_raft.raft);
char *link_state = "connected";
appendClusterNodeString(ret, node_id, addr, flags, master, ping_sent, pong_recv, epoch, link_state, slots);
}
/* Produce a CLUSTER NODES compatible reply, including:
*
* 1. Local cluster's slot range and nodes
* 2. All configured shardgroups with their slot ranges and nodes.
*/
static void addClusterNodesReply(RedisRaftCtx *rr, RaftReq *req)
{
raft_node_t *leader_node = getLeaderNodeOrReply(rr, req);
if (!leader_node) {
return;
}
ShardingInfo *si = rr->sharding_info;
RedisModuleString *ret = RedisModule_CreateString(req->ctx, "", 0);
for (int i = 0; i < si->shard_groups_num; i++) {
ShardGroup *sg = si->shard_groups[i];
RedisModuleString *slots = generateSlots(req->ctx, sg);
if (i == 0) { /* our own shardgroup we reply out of the node data */
for (int j = 0; j < raft_get_num_nodes(rr->raft); j++) {
raft_node_t *raft_node = raft_get_node_from_idx(rr->raft, j);
if (!raft_node_is_active(raft_node)) {
continue;
}
addClusterNodeReplyFromNode(rr, ret, raft_node, slots);
}
} else { /* the other shard groups we reply out of the shard group data */
for (int j = 0; j < sg->nodes_num; j++) {
char *flags = "noflags";
/* SHARDGROUP GET only works on leader
* SHARDGROUP GET lists nodes in order of idx, but 0 will always be self, i.e. leader
*/
char *master = j == 0 ? "master" : "slave";
int ping_sent = 0;
int pong_recv = 0;
int epoch = 0;
char *link_state = "connected";
appendClusterNodeString(ret, sg->nodes[j].node_id, &sg->nodes[j].addr, flags, master, ping_sent,
pong_recv, epoch, link_state, slots);
}
}
RedisModule_FreeString(req->ctx, slots);
}
RedisModule_ReplyWithString(req->ctx, ret);
RedisModule_FreeString(req->ctx, ret);
}
/* Produce a CLUSTER SLOTS compatible reply, including:
*
* 1. Local cluster's slot range and nodes.
* 2. All configured shardgroups with their slot ranges and nodes.
*/