-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcluster.c
More file actions
1839 lines (1613 loc) · 69.9 KB
/
Copy pathcluster.c
File metadata and controls
1839 lines (1613 loc) · 69.9 KB
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) 2006-Present, Redis Ltd.
* All rights reserved.
*
* Licensed under your choice of (a) the Redis Source Available License 2.0
* (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the
* GNU Affero General Public License v3 (AGPLv3).
*/
#include "redismodule.h"
#include "common.h"
#include "mr.h"
#include "cluster.h"
#include "event_loop.h"
#include "utils/arr_rm_alloc.h"
#include "utils/buffer.h"
#include "utils/dict.h"
#include "utils/adlist.h"
#include <ctype.h>
#include <hiredis.h>
#include <hiredis_ssl.h>
#include <async.h>
#include <libevent.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#define RETRY_INTERVAL 1000 // 1 second
#define MSG_MAX_RETRIES 3
#define NUMBER_OF_SLOTS 16384
#define RUN_ID_SIZE 40
/*
* The CLUSTERSET command can come in a long form (legacy, very explicit):
*
* <module-name>.CLUSTERSET
* HASHFUNC {hashing_function}
* NUMSLOTS {number_of_slots}
* MYID {current_shard_id}
* [HASREPLICATION]
* RANGES {num_of_ranges}
* { SHARD {shard_id}
* [SLOTRANGE {start_slot} {end_slot}]
* ADDR {auth@ip:port} [UNIXADDR {unixsock}]
* [MASTER]
* }
*
* or short form (new, more compact; the module will get the topology from the server directly):
*
* <module-name>.CLUSTERSET [AUTH {pwd}] // the assumption is that all nodes use the same (or no) password
*/
#define CLUSTERSET_MYID_LONG_FORM_INDEX 6
static bool IsLongFormClusterSet(int argc) {
return argc >= 10;
}
static bool IsShortFormClusterSet(int argc) {
return argc == 1 || argc == 3;
}
#define CLUSTER_INNER_COMMUNICATION_COMMAND xstr(MODULE_NAME)".INNERCOMMUNICATION"
#define CLUSTER_HELLO_COMMAND xstr(MODULE_NAME)".HELLO"
#define CLUSTER_REFRESH_COMMAND xstr(MODULE_NAME)".REFRESHCLUSTER"
#define CLUSTER_SET_COMMAND xstr(MODULE_NAME)".CLUSTERSET"
#define CLUSTER_SET_FROM_SHARD_COMMAND xstr(MODULE_NAME)".CLUSTERSETFROMSHARD"
#define CLUSTER_INFO_COMMAND xstr(MODULE_NAME)".INFOCLUSTER"
#define NETWORK_TEST_COMMAND xstr(MODULE_NAME)".NETWORKTEST"
#define FORCE_SHARDS_CONNECTION xstr(MODULE_NAME)".FORCESHARDSCONNECTION"
/** @brief Register a new Redis command with the required ACLs.
* @see RedisModule_CreateCommand
* @return true if the command was registered successfully, false
* otherwise.
*/
static inline __attribute__((always_inline)) bool
RegisterRedisCommand(RedisModuleCtx *ctx, const char *name,
RedisModuleCmdFunc cmdfunc, const char *strflags,
int firstkey, int lastkey, int keystep) {
const int ret = RedisModule_CreateCommand(ctx, name, cmdfunc, strflags,
firstkey, lastkey, keystep);
if (ret != REDISMODULE_OK) {
RedisModule_Log(ctx, "warning", "Couldn't register the command %s", name);
return false;
}
return true;
}
typedef enum NodeStatus{
NodeStatus_Connected, NodeStatus_Disconnected, NodeStatus_HelloSent, NodeStatus_Free, NodeStatus_Uninitialized
}NodeStatus;
typedef enum SendMsgType{
SendMsgType_BySlot, SendMsgType_ById, SendMsgType_ToAll
}SendMsgType;
typedef struct SendMsg{
size_t refCount; // ref count does not need to be thread safe as its only touched on the event loop
union {
char idToSend[REDISMODULE_NODE_ID_LEN + 1];
size_t slotToSend;
};
SendMsgType sendMsgType;
functionId function;
char* msg;
size_t msgLen;
}SendMsg;
typedef struct NodeSendMsg{
SendMsg* msg;
size_t msgId;
size_t retries;
}NodeSendMsg;
typedef struct SlotRange{
uint16_t minSlot;
uint16_t maxSlot;
}SlotRange;
typedef struct Node{
char* id;
char* ip;
unsigned short port;
char* password;
char* unixSocket;
redisAsyncContext *c;
char* runId;
unsigned long long msgId;
mr_list* pendingMessages;
mr_list* slotRanges;
bool isMe;
unsigned short index; // A small int unique node identifier for internal usage
NodeStatus status;
MR_LoopTaskCtx* reconnectEvent;
MR_LoopTaskCtx* resendHelloEvent;
bool sendClusterTopologyOnNextConnect;
}Node;
typedef struct Cluster {
char* myId;
mr_dict* nodes;
Node* slots[NUMBER_OF_SLOTS];
size_t clusterSetCommandSize;
char** clusterSetCommand;
char runId[RUN_ID_SIZE + 1];
}Cluster;
struct ClusterCtx {
ARR(MR_ClusterMessageReceiver) callbacks;
Cluster* CurrCluster;
mr_dict* nodesMsgIds;
// Note that the slot range in ClusterCtx are legacy code and only used as a fallback.
// The general case (i.e., of possible multiple ranges per shard) are handled in `Node`.
size_t minSlot;
size_t maxSlot;
size_t clusterSize;
char myId[REDISMODULE_NODE_ID_LEN + 1];
int isOss;
functionId networkTestMsgReceiver;
char *password;
}clusterCtx;
typedef struct ClusterSetCtx {
RedisModuleBlockedClient* bc;
RedisModuleString **argv;
int argc;
bool force;
const char* errReply; // NULL => reply "OK"; otherwise reply this error to the client
}ClusterSetCtx;
typedef enum MessageReply {
MessageReply_Undefined,
MessageReply_OK,
MessageReply_ClusterUninitialized,
MessageReply_ClusterNull,
MessageReply_BadMsgId,
MessageReply_BadFunctionId,
MessageReply_DuplicateMsg,
}MessageReply;
typedef struct MessageCtx {
RedisModuleBlockedClient* bc;
RedisModuleString **argv;
int argc;
MessageReply reply;
}MessageCtx;
static void MR_OnStatusResponseArrived(struct redisAsyncContext* c, void* a, void* b);
static void MR_OnDataResponseArrived(struct redisAsyncContext* c, void* a, void* b); // A response to an internal-commands command
static void MR_ConnectToShard(Node* n);
static void MR_HelloResponseArrived(struct redisAsyncContext* c, void* a, void* b);
static Node* MR_GetNode(const char* id);
static SlotRange* NewSlotRange(uint16_t minSlot, uint16_t maxSlot) {
SlotRange* result = MR_ALLOC(sizeof(*result));
result->minSlot = minSlot;
result->maxSlot = maxSlot;
return result;
}
static void FreeSlotRange(void *ptr) {
MR_FREE(ptr);
}
static void MR_ClusterFreeMsg(void* ptr){
SendMsg* msg = ptr;
if (--msg->refCount > 0) {
return;
}
MR_FREE(msg->msg);
MR_FREE(msg);
}
static void MR_ClusterFreeNodeMsg(void* ptr){
NodeSendMsg* nodeMsg = ptr;
MR_ClusterFreeMsg(nodeMsg->msg);
MR_FREE(nodeMsg);
}
static void MR_ClusterSendMsgToNodeInternal(Node* node, NodeSendMsg* nodeMsg){
// CLUSTER_INNER_COMMUNICATION_COMMAND <myid> <runid> <functionid> <msg> <msgId>
void (*onResponse)(struct redisAsyncContext*, void*, void*) =
(nodeMsg->msg->function & FUNCTION_ID_INTERNAL) ? MR_OnDataResponseArrived : MR_OnStatusResponseArrived;
redisAsyncCommand(node->c, onResponse, node, CLUSTER_INNER_COMMUNICATION_COMMAND" %s %s %llu %b %llu",
clusterCtx.CurrCluster->myId,
clusterCtx.CurrCluster->runId,
nodeMsg->msg->function,
nodeMsg->msg->msg, nodeMsg->msg->msgLen,
nodeMsg->msgId);
}
static void MR_ClusterSendMsgToNode(Node* node, SendMsg* msg){
msg->refCount+=1;
NodeSendMsg* nodeMsg = MR_ALLOC(sizeof(*nodeMsg));
nodeMsg->msg = msg;
nodeMsg->retries = 0;
nodeMsg->msgId = node->msgId++;
if (node->status == NodeStatus_Connected) {
MR_ClusterSendMsgToNodeInternal(node, nodeMsg);
} else {
if (node->status == NodeStatus_Uninitialized) {
MR_ConnectToShard(node);
node->status = NodeStatus_Disconnected;
}
RedisModule_Log(mr_staticCtx, "warning", "message was not sent because status is not connected");
}
mr_listAddNodeTail(node->pendingMessages, nodeMsg);
}
/* Runs on the event loop */
static void MR_ClusterSendMsgTask(void* ctx) {
SendMsg* sendMsg = ctx;
if (!clusterCtx.CurrCluster) {
RedisModule_Log(mr_staticCtx, "warning", "try to send a message on an uninitialize cluster, message will not be sent.");
MR_ClusterFreeMsg(sendMsg);
return;
}
if (sendMsg->sendMsgType == SendMsgType_ById) {
Node* n = MR_GetNode(sendMsg->idToSend);
if(!n){
RedisModule_Log(mr_staticCtx, "warning", "Could not find node to send message to");
} else {
MR_ClusterSendMsgToNode(n, sendMsg);
}
} else if (sendMsg->sendMsgType == SendMsgType_ToAll) {
mr_dictIterator *iter = mr_dictGetIterator(clusterCtx.CurrCluster->nodes);
mr_dictEntry *entry = NULL;
while((entry = mr_dictNext(iter))){
Node* n = mr_dictGetVal(entry);
bool isInternalCommand = (sendMsg->function & FUNCTION_ID_INTERNAL) != 0;
bool shouldSendToNode = !n->isMe || isInternalCommand;
if (shouldSendToNode)
MR_ClusterSendMsgToNode(n, sendMsg);
}
mr_dictReleaseIterator(iter);
} else if (sendMsg->sendMsgType == SendMsgType_BySlot) {
Node* n = clusterCtx.CurrCluster->slots[sendMsg->slotToSend];
if(!n){
RedisModule_Log(mr_staticCtx, "warning", "Could not find node to send message to");
return;
}
MR_ClusterSendMsgToNode(n, sendMsg);
} else {
RedisModule_Assert(false);
}
MR_ClusterFreeMsg(sendMsg);
}
void MR_ClusterSendMsg(const char* nodeId, functionId function, char* msg, size_t len) {
SendMsg* msgStruct = MR_ALLOC(sizeof(*msgStruct));
if(nodeId){
memcpy(msgStruct->idToSend, nodeId, REDISMODULE_NODE_ID_LEN);
msgStruct->idToSend[REDISMODULE_NODE_ID_LEN] = '\0';
msgStruct->sendMsgType = SendMsgType_ById;
}else{
msgStruct->sendMsgType = SendMsgType_ToAll;
}
msgStruct->function = function;
msgStruct->msg = msg;
msgStruct->msgLen = len;
msgStruct->refCount = 1;
MR_EventLoopAddTask(MR_ClusterSendMsgTask, msgStruct);
}
void MR_ClusterCopyAndSendMsg(const char* nodeId, functionId function, char* msg, size_t len) {
char* cMsg = MR_ALLOC(len);
memcpy(cMsg, msg, len);
MR_ClusterSendMsg(nodeId, function, cMsg, len);
}
void MR_ClusterSendMsgBySlot(size_t slot, functionId function, char* msg, size_t len) {
SendMsg* msgStruct = MR_ALLOC(sizeof(*msgStruct));
msgStruct->slotToSend = slot;
msgStruct->sendMsgType = SendMsgType_BySlot;
msgStruct->function = function;
msgStruct->msg = msg;
msgStruct->msgLen = len;
msgStruct->refCount = 1;
MR_EventLoopAddTask(MR_ClusterSendMsgTask, msgStruct);
}
void MR_ClusterCopyAndSendMsgBySlot(size_t slot, functionId function, char* msg, size_t len) {
char* cMsg = MR_ALLOC(len);
memcpy(cMsg, msg, len);
MR_ClusterSendMsgBySlot(slot, function, cMsg, len);
}
functionId MR_ClusterRegisterMsgReceiver(MR_ClusterMessageReceiver receiver) {
for (functionId fid = 0; fid < array_len(clusterCtx.callbacks); fid++)
if (clusterCtx.callbacks[fid] == receiver)
return fid;
clusterCtx.callbacks = array_append(clusterCtx.callbacks, receiver);
return array_len(clusterCtx.callbacks) - 1;
}
static void MR_OnDataResponseArrived(struct redisAsyncContext* c, void* r, void* n) {
redisReply* reply = r;
if (!reply || !c->data) return;
Node* node = n;
if (reply->type != REDIS_REPLY_ARRAY) {
RedisModule_Log(mr_staticCtx, "warning",
"Received an invalid status reply from shard %s (%s:%d), will disconnect and try to reconnect.",
node->id, node->ip, node->port);
redisAsyncDisconnect(c);
return;
}
mr_listNode* pendingMessage = mr_listFirst(node->pendingMessages);
NodeSendMsg *message = pendingMessage->value;
Execution *e = MR_GetExecution(message->msg->msg, message->msg->msgLen);
mr_listDelNode(node->pendingMessages, pendingMessage);
MR_SetInternalCommandResults(node->index, reply, e);
}
static void MR_OnStatusResponseArrived(struct redisAsyncContext* c, void* r, void* n){
redisReply* reply = r;
if (!reply || !c->data) return;
Node* node = n;
if(reply->type == REDIS_REPLY_ERROR && strncmp(reply->str, CLUSTER_ERROR, strlen(CLUSTER_ERROR)) == 0){
node->sendClusterTopologyOnNextConnect = true;
RedisModule_Log(mr_staticCtx, "warning",
"Received ERRCLUSTER reply from shard %s (%s:%d), will send cluster topology to the shard on next connect",
node->id, node->ip, node->port);
redisAsyncDisconnect(c);
return;
}
if(reply->type != REDIS_REPLY_STATUS){
RedisModule_Log(mr_staticCtx, "warning",
"Received an invalid status reply from shard %s (%s:%d), will disconnect and try to reconnect. "
"This is usually because the Redis server's 'proto-max-bulk-len' configuration setting is too low.",
node->id, node->ip, node->port);
redisAsyncDisconnect(c);
return;
}
mr_listNode* pendingMessage = mr_listFirst(node->pendingMessages);
mr_listDelNode(node->pendingMessages, pendingMessage);
}
static void MR_ClusterResendHelloMessage(void* ctx){
Node* n = ctx;
n->resendHelloEvent = NULL;
if(n->status == NodeStatus_Disconnected){
// we will resent the hello request when reconnect
return;
}
if(n->sendClusterTopologyOnNextConnect && clusterCtx.CurrCluster->clusterSetCommand){
bool isLongForm = IsLongFormClusterSet(clusterCtx.CurrCluster->clusterSetCommandSize);
RedisModule_Log(mr_staticCtx, "notice", "Sending cluster (%s form) topology to %s (%s:%d) on rg.hello retry",
isLongForm ? "long" : "short", n->id, n->ip, n->port);
if (isLongForm)
clusterCtx.CurrCluster->clusterSetCommand[CLUSTERSET_MYID_LONG_FORM_INDEX] = MR_STRDUP(n->id);
redisAsyncCommandArgv(n->c, NULL, NULL, clusterCtx.CurrCluster->clusterSetCommandSize, (const char**)clusterCtx.CurrCluster->clusterSetCommand, NULL);
if (isLongForm) {
MR_FREE(clusterCtx.CurrCluster->clusterSetCommand[CLUSTERSET_MYID_LONG_FORM_INDEX]);
clusterCtx.CurrCluster->clusterSetCommand[CLUSTERSET_MYID_LONG_FORM_INDEX] = NULL;
}
n->sendClusterTopologyOnNextConnect = false;
}
RedisModule_Log(mr_staticCtx, "notice", "Resending hello request to %s (%s:%d)", n->id, n->ip, n->port);
redisAsyncCommand((redisAsyncContext*)n->c, MR_HelloResponseArrived, n, CLUSTER_HELLO_COMMAND);
}
static void SendAuthCommandIfNeeded(const struct redisAsyncContext* c, const Node *n) {
if (n->password){
/* If password is provided to us we will use it (it means it was given to us with clusterset) */
redisAsyncCommand((redisAsyncContext*)c, NULL, NULL, "AUTH %s", n->password);
return;
}
if (RedisModule_GetInternalSecret && clusterCtx.isOss) {
/* OSS deployment that support internal secret, lets use it. */
RedisModule_ThreadSafeContextLock(mr_staticCtx);
size_t len;
const char *secret = RedisModule_GetInternalSecret(mr_staticCtx, &len);
RedisModule_Assert(secret);
redisAsyncCommand((redisAsyncContext*)c, NULL, NULL, "AUTH %s %b", "internal connection", secret, len);
RedisModule_ThreadSafeContextUnlock(mr_staticCtx);
}
}
static void MR_HelloResponseArrived(struct redisAsyncContext* c, void* a, void* b){
redisReply* reply = (redisReply*)a;
if(!reply){
return;
}
Node* n = (Node*)b;
if(!c->data){
return;
}
if(reply->type != REDIS_REPLY_STRING){
// we did not got a string reply
// the shard is probably not yet up.
// we will try again in one second.
if(reply->type == REDIS_REPLY_ERROR && strncmp(reply->str, CLUSTER_ERROR, strlen(CLUSTER_ERROR)) == 0){
RedisModule_Log(mr_staticCtx, "warning", "Got uninitialize cluster error on hello response from %s (%s:%d), will resend cluster topology in next try in 1 second.", n->id, n->ip, n->port);
n->sendClusterTopologyOnNextConnect = true;
}else{
RedisModule_Log(mr_staticCtx, "warning", "Got bad hello response from %s (%s:%d), will try again in 1 second, %s.", n->id, n->ip, n->port, reply->str);
// This might happen if the AUTH has failed because we sent it too early when `n`
// accepted connections but did not set its internal secret to the cluster's yet.
// In such cases we will have a regular (i.e., non-internal) connection and the
// hidden commands (including `<module>.HELLO`) will not be visible to us.
if (clusterCtx.isOss && strstr(reply->str, "unknown command") != NULL)
SendAuthCommandIfNeeded(c, n);
}
n->resendHelloEvent = MR_EventLoopAddTaskWithDelay(MR_ClusterResendHelloMessage, n, RETRY_INTERVAL);
return;
}
bool resendPendingMessages = true;;
if(n->runId){
if(strcmp(n->runId, reply->str) != 0){
/* here we know that the shard has crashed
* There is no need to send pending messages
*/
resendPendingMessages = false;
n->msgId = 0;
mr_listEmpty(n->pendingMessages);
}
MR_FREE(n->runId);
}
if(resendPendingMessages){
// we need to send pending messages to the shard
mr_listIter* iter = mr_listGetIterator(n->pendingMessages, AL_START_HEAD);
mr_listNode *node = NULL;
while((node = mr_listNext(iter)) != NULL){
NodeSendMsg* sentMsg = mr_listNodeValue(node);
++sentMsg->retries;
if(MSG_MAX_RETRIES == 0 || sentMsg->retries < MSG_MAX_RETRIES){
MR_ClusterSendMsgToNodeInternal(n, sentMsg);
}else{
RedisModule_Log(mr_staticCtx, "warning", "Gave up of message because failed to send it for more than %d time", MSG_MAX_RETRIES);
mr_listDelNode(n->pendingMessages, node);
}
}
mr_listReleaseIterator(iter);
}
n->runId = MR_STRDUP(reply->str);
n->status = NodeStatus_Connected;
}
static void MR_ClusterReconnect(void* ctx){
Node* n = ctx;
n->reconnectEvent = NULL;
MR_ConnectToShard(n);
}
static void MR_ClusterAsyncDisconnect(void* ctx){
Node* n = ctx;
if (n->c) {
redisAsyncFree(n->c);
n->c = NULL;
}
}
static void MR_ClusterOnDisconnectCallback(const struct redisAsyncContext* c, int status){
RedisModule_Log(mr_staticCtx, "warning", "disconnected : %s:%d, status : %d, %s.", c->c.tcp.host, c->c.tcp.port, status,
c->data ? "will try to reconnect later" : "no context data");
if(!c->data){
return;
}
Node* n = (Node*)c->data;
n->status = NodeStatus_Disconnected;
n->c = NULL;
n->reconnectEvent = MR_EventLoopAddTaskWithDelay(MR_ClusterReconnect, n, RETRY_INTERVAL);
}
char* getConfigValue(RedisModuleCtx *ctx, const char* confName){
RedisModuleCallReply *rep = RedisModule_Call(ctx, "config", "cc", "get",
confName);
RedisModule_Assert(
RedisModule_CallReplyType(rep) == REDISMODULE_REPLY_ARRAY);
if (RedisModule_CallReplyLength(rep) == 0) {
RedisModule_FreeCallReply(rep);
return NULL;
}
RedisModule_Assert(RedisModule_CallReplyLength(rep) == 2);
RedisModuleCallReply *valueRep = RedisModule_CallReplyArrayElement(rep, 1);
RedisModule_Assert(
RedisModule_CallReplyType(valueRep) == REDISMODULE_REPLY_STRING);
size_t len;
const char* valueRepCStr = RedisModule_CallReplyStringPtr(valueRep, &len);
char* res = MR_CALLOC(1, len + 1);
memcpy(res, valueRepCStr, len);
RedisModule_FreeCallReply(rep);
return res;
}
static int checkTLS(char** client_key, char** client_cert, char** ca_cert, char** key_pass){
int ret = 1;
RedisModule_ThreadSafeContextLock(mr_staticCtx);
char* clusterTls = NULL;
char* tlsPort = NULL;
clusterTls = getConfigValue(mr_staticCtx, "tls-cluster");
if (!clusterTls || strcmp(clusterTls, "yes")) {
tlsPort = getConfigValue(mr_staticCtx, "tls-port");
if (!tlsPort || !strcmp(tlsPort, "0")) {
ret = 0;
goto done;
}
}
*client_key = getConfigValue(mr_staticCtx, "tls-key-file");
*client_cert = getConfigValue(mr_staticCtx, "tls-cert-file");
*ca_cert = getConfigValue(mr_staticCtx, "tls-ca-cert-file");
*key_pass = getConfigValue(mr_staticCtx, "tls-key-file-pass");
if (!*client_key || !*client_cert || !*ca_cert) {
ret = 0;
if (*client_key) {
MR_FREE(*client_key);
}
if (*client_cert) {
MR_FREE(*client_cert);
}
if (*ca_cert) {
MR_FREE(*ca_cert);
}
}
done:
if (clusterTls) {
MR_FREE(clusterTls);
}
if (tlsPort) {
MR_FREE(tlsPort);
}
RedisModule_ThreadSafeContextUnlock(mr_staticCtx);
return ret;
}
/* Callback for passing a keyfile password stored as an sds to OpenSSL */
static int MR_TlsPasswordCallback(char *buf, int size, int rwflag, void *u) {
const char *pass = u;
size_t pass_len;
if (!pass) return -1;
pass_len = strlen(pass);
if (pass_len > (size_t) size) return -1;
memcpy(buf, pass, pass_len);
return (int) pass_len;
}
SSL_CTX* MR_CreateSSLContext(const char *cacert_filename,
const char *cert_filename,
const char *private_key_filename,
const char *private_key_pass,
redisSSLContextError *error)
{
SSL_CTX *ssl_ctx = SSL_CTX_new(SSLv23_client_method());
if (!ssl_ctx) {
if (error) *error = REDIS_SSL_CTX_CREATE_FAILED;
goto error;
}
SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);
/* always set the callback, otherwise if key is encrypted and password
* was not given, we will be waiting on stdin. */
SSL_CTX_set_default_passwd_cb(ssl_ctx, MR_TlsPasswordCallback);
SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, (void *) private_key_pass);
if ((cert_filename != NULL && private_key_filename == NULL) ||
(private_key_filename != NULL && cert_filename == NULL)) {
if (error) *error = REDIS_SSL_CTX_CERT_KEY_REQUIRED;
goto error;
}
if (cacert_filename) {
if (!SSL_CTX_load_verify_locations(ssl_ctx, cacert_filename, NULL)) {
if (error) *error = REDIS_SSL_CTX_CA_CERT_LOAD_FAILED;
goto error;
}
}
if (cert_filename) {
if (!SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_filename)) {
if (error) *error = REDIS_SSL_CTX_CLIENT_CERT_LOAD_FAILED;
goto error;
}
if (!SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key_filename, SSL_FILETYPE_PEM)) {
if (error) *error = REDIS_SSL_CTX_PRIVATE_KEY_LOAD_FAILED;
goto error;
}
}
return ssl_ctx;
error:
if (ssl_ctx) SSL_CTX_free(ssl_ctx);
return NULL;
}
static void MR_OnConnectCallback(const struct redisAsyncContext* c, int status){
if(!c->data){
return;
}
Node* n = (Node*)c->data;
if(status == -1){
// connection failed lets try again
n->c = NULL;
n->reconnectEvent = MR_EventLoopAddTaskWithDelay(MR_ClusterReconnect, n, RETRY_INTERVAL);
return;
}
char* client_cert = NULL;
char* client_key = NULL;
char* ca_cert = NULL;
char* key_file_pass = NULL;
if(checkTLS(&client_key, &client_cert, &ca_cert, &key_file_pass)){
redisSSLContextError ssl_error = 0;
SSL_CTX *ssl_context = MR_CreateSSLContext(ca_cert, client_cert, client_key, key_file_pass, &ssl_error);
MR_FREE(client_key);
MR_FREE(client_cert);
MR_FREE(ca_cert);
if (key_file_pass) {
MR_FREE(key_file_pass);
}
if(ssl_context == NULL || ssl_error != 0) {
RedisModule_Log(mr_staticCtx, "warning", "SSL context generation to %s:%d failed, will initiate retry.", c->c.tcp.host, c->c.tcp.port);
// disconnect async, its not possible to free redisAsyncContext here
MR_EventLoopAddTask(MR_ClusterAsyncDisconnect, n);
return;
}
SSL *ssl = SSL_new(ssl_context);
SSL_CTX_free(ssl_context);
if (redisInitiateSSL((redisContext *)(&c->c), ssl) != REDIS_OK) {
const char *err = "Unknown error";
if (c->c.err != 0) {
err = c->c.errstr;
}
RedisModule_Log(mr_staticCtx, "warning", "SSL auth to %s:%d failed, will initiate retry. %s.", c->c.tcp.host, c->c.tcp.port, err);
// disconnect async, its not possible to free redisAsyncContext here
MR_EventLoopAddTask(MR_ClusterAsyncDisconnect, n);
return;
}
}
RedisModule_Log(mr_staticCtx, "notice", "connected : %s:%d, status = %d", c->c.tcp.host, c->c.tcp.port, status);
SendAuthCommandIfNeeded(c, n);
if(n->sendClusterTopologyOnNextConnect && clusterCtx.CurrCluster->clusterSetCommand){
bool isLongForm = IsLongFormClusterSet(clusterCtx.CurrCluster->clusterSetCommandSize);
RedisModule_Log(mr_staticCtx, "notice", "Sending cluster (%s form) topology to %s (%s:%d) after reconnect",
isLongForm ? "long" : "short", n->id, n->ip, n->port);
if (isLongForm)
clusterCtx.CurrCluster->clusterSetCommand[CLUSTERSET_MYID_LONG_FORM_INDEX] = MR_STRDUP(n->id);
redisAsyncCommandArgv((redisAsyncContext*)c, NULL, NULL, clusterCtx.CurrCluster->clusterSetCommandSize, (const char**)clusterCtx.CurrCluster->clusterSetCommand, NULL);
if (isLongForm) {
MR_FREE(clusterCtx.CurrCluster->clusterSetCommand[CLUSTERSET_MYID_LONG_FORM_INDEX]);
clusterCtx.CurrCluster->clusterSetCommand[CLUSTERSET_MYID_LONG_FORM_INDEX] = NULL;
}
n->sendClusterTopologyOnNextConnect = false;
}
redisAsyncCommand((redisAsyncContext*)c, MR_HelloResponseArrived, n, CLUSTER_HELLO_COMMAND);
n->status = NodeStatus_HelloSent;
}
static void MR_ConnectToShard(Node* n){
redisAsyncContext* c = redisAsyncConnect(n->ip, n->port);
if (!c) {
RedisModule_Log(mr_staticCtx, "warning", "Got NULL async connection");
return;
}
if (c->err) {
RedisModule_Log(mr_staticCtx, "warning", "Error: %s\n", c->errstr);
redisAsyncFree(c);
return;
}
c->data = n;
n->c = c;
redisLibeventAttach(c, MR_EventLoopGet());
redisAsyncSetConnectCallback(c, MR_OnConnectCallback);
redisAsyncSetDisconnectCallback(c, MR_ClusterOnDisconnectCallback);
}
static void MR_ClusterConnectToShards(){
mr_dictIterator *iter = mr_dictGetIterator(clusterCtx.CurrCluster->nodes);
mr_dictEntry *entry = NULL;
while((entry = mr_dictNext(iter))){
Node* n = mr_dictGetVal(entry);
if(n->isMe){
continue;
}
if (n->status == NodeStatus_Uninitialized) {
MR_ConnectToShard(n);
n->status = NodeStatus_Disconnected;
}
}
mr_dictReleaseIterator(iter);
}
static void MR_NodeFreeInternals(Node* n){
if (n->reconnectEvent) {
MR_EventLoopDelayTaskCancel(n->reconnectEvent);
n->reconnectEvent = NULL;
}
if (n->resendHelloEvent) {
MR_EventLoopDelayTaskCancel(n->resendHelloEvent);
n->resendHelloEvent = NULL;
}
MR_FREE(n->id);
MR_FREE(n->ip);
if(n->unixSocket){
MR_FREE(n->unixSocket);
}
if(n->password){
MR_FREE(n->password);
}
if(n->runId){
MR_FREE(n->runId);
}
if(n->c){
redisAsyncFree(n->c);
}
mr_listRelease(n->pendingMessages);
mr_listRelease(n->slotRanges);
MR_FREE(n);
}
static void MR_NodeFree(Node* n){
if(n->c){
n->c->data = NULL;
}
n->status = NodeStatus_Free;
MR_NodeFreeInternals(n);
}
static void MR_ClusterFree(){
MR_AbortRunningExecutions();
if(clusterCtx.CurrCluster->myId){
MR_FREE(clusterCtx.CurrCluster->myId);
}
if(clusterCtx.CurrCluster->nodes){
mr_dictIterator *iter = mr_dictGetIterator(clusterCtx.CurrCluster->nodes);
mr_dictEntry *entry = NULL;
while((entry = mr_dictNext(iter))){
Node* n = mr_dictGetVal(entry);
MR_NodeFree(n);
}
mr_dictReleaseIterator(iter);
mr_dictRelease(clusterCtx.CurrCluster->nodes);
}
if(clusterCtx.CurrCluster->clusterSetCommand){
for(int i = 0 ; i < clusterCtx.CurrCluster->clusterSetCommandSize ; ++i){
if(clusterCtx.CurrCluster->clusterSetCommand[i]){
MR_FREE(clusterCtx.CurrCluster->clusterSetCommand[i]);
}
}
MR_FREE(clusterCtx.CurrCluster->clusterSetCommand);
}
MR_FREE(clusterCtx.CurrCluster);
clusterCtx.CurrCluster = NULL;
clusterCtx.minSlot = 0;
clusterCtx.maxSlot = 0;
clusterCtx.clusterSize = 1;
memset(clusterCtx.myId, '0', REDISMODULE_NODE_ID_LEN);
}
static Node* MR_GetNode(const char* id){
mr_dictEntry *entry = mr_dictFind(clusterCtx.CurrCluster->nodes, id);
Node* n = NULL;
if(entry){
n = mr_dictGetVal(entry);
}
return n;
}
static Node* MR_CreateNode(const char* id, const char* ip, unsigned short port, const char* password, const char* unixSocket, long long minSlot, long long maxSlot){
RedisModule_Assert(!MR_GetNode(id));
mr_list* slotRanges = mr_listCreate();
mr_listSetFreeMethod(slotRanges, FreeSlotRange);
if (minSlot <= maxSlot) {
mr_listAddNodeTail(slotRanges, NewSlotRange(minSlot, maxSlot));
}
mr_list* pendingMessages = mr_listCreate();
mr_listSetFreeMethod(pendingMessages, MR_ClusterFreeNodeMsg);
Node* n = MR_ALLOC(sizeof(*n));
*n = (Node){
.id = MR_STRDUP(id),
.ip = MR_STRDUP(ip),
.port = port,
.password = password ? MR_STRDUP(password) : NULL,
.unixSocket = unixSocket ? MR_STRDUP(unixSocket) : NULL,
.c = NULL,
.msgId = 0,
.pendingMessages = pendingMessages,
.slotRanges = slotRanges,
.isMe = false,
.index = 0,
.status = NodeStatus_Uninitialized,
.sendClusterTopologyOnNextConnect = false,
.runId = NULL,
.reconnectEvent = NULL,
.resendHelloEvent = NULL,
};
n->index = mr_dictSize(clusterCtx.CurrCluster->nodes);
n->isMe = strcmp(id, clusterCtx.CurrCluster->myId) == 0;
mr_dictAdd(clusterCtx.CurrCluster->nodes, n->id, n);
return n;
}
static void MR_RefreshClusterData(){
if(clusterCtx.CurrCluster){
MR_ClusterFree();
}
RedisModule_Log(mr_staticCtx, "notice", "Got cluster refresh command");
if(!(RedisModule_GetContextFlags(mr_staticCtx) & REDISMODULE_CTX_FLAGS_CLUSTER)){
return;
}
clusterCtx.CurrCluster = MR_CALLOC(1, sizeof(*clusterCtx.CurrCluster));
// generate runID
RedisModule_GetRandomHexChars(clusterCtx.CurrCluster->runId, RUN_ID_SIZE);
clusterCtx.CurrCluster->runId[RUN_ID_SIZE] = '\0';
clusterCtx.CurrCluster->clusterSetCommand = NULL;
clusterCtx.CurrCluster->clusterSetCommandSize = 0;
clusterCtx.CurrCluster->myId = MR_ALLOC(REDISMODULE_NODE_ID_LEN + 1);
memcpy(clusterCtx.CurrCluster->myId, RedisModule_GetMyClusterID(), REDISMODULE_NODE_ID_LEN);
clusterCtx.CurrCluster->myId[REDISMODULE_NODE_ID_LEN] = '\0';
memcpy(clusterCtx.myId, clusterCtx.CurrCluster->myId, REDISMODULE_NODE_ID_LEN + 1);
clusterCtx.CurrCluster->nodes = mr_dictCreate(&mr_dictTypeHeapStrings, NULL);
RedisModule_ThreadSafeContextLock(mr_staticCtx);
RedisModuleCallReply *allSlotsReply = RedisModule_Call(mr_staticCtx, "cluster", "c", "slots");
RedisModule_ThreadSafeContextUnlock(mr_staticCtx);
RedisModule_Assert(RedisModule_CallReplyType(allSlotsReply) == REDISMODULE_REPLY_ARRAY);
for(size_t i = 0 ; i < RedisModule_CallReplyLength(allSlotsReply) ; ++i){
RedisModuleCallReply *slotRangeReply = RedisModule_CallReplyArrayElement(allSlotsReply, i);
RedisModuleCallReply *minSlotReply = RedisModule_CallReplyArrayElement(slotRangeReply, 0);
RedisModule_Assert(RedisModule_CallReplyType(minSlotReply) == REDISMODULE_REPLY_INTEGER);
long long minSlot = RedisModule_CallReplyInteger(minSlotReply);
RedisModuleCallReply *maxSlotReply = RedisModule_CallReplyArrayElement(slotRangeReply, 1);
RedisModule_Assert(RedisModule_CallReplyType(maxSlotReply) == REDISMODULE_REPLY_INTEGER);
long long maxSlot = RedisModule_CallReplyInteger(maxSlotReply);
RedisModuleCallReply *nodeDetailsReply = RedisModule_CallReplyArrayElement(slotRangeReply, 2);
RedisModule_Assert(RedisModule_CallReplyType(nodeDetailsReply) == REDISMODULE_REPLY_ARRAY);
RedisModule_Assert(RedisModule_CallReplyLength(nodeDetailsReply) >= 3);
RedisModuleCallReply *nodeipReply = RedisModule_CallReplyArrayElement(nodeDetailsReply, 0);
RedisModuleCallReply *nodeidReply = RedisModule_CallReplyArrayElement(nodeDetailsReply, 2);
size_t idLen;
size_t ipLen;
const char* id = RedisModule_CallReplyStringPtr(nodeidReply,&idLen);
const char* ip = RedisModule_CallReplyStringPtr(nodeipReply,&ipLen);
char nodeId[REDISMODULE_NODE_ID_LEN + 1];
memcpy(nodeId, id, REDISMODULE_NODE_ID_LEN);
nodeId[REDISMODULE_NODE_ID_LEN] = '\0';
char nodeIp[ipLen + 1];
memcpy(nodeIp, ip, ipLen);
nodeIp[ipLen] = '\0';
// We need to get the port using the `RedisModule_GetClusterNodeInfo` API because on 7.2
// invoking `cluster slot` from RM_Call will always return the none tls port.
// For for information refer to: https://github.com/redis/redis/pull/12233
int port = 0;
RedisModule_ThreadSafeContextLock(mr_staticCtx);
RedisModule_GetClusterNodeInfo(mr_staticCtx, nodeId, NULL, NULL, &port, NULL);
RedisModule_ThreadSafeContextUnlock(mr_staticCtx);
Node* n = MR_GetNode(nodeId);
if(!n){
/* If we have internal secret we will ignore the clusterCtx.password, we do not need it. */
n = MR_CreateNode(nodeId, nodeIp, (unsigned short)port, RedisModule_GetInternalSecret ? NULL : clusterCtx.password, NULL, minSlot, maxSlot);
}
if (n->isMe) {
clusterCtx.minSlot = minSlot;
clusterCtx.maxSlot = maxSlot;
}
for(int k = minSlot ; k <= maxSlot ; ++k){
clusterCtx.CurrCluster->slots[k] = n;
}
}
RedisModule_FreeCallReply(allSlotsReply);
clusterCtx.clusterSize = mr_dictSize(clusterCtx.CurrCluster->nodes);
mr_dictEmpty(clusterCtx.nodesMsgIds, NULL);
}
static void GenerateRunId(Cluster* cluster){
RedisModule_GetRandomHexChars(cluster->runId, RUN_ID_SIZE);
cluster->runId[RUN_ID_SIZE] = '\0';
}
static void CopyClusterSetArgs(Cluster* cluster, RedisModuleString** argv, int argc){
for(int i = 1 ; i < argc ; ++i){
if (IsLongFormClusterSet(argc) && i == CLUSTERSET_MYID_LONG_FORM_INDEX) {
cluster->clusterSetCommand[i] = NULL;
continue;
}
const char* arg = RedisModule_StringPtrLen(argv[i], NULL);
cluster->clusterSetCommand[i] = MR_STRDUP(arg);
}
}
static void SetMyId(Cluster* cluster, RedisModuleString** argv, int argc){
const char* myId = RedisModule_GetMyClusterID();
size_t myIdLen = REDISMODULE_NODE_ID_LEN;
if (IsLongFormClusterSet(argc)) {
RedisModule_Assert(CLUSTERSET_MYID_LONG_FORM_INDEX < argc);
myId = RedisModule_StringPtrLen(argv[CLUSTERSET_MYID_LONG_FORM_INDEX], &myIdLen);
}
cluster->myId = MR_ALLOC(REDISMODULE_NODE_ID_LEN + 1);
size_t zerosPadding = REDISMODULE_NODE_ID_LEN - myIdLen;
memset(cluster->myId, '0', zerosPadding);
memcpy(cluster->myId + zerosPadding, myId, myIdLen);
cluster->myId[REDISMODULE_NODE_ID_LEN] = '\0';
}
static void InitClusterData(Cluster* cluster, RedisModuleString** argv, int argc){
cluster->clusterSetCommand = MR_ALLOC(sizeof(char*) * argc);
cluster->clusterSetCommandSize = argc;
cluster->clusterSetCommand[0] = MR_STRDUP(CLUSTER_SET_FROM_SHARD_COMMAND);
GenerateRunId(cluster);
CopyClusterSetArgs(cluster, argv, argc);
SetMyId(cluster, argv, argc);
cluster->nodes = mr_dictCreate(&mr_dictTypeHeapStrings, NULL);
}