-
Notifications
You must be signed in to change notification settings - Fork 43
/
hircluster.c
4536 lines (3721 loc) · 129 KB
/
hircluster.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) 2015-2017, Ieshen Zheng <ieshen.zheng at 163 dot com>
* Copyright (c) 2020, Nick <heronr1 at gmail dot com>
* Copyright (c) 2020-2021, Bjorn Svensson <bjorn.a.svensson at est dot tech>
* Copyright (c) 2020-2021, Viktor Söderqvist <viktor.soderqvist at est dot tech>
* Copyright (c) 2021, Red Hat
* 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.
*/
#define _XOPEN_SOURCE 600
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <hiredis/alloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "adlist.h"
#include "command.h"
#include "dict.h"
#include "hiarray.h"
#include "hircluster.h"
#include "hiutil.h"
#include "win32.h"
// Cluster errors are offset by 100 to be sufficiently out of range of
// standard Redis errors
#define REDIS_ERR_CLUSTER_TOO_MANY_RETRIES 100
#define REDIS_ERROR_MOVED "MOVED"
#define REDIS_ERROR_ASK "ASK"
#define REDIS_ERROR_TRYAGAIN "TRYAGAIN"
#define REDIS_ERROR_CLUSTERDOWN "CLUSTERDOWN"
#define REDIS_STATUS_OK "OK"
#define REDIS_COMMAND_CLUSTER_NODES "CLUSTER NODES"
#define REDIS_COMMAND_CLUSTER_SLOTS "CLUSTER SLOTS"
#define REDIS_COMMAND_ASKING "ASKING"
#define IP_PORT_SEPARATOR ':'
#define PORT_CPORT_SEPARATOR '@'
#define CLUSTER_ADDRESS_SEPARATOR ","
#define CLUSTER_DEFAULT_MAX_RETRY_COUNT 5
#define NO_RETRY -1
#define CRLF "\x0d\x0a"
#define CRLF_LEN (sizeof("\x0d\x0a") - 1)
#define SLOTMAP_UPDATE_THROTTLE_USEC 1000000
#define SLOTMAP_UPDATE_ONGOING INT64_MAX
typedef struct cluster_async_data {
redisClusterAsyncContext *acc;
struct cmd *command;
redisClusterCallbackFn *callback;
int retry_count;
void *privdata;
} cluster_async_data;
typedef enum CLUSTER_ERR_TYPE {
CLUSTER_NOT_ERR = 0,
CLUSTER_ERR_MOVED,
CLUSTER_ERR_ASK,
CLUSTER_ERR_TRYAGAIN,
CLUSTER_ERR_CLUSTERDOWN,
CLUSTER_ERR_SENTINEL
} CLUSTER_ERR_TYPE;
static void freeRedisClusterNode(redisClusterNode *node);
static void cluster_slot_destroy(cluster_slot *slot);
static void cluster_open_slot_destroy(copen_slot *oslot);
static int updateNodesAndSlotmap(redisClusterContext *cc, dict *nodes);
static int updateSlotMapAsync(redisClusterAsyncContext *acc,
redisAsyncContext *ac);
void listClusterNodeDestructor(void *val) { freeRedisClusterNode(val); }
void listClusterSlotDestructor(void *val) { cluster_slot_destroy(val); }
unsigned int dictSdsHash(const void *key) {
return dictGenHashFunction((unsigned char *)key, sdslen((char *)key));
}
int dictSdsKeyCompare(void *privdata, const void *key1, const void *key2) {
int l1, l2;
DICT_NOTUSED(privdata);
l1 = sdslen((sds)key1);
l2 = sdslen((sds)key2);
if (l1 != l2)
return 0;
return memcmp(key1, key2, l1) == 0;
}
void dictSdsDestructor(void *privdata, void *val) {
DICT_NOTUSED(privdata);
sdsfree(val);
}
void dictClusterNodeDestructor(void *privdata, void *val) {
DICT_NOTUSED(privdata);
freeRedisClusterNode(val);
}
/* Cluster node hash table
* maps node address (1.2.3.4:6379) to a redisClusterNode
* Has ownership of redisClusterNode memory
*/
dictType clusterNodesDictType = {
dictSdsHash, /* hash function */
NULL, /* key dup */
NULL, /* val dup */
dictSdsKeyCompare, /* key compare */
dictSdsDestructor, /* key destructor */
dictClusterNodeDestructor /* val destructor */
};
/* Referenced cluster node hash table
* maps node id (437c719f5.....) to a redisClusterNode
* No ownership of redisClusterNode memory
*/
dictType clusterNodesRefDictType = {
dictSdsHash, /* hash function */
NULL, /* key dup */
NULL, /* val dup */
dictSdsKeyCompare, /* key compare */
dictSdsDestructor, /* key destructor */
NULL /* val destructor */
};
void listCommandFree(void *command) {
struct cmd *cmd = command;
command_destroy(cmd);
}
/* -----------------------------------------------------------------------------
* Key space handling
* -------------------------------------------------------------------------- */
/* 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). */
static unsigned int keyHashSlot(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(key, keylen) & 0x3FFF;
/* '{' found? Check if we have the corresponding '}'. */
for (e = s + 1; e < keylen; e++)
if (key[e] == '}')
break;
/* No '}' or nothing betweeen {} ? Hash the whole key. */
if (e == keylen || e == s + 1)
return crc16(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(key + s + 1, e - s - 1) & 0x3FFF;
}
static void __redisClusterSetError(redisClusterContext *cc, int type,
const char *str) {
size_t len;
if (cc == NULL) {
return;
}
cc->err = type;
if (str != NULL) {
len = strlen(str);
len = len < (sizeof(cc->errstr) - 1) ? len : (sizeof(cc->errstr) - 1);
memcpy(cc->errstr, str, len);
cc->errstr[len] = '\0';
} else {
/* Only REDIS_ERR_IO may lack a description! */
assert(type == REDIS_ERR_IO);
strerror_r(errno, cc->errstr, sizeof(cc->errstr));
}
}
static int cluster_reply_error_type(redisReply *reply) {
if (reply == NULL) {
return REDIS_ERR;
}
if (reply->type == REDIS_REPLY_ERROR) {
if ((int)strlen(REDIS_ERROR_MOVED) < reply->len &&
memcmp(reply->str, REDIS_ERROR_MOVED, strlen(REDIS_ERROR_MOVED)) ==
0) {
return CLUSTER_ERR_MOVED;
} else if ((int)strlen(REDIS_ERROR_ASK) < reply->len &&
memcmp(reply->str, REDIS_ERROR_ASK,
strlen(REDIS_ERROR_ASK)) == 0) {
return CLUSTER_ERR_ASK;
} else if ((int)strlen(REDIS_ERROR_TRYAGAIN) < reply->len &&
memcmp(reply->str, REDIS_ERROR_TRYAGAIN,
strlen(REDIS_ERROR_TRYAGAIN)) == 0) {
return CLUSTER_ERR_TRYAGAIN;
} else if ((int)strlen(REDIS_ERROR_CLUSTERDOWN) < reply->len &&
memcmp(reply->str, REDIS_ERROR_CLUSTERDOWN,
strlen(REDIS_ERROR_CLUSTERDOWN)) == 0) {
return CLUSTER_ERR_CLUSTERDOWN;
} else {
return CLUSTER_ERR_SENTINEL;
}
}
return CLUSTER_NOT_ERR;
}
/* Create and initiate the cluster node structure */
static redisClusterNode *createRedisClusterNode(void) {
/* use calloc to guarantee all fields are zeroed */
return hi_calloc(1, sizeof(redisClusterNode));
}
/* Cleanup the cluster node structure */
static void freeRedisClusterNode(redisClusterNode *node) {
if (node == NULL) {
return;
}
sdsfree(node->name);
sdsfree(node->addr);
sdsfree(node->host);
redisFree(node->con);
if (node->acon != NULL) {
/* Detach this cluster node from the async context. This makes sure
* that redisAsyncFree() wont attempt to update the pointer via its
* dataCleanup and unlinkAsyncContextAndNode() */
node->acon->data = NULL;
redisAsyncFree(node->acon);
}
if (node->slots != NULL) {
listRelease(node->slots);
}
if (node->slaves != NULL) {
listRelease(node->slaves);
}
copen_slot **oslot;
if (node->migrating) {
while (hiarray_n(node->migrating)) {
oslot = hiarray_pop(node->migrating);
cluster_open_slot_destroy(*oslot);
}
hiarray_destroy(node->migrating);
}
if (node->importing) {
while (hiarray_n(node->importing)) {
oslot = hiarray_pop(node->importing);
cluster_open_slot_destroy(*oslot);
}
hiarray_destroy(node->importing);
}
hi_free(node);
}
static cluster_slot *cluster_slot_create(redisClusterNode *node) {
cluster_slot *slot;
slot = hi_calloc(1, sizeof(*slot));
if (slot == NULL) {
return NULL;
}
slot->node = node;
if (node != NULL) {
ASSERT(node->role == REDIS_ROLE_MASTER);
if (node->slots == NULL) {
node->slots = listCreate();
if (node->slots == NULL) {
cluster_slot_destroy(slot);
return NULL;
}
node->slots->free = listClusterSlotDestructor;
}
if (listAddNodeTail(node->slots, slot) == NULL) {
cluster_slot_destroy(slot);
return NULL;
}
}
return slot;
}
static int cluster_slot_ref_node(cluster_slot *slot, redisClusterNode *node) {
if (slot == NULL || node == NULL) {
return REDIS_ERR;
}
if (node->role != REDIS_ROLE_MASTER) {
return REDIS_ERR;
}
if (node->slots == NULL) {
node->slots = listCreate();
if (node->slots == NULL) {
return REDIS_ERR;
}
node->slots->free = listClusterSlotDestructor;
}
if (listAddNodeTail(node->slots, slot) == NULL) {
return REDIS_ERR;
}
slot->node = node;
return REDIS_OK;
}
static void cluster_slot_destroy(cluster_slot *slot) {
slot->start = 0;
slot->end = 0;
slot->node = NULL;
hi_free(slot);
}
static copen_slot *cluster_open_slot_create(uint32_t slot_num, int migrate,
sds remote_name,
redisClusterNode *node) {
copen_slot *oslot;
oslot = hi_calloc(1, sizeof(*oslot));
if (oslot == NULL) {
return NULL;
}
oslot->slot_num = slot_num;
oslot->migrate = migrate;
oslot->node = node;
oslot->remote_name = sdsdup(remote_name);
if (oslot->remote_name == NULL) {
hi_free(oslot);
return NULL;
}
return oslot;
}
static void cluster_open_slot_destroy(copen_slot *oslot) {
oslot->slot_num = 0;
oslot->migrate = 0;
oslot->node = NULL;
sdsfree(oslot->remote_name);
oslot->remote_name = NULL;
hi_free(oslot);
}
/**
* Handle password authentication in the synchronous API
*/
static int authenticate(redisClusterContext *cc, redisContext *c) {
if (cc == NULL || c == NULL) {
return REDIS_ERR;
}
// Skip if no password configured
if (cc->password == NULL) {
return REDIS_OK;
}
redisReply *reply;
if (cc->username != NULL) {
reply = redisCommand(c, "AUTH %s %s", cc->username, cc->password);
} else {
reply = redisCommand(c, "AUTH %s", cc->password);
}
if (reply == NULL) {
__redisClusterSetError(cc, REDIS_ERR_OTHER,
"Command AUTH reply error (NULL)");
goto error;
}
if (reply->type == REDIS_REPLY_ERROR) {
__redisClusterSetError(cc, REDIS_ERR_OTHER, reply->str);
goto error;
}
freeReplyObject(reply);
return REDIS_OK;
error:
freeReplyObject(reply);
return REDIS_ERR;
}
/**
* Return a new node with the "cluster slots" command reply.
*/
static redisClusterNode *node_get_with_slots(redisClusterContext *cc,
redisReply *host_elem,
redisReply *port_elem,
uint8_t role) {
redisClusterNode *node = NULL;
if (host_elem == NULL || port_elem == NULL) {
return NULL;
}
if (host_elem->type != REDIS_REPLY_STRING || host_elem->len <= 0) {
__redisClusterSetError(cc, REDIS_ERR_OTHER,
"Command(cluster slots) reply error: "
"node ip is not string.");
goto error;
}
if (port_elem->type != REDIS_REPLY_INTEGER || port_elem->integer <= 0) {
__redisClusterSetError(cc, REDIS_ERR_OTHER,
"Command(cluster slots) reply error: "
"node port is not integer.");
goto error;
}
if (!hi_valid_port((int)port_elem->integer)) {
__redisClusterSetError(cc, REDIS_ERR_OTHER,
"Command(cluster slots) reply error: "
"node port is not valid.");
goto error;
}
node = createRedisClusterNode();
if (node == NULL) {
goto oom;
}
if (role == REDIS_ROLE_MASTER) {
node->slots = listCreate();
if (node->slots == NULL) {
goto oom;
}
node->slots->free = listClusterSlotDestructor;
}
node->addr = sdsnewlen(host_elem->str, host_elem->len);
if (node->addr == NULL) {
goto oom;
}
node->addr = sdscatfmt(node->addr, ":%i", port_elem->integer);
if (node->addr == NULL) {
goto oom;
}
node->host = sdsnewlen(host_elem->str, host_elem->len);
if (node->host == NULL) {
goto oom;
}
node->name = NULL;
node->port = (int)port_elem->integer;
node->role = role;
return node;
oom:
__redisClusterSetError(cc, REDIS_ERR_OOM, "Out of memory");
// passthrough
error:
if (node != NULL) {
sdsfree(node->addr);
sdsfree(node->host);
hi_free(node);
}
return NULL;
}
/**
* Return a new node with the "cluster nodes" command reply.
*/
static redisClusterNode *node_get_with_nodes(redisClusterContext *cc,
sds *node_infos, int info_count,
uint8_t role) {
char *p = NULL;
redisClusterNode *node = NULL;
if (info_count < 8) {
return NULL;
}
node = createRedisClusterNode();
if (node == NULL) {
goto oom;
}
if (role == REDIS_ROLE_MASTER) {
node->slots = listCreate();
if (node->slots == NULL) {
goto oom;
}
node->slots->free = listClusterSlotDestructor;
}
/* Handle field <id> */
node->name = node_infos[0];
node_infos[0] = NULL; /* Ownership moved */
/* Handle field <ip:port@cport...>
* Remove @cport... since addr is used as a dict key which should be <ip>:<port> */
if ((p = strchr(node_infos[1], PORT_CPORT_SEPARATOR)) != NULL) {
sdsrange(node_infos[1], 0, p - node_infos[1] - 1 /* skip @ */);
}
node->addr = node_infos[1];
node_infos[1] = NULL; /* Ownership moved */
node->role = role;
/* Get the ip part */
if ((p = strrchr(node->addr, IP_PORT_SEPARATOR)) == NULL) {
__redisClusterSetError(
cc, REDIS_ERR_OTHER,
"server address is incorrect, port separator missing.");
goto error;
}
node->host = sdsnewlen(node->addr, p - node->addr);
if (node->host == NULL) {
goto oom;
}
p++; // remove found separator character
/* Get the port part */
node->port = hi_atoi(p, strlen(p));
return node;
oom:
__redisClusterSetError(cc, REDIS_ERR_OOM, "Out of memory");
// passthrough
error:
freeRedisClusterNode(node);
return NULL;
}
static void cluster_nodes_swap_ctx(dict *nodes_f, dict *nodes_t) {
dictEntry *de_f, *de_t;
redisClusterNode *node_f, *node_t;
redisContext *c;
redisAsyncContext *ac;
if (nodes_f == NULL || nodes_t == NULL) {
return;
}
dictIterator di;
dictInitIterator(&di, nodes_t);
while ((de_t = dictNext(&di)) != NULL) {
node_t = dictGetEntryVal(de_t);
if (node_t == NULL) {
continue;
}
de_f = dictFind(nodes_f, node_t->addr);
if (de_f == NULL) {
continue;
}
node_f = dictGetEntryVal(de_f);
if (node_f->con != NULL) {
c = node_f->con;
node_f->con = node_t->con;
node_t->con = c;
}
if (node_f->acon != NULL) {
ac = node_f->acon;
node_f->acon = node_t->acon;
node_t->acon = ac;
node_t->acon->data = node_t;
if (node_f->acon)
node_f->acon->data = node_f;
}
}
}
static int cluster_master_slave_mapping_with_name(redisClusterContext *cc,
dict **nodes,
redisClusterNode *node,
sds master_name) {
int ret;
dictEntry *di;
redisClusterNode *node_old;
listNode *lnode;
if (node == NULL || master_name == NULL) {
return REDIS_ERR;
}
if (*nodes == NULL) {
*nodes = dictCreate(&clusterNodesRefDictType, NULL);
if (*nodes == NULL) {
goto oom;
}
}
di = dictFind(*nodes, master_name);
if (di == NULL) {
sds key = sdsnewlen(master_name, sdslen(master_name));
if (key == NULL) {
goto oom;
}
ret = dictAdd(*nodes, key, node);
if (ret != DICT_OK) {
sdsfree(key);
goto oom;
}
} else {
node_old = dictGetEntryVal(di);
if (node_old == NULL) {
__redisClusterSetError(cc, REDIS_ERR_OTHER, "dict get value null");
return REDIS_ERR;
}
if (node->role == REDIS_ROLE_MASTER &&
node_old->role == REDIS_ROLE_MASTER) {
__redisClusterSetError(cc, REDIS_ERR_OTHER,
"two masters have the same name");
return REDIS_ERR;
} else if (node->role == REDIS_ROLE_MASTER &&
node_old->role == REDIS_ROLE_SLAVE) {
if (node->slaves == NULL) {
node->slaves = listCreate();
if (node->slaves == NULL) {
goto oom;
}
node->slaves->free = listClusterNodeDestructor;
}
if (node_old->slaves != NULL) {
node_old->slaves->free = NULL;
while (listLength(node_old->slaves) > 0) {
lnode = listFirst(node_old->slaves);
if (listAddNodeHead(node->slaves, lnode->value) == NULL) {
goto oom;
}
listDelNode(node_old->slaves, lnode);
}
listRelease(node_old->slaves);
node_old->slaves = NULL;
}
if (listAddNodeHead(node->slaves, node_old) == NULL) {
goto oom;
}
dictSetHashVal(*nodes, di, node);
} else if (node->role == REDIS_ROLE_SLAVE) {
if (node_old->slaves == NULL) {
node_old->slaves = listCreate();
if (node_old->slaves == NULL) {
goto oom;
}
node_old->slaves->free = listClusterNodeDestructor;
}
if (listAddNodeTail(node_old->slaves, node) == NULL) {
goto oom;
}
} else {
NOT_REACHED();
}
}
return REDIS_OK;
oom:
__redisClusterSetError(cc, REDIS_ERR_OOM, "Out of memory");
return REDIS_ERR;
}
/**
* Parse the "cluster slots" command reply to nodes dict.
*/
dict *parse_cluster_slots(redisClusterContext *cc, redisReply *reply,
int flags) {
int ret;
cluster_slot *slot = NULL;
dict *nodes = NULL;
dictEntry *den;
redisReply *elem_slots;
redisReply *elem_slots_begin, *elem_slots_end;
redisReply *elem_nodes;
redisReply *elem_ip, *elem_port;
redisClusterNode *master = NULL, *slave;
uint32_t i, idx;
if (reply == NULL) {
return NULL;
}
nodes = dictCreate(&clusterNodesDictType, NULL);
if (nodes == NULL) {
goto oom;
}
if (reply->type != REDIS_REPLY_ARRAY || reply->elements <= 0) {
__redisClusterSetError(cc, REDIS_ERR_OTHER,
"Command(cluster slots) reply error: "
"reply is not an array.");
goto error;
}
for (i = 0; i < reply->elements; i++) {
elem_slots = reply->element[i];
if (elem_slots->type != REDIS_REPLY_ARRAY || elem_slots->elements < 3) {
__redisClusterSetError(cc, REDIS_ERR_OTHER,
"Command(cluster slots) reply error: "
"first sub_reply is not an array.");
goto error;
}
slot = cluster_slot_create(NULL);
if (slot == NULL) {
goto oom;
}
// one slots region
for (idx = 0; idx < elem_slots->elements; idx++) {
if (idx == 0) {
elem_slots_begin = elem_slots->element[idx];
if (elem_slots_begin->type != REDIS_REPLY_INTEGER) {
__redisClusterSetError(
cc, REDIS_ERR_OTHER,
"Command(cluster slots) reply error: "
"slot begin is not an integer.");
goto error;
}
slot->start = (int)(elem_slots_begin->integer);
} else if (idx == 1) {
elem_slots_end = elem_slots->element[idx];
if (elem_slots_end->type != REDIS_REPLY_INTEGER) {
__redisClusterSetError(
cc, REDIS_ERR_OTHER,
"Command(cluster slots) reply error: "
"slot end is not an integer.");
goto error;
}
slot->end = (int)(elem_slots_end->integer);
if (slot->start > slot->end) {
__redisClusterSetError(
cc, REDIS_ERR_OTHER,
"Command(cluster slots) reply error: "
"slot begin is bigger than slot end.");
goto error;
}
} else {
elem_nodes = elem_slots->element[idx];
if (elem_nodes->type != REDIS_REPLY_ARRAY ||
elem_nodes->elements < 2) {
__redisClusterSetError(
cc, REDIS_ERR_OTHER,
"Command(cluster slots) reply error: "
"nodes sub_reply is not an correct array.");
goto error;
}
elem_ip = elem_nodes->element[0];
elem_port = elem_nodes->element[1];
if (elem_ip == NULL || elem_port == NULL ||
elem_ip->type != REDIS_REPLY_STRING ||
elem_port->type != REDIS_REPLY_INTEGER) {
__redisClusterSetError(
cc, REDIS_ERR_OTHER,
"Command(cluster slots) reply error: "
"master ip or port is not correct.");
goto error;
}
// this is master.
if (idx == 2) {
sds address = sdsnewlen(elem_ip->str, elem_ip->len);
if (address == NULL) {
goto oom;
}
address = sdscatfmt(address, ":%i", elem_port->integer);
if (address == NULL) {
goto oom;
}
den = dictFind(nodes, address);
sdsfree(address);
// master already exists, break to the next slots region.
if (den != NULL) {
master = dictGetEntryVal(den);
ret = cluster_slot_ref_node(slot, master);
if (ret != REDIS_OK) {
goto oom;
}
slot = NULL;
break;
}
master = node_get_with_slots(cc, elem_ip, elem_port,
REDIS_ROLE_MASTER);
if (master == NULL) {
goto error;
}
sds key = sdsnewlen(master->addr, sdslen(master->addr));
if (key == NULL) {
freeRedisClusterNode(master);
goto oom;
}
ret = dictAdd(nodes, key, master);
if (ret != DICT_OK) {
sdsfree(key);
freeRedisClusterNode(master);
goto oom;
}
ret = cluster_slot_ref_node(slot, master);
if (ret != REDIS_OK) {
goto oom;
}
slot = NULL;
} else if (flags & HIRCLUSTER_FLAG_ADD_SLAVE) {
slave = node_get_with_slots(cc, elem_ip, elem_port,
REDIS_ROLE_SLAVE);
if (slave == NULL) {
goto error;
}
if (master->slaves == NULL) {
master->slaves = listCreate();
if (master->slaves == NULL) {
freeRedisClusterNode(slave);
goto oom;
}
master->slaves->free = listClusterNodeDestructor;
}
if (listAddNodeTail(master->slaves, slave) == NULL) {
freeRedisClusterNode(slave);
goto oom;
}
}
}
}
}
return nodes;
oom:
__redisClusterSetError(cc, REDIS_ERR_OOM, "Out of memory");
// passthrough
error:
if (nodes != NULL) {
dictRelease(nodes);
}
if (slot != NULL) {
cluster_slot_destroy(slot);
}
return NULL;
}
/**
* Parse the "cluster nodes" command reply to nodes dict.
*/
dict *parse_cluster_nodes(redisClusterContext *cc, char *str, int str_len,
int flags) {
int ret;
dict *nodes = NULL;
dict *nodes_name = NULL;
redisClusterNode *master, *slave;
cluster_slot *slot;
char *pos, *start, *end, *line_start, *line_end;
char *role;
int role_len;
int slot_start, slot_end, slot_ranges_found = 0;
sds *part = NULL, *slot_start_end = NULL;
int count_part = 0, count_slot_start_end = 0;
int k;
int len;
nodes = dictCreate(&clusterNodesDictType, NULL);
if (nodes == NULL) {
goto oom;
}
start = str;
end = start + str_len;
line_start = start;
for (pos = start; pos < end; pos++) {
if (*pos == '\n') {
line_end = pos - 1;
len = line_end - line_start;
part = sdssplitlen(line_start, len + 1, " ", 1, &count_part);
if (part == NULL) {
goto oom;
}
if (count_part < 8) {
__redisClusterSetError(cc, REDIS_ERR_OTHER,
"split cluster nodes error");
goto error;
}
// if the address string starts with ":0", skip this node.
if (sdslen(part[1]) >= 2 && memcmp(part[1], ":0", 2) == 0) {
sdsfreesplitres(part, count_part);
count_part = 0;
part = NULL;
start = pos + 1;
line_start = start;
pos = start;
continue;
}
if (sdslen(part[2]) >= 7 && memcmp(part[2], "myself,", 7) == 0) {
role_len = sdslen(part[2]) - 7;
role = part[2] + 7;
} else {
role_len = sdslen(part[2]);
role = part[2];
}
// add master node
if (role_len >= 6 && memcmp(role, "master", 6) == 0) {
master = node_get_with_nodes(cc, part, count_part,
REDIS_ROLE_MASTER);
if (master == NULL) {
goto error;
}
sds key = sdsnewlen(master->addr, sdslen(master->addr));
if (key == NULL) {
freeRedisClusterNode(master);
goto oom;
}
ret = dictAdd(nodes, key, master);
if (ret != DICT_OK) {
// Key already exists, but possibly an OOM error