-
Notifications
You must be signed in to change notification settings - Fork 641
/
cluster_legacy.c
7007 lines (6240 loc) · 296 KB
/
cluster_legacy.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) 2009-2012, Redis Ltd.
* 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.
*/
/*
* cluster_legacy.c contains the implementation of the cluster API that is
* specific to the standard, cluster-bus based clustering mechanism.
*/
#include "server.h"
#include "cluster.h"
#include "cluster_legacy.h"
#include "cluster_slot_stats.h"
#include "endianconv.h"
#include "connection.h"
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <math.h>
#include <sys/file.h>
/* A global reference to myself is handy to make code more clear.
* Myself always points to server.cluster->myself, that is, the clusterNode
* that represents this node. */
clusterNode *myself = NULL;
clusterNode *createClusterNode(char *nodename, int flags);
void clusterAddNode(clusterNode *node);
void clusterAcceptHandler(aeEventLoop *el, int fd, void *privdata, int mask);
void clusterReadHandler(connection *conn);
void clusterSendPing(clusterLink *link, int type);
void clusterSendFail(char *nodename);
void clusterSendFailoverAuthIfNeeded(clusterNode *node, clusterMsg *request);
void clusterUpdateState(void);
list *clusterGetNodesInMyShard(clusterNode *node);
int clusterNodeAddReplica(clusterNode *primary, clusterNode *replica);
int clusterAddSlot(clusterNode *n, int slot);
int clusterDelSlot(int slot);
int clusterDelNodeSlots(clusterNode *node);
int clusterNodeSetSlotBit(clusterNode *n, int slot);
static void clusterSetPrimary(clusterNode *n, int closeSlots, int full_sync_required);
void clusterHandleReplicaFailover(void);
void clusterHandleReplicaMigration(int max_replicas);
int bitmapTestBit(unsigned char *bitmap, int pos);
void bitmapSetBit(unsigned char *bitmap, int pos);
void bitmapClearBit(unsigned char *bitmap, int pos);
void clusterDoBeforeSleep(int flags);
void clusterSendUpdate(clusterLink *link, clusterNode *node);
void resetManualFailover(void);
void clusterCloseAllSlots(void);
void clusterSetNodeAsPrimary(clusterNode *n);
void clusterDelNode(clusterNode *delnode);
sds representClusterNodeFlags(sds ci, uint16_t flags);
sds representSlotInfo(sds ci, uint16_t *slot_info_pairs, int slot_info_pairs_count);
void clusterFreeNodesSlotsInfo(clusterNode *n);
uint64_t clusterGetMaxEpoch(void);
int clusterBumpConfigEpochWithoutConsensus(void);
void moduleCallClusterReceivers(const char *sender_id,
uint64_t module_id,
uint8_t type,
const unsigned char *payload,
uint32_t len);
const char *clusterGetMessageTypeString(int type);
void removeChannelsInSlot(unsigned int slot);
unsigned int countChannelsInSlot(unsigned int hashslot);
unsigned int delKeysInSlot(unsigned int hashslot);
void clusterAddNodeToShard(const char *shard_id, clusterNode *node);
list *clusterLookupNodeListByShardId(const char *shard_id);
void clusterRemoveNodeFromShard(clusterNode *node);
int auxShardIdSetter(clusterNode *n, void *value, size_t length);
sds auxShardIdGetter(clusterNode *n, sds s);
int auxShardIdPresent(clusterNode *n);
int auxHumanNodenameSetter(clusterNode *n, void *value, size_t length);
sds auxHumanNodenameGetter(clusterNode *n, sds s);
int auxHumanNodenamePresent(clusterNode *n);
int auxAnnounceClientIpV4Setter(clusterNode *n, void *value, size_t length);
sds auxAnnounceClientIpV4Getter(clusterNode *n, sds s);
int auxAnnounceClientIpV4Present(clusterNode *n);
int auxAnnounceClientIpV6Setter(clusterNode *n, void *value, size_t length);
sds auxAnnounceClientIpV6Getter(clusterNode *n, sds s);
int auxAnnounceClientIpV6Present(clusterNode *n);
int auxTcpPortSetter(clusterNode *n, void *value, size_t length);
sds auxTcpPortGetter(clusterNode *n, sds s);
int auxTcpPortPresent(clusterNode *n);
int auxTlsPortSetter(clusterNode *n, void *value, size_t length);
sds auxTlsPortGetter(clusterNode *n, sds s);
int auxTlsPortPresent(clusterNode *n);
static void clusterBuildMessageHdrLight(clusterMsgLight *hdr, int type, size_t msglen);
static void clusterBuildMessageHdr(clusterMsg *hdr, int type, size_t msglen);
void freeClusterLink(clusterLink *link);
int verifyClusterNodeId(const char *name, int length);
sds clusterEncodeOpenSlotsAuxField(int rdbflags);
int clusterDecodeOpenSlotsAuxField(int rdbflags, sds s);
/* Only primaries that own slots have voting rights.
* Returns 1 if the node has voting rights, otherwise returns 0. */
static inline int clusterNodeIsVotingPrimary(clusterNode *n) {
return (n->flags & CLUSTER_NODE_PRIMARY) && n->numslots;
}
int getNodeDefaultClientPort(clusterNode *n) {
return server.tls_cluster ? n->tls_port : n->tcp_port;
}
static inline int getNodeDefaultReplicationPort(clusterNode *n) {
return server.tls_replication ? n->tls_port : n->tcp_port;
}
int clusterNodeClientPort(clusterNode *n, int use_tls) {
return use_tls ? n->tls_port : n->tcp_port;
}
static inline int defaultClientPort(void) {
return server.tls_cluster ? server.tls_port : server.port;
}
#define isSlotUnclaimed(slot) \
(server.cluster->slots[slot] == NULL || bitmapTestBit(server.cluster->owner_not_claiming_slot, slot))
#define RCVBUF_INIT_LEN 1024
#define RCVBUF_MIN_READ_LEN 14
static_assert(offsetof(clusterMsg, type) + sizeof(uint16_t) == RCVBUF_MIN_READ_LEN,
"Incorrect length to read to identify type");
#define RCVBUF_MAX_PREALLOC (1 << 20) /* 1MB */
/* Fixed timeout value for cluster operations (milliseconds) */
#define CLUSTER_OPERATION_TIMEOUT 2000
/* Cluster nodes hash table, mapping nodes addresses 1.2.3.4:6379 to
* clusterNode structures. */
dictType clusterNodesDictType = {
dictSdsHash, /* hash function */
NULL, /* key dup */
dictSdsKeyCompare, /* key compare */
dictSdsDestructor, /* key destructor */
NULL, /* val destructor */
NULL /* allow to expand */
};
/* Cluster re-addition blacklist. This maps node IDs to the time
* we can re-add this node. The goal is to avoid reading a removed
* node for some time. */
dictType clusterNodesBlackListDictType = {
dictSdsCaseHash, /* hash function */
NULL, /* key dup */
dictSdsKeyCaseCompare, /* key compare */
dictSdsDestructor, /* key destructor */
NULL, /* val destructor */
NULL /* allow to expand */
};
/* Cluster shards hash table, mapping shard id to list of nodes */
dictType clusterSdsToListType = {
dictSdsHash, /* hash function */
NULL, /* key dup */
dictSdsKeyCompare, /* key compare */
dictSdsDestructor, /* key destructor */
dictListDestructor, /* val destructor */
NULL /* allow to expand */
};
typedef struct {
enum {
ITER_DICT,
ITER_LIST
} type;
union {
dictIterator di;
listIter li;
};
} ClusterNodeIterator;
static void clusterNodeIterInitAllNodes(ClusterNodeIterator *iter) {
iter->type = ITER_DICT;
dictInitSafeIterator(&iter->di, server.cluster->nodes);
}
static void clusterNodeIterInitMyShard(ClusterNodeIterator *iter) {
list *nodes = clusterGetNodesInMyShard(server.cluster->myself);
serverAssert(nodes != NULL);
iter->type = ITER_LIST;
listRewind(nodes, &iter->li);
}
static clusterNode *clusterNodeIterNext(ClusterNodeIterator *iter) {
switch (iter->type) {
case ITER_DICT: {
/* Get the next entry in the dictionary */
dictEntry *de = dictNext(&iter->di);
/* Return the value associated with the entry, or NULL if no more entries */
return de ? dictGetVal(de) : NULL;
}
case ITER_LIST: {
/* Get the next node in the list */
listNode *ln = listNext(&iter->li);
/* Return the value associated with the node, or NULL if no more nodes */
return ln ? listNodeValue(ln) : NULL;
}
}
serverPanic("Unknown iterator type %d", iter->type);
}
static void clusterNodeIterReset(ClusterNodeIterator *iter) {
if (iter->type == ITER_DICT) {
dictResetIterator(&iter->di);
}
}
/* Aux fields were introduced in Redis OSS 7.2 to support the persistence
* of various important node properties, such as shard id, in nodes.conf.
* Aux fields take an explicit format of name=value pairs and have no
* intrinsic order among them. Aux fields are always grouped together
* at the end of the second column of each row after the node's IP
* address/port/cluster_port and the optional hostname. Aux fields
* are separated by ','. */
/* Aux field setter function prototype
* return C_OK when the update is successful; C_ERR otherwise */
typedef int(aux_value_setter)(clusterNode *n, void *value, size_t length);
/* Aux field getter function prototype
* return an sds that is a concatenation of the input sds string and
* the aux value */
typedef sds(aux_value_getter)(clusterNode *n, sds s);
typedef int(aux_value_present)(clusterNode *n);
typedef struct {
char *field;
aux_value_setter *setter;
aux_value_getter *getter;
aux_value_present *isPresent;
} auxFieldHandler;
/* Assign index to each aux field */
typedef enum {
af_shard_id,
af_human_nodename,
af_tcp_port,
af_tls_port,
af_announce_client_ipv4,
af_announce_client_ipv6,
af_count, /* must be the last field */
} auxFieldIndex;
/* Note that
* 1. the order of the elements below must match that of their
* indices as defined in auxFieldIndex
* 2. aux name can contain characters that pass the isValidAuxChar check only */
auxFieldHandler auxFieldHandlers[] = {
{"shard-id", auxShardIdSetter, auxShardIdGetter, auxShardIdPresent},
{"nodename", auxHumanNodenameSetter, auxHumanNodenameGetter, auxHumanNodenamePresent},
{"tcp-port", auxTcpPortSetter, auxTcpPortGetter, auxTcpPortPresent},
{"tls-port", auxTlsPortSetter, auxTlsPortGetter, auxTlsPortPresent},
{"client-ipv4", auxAnnounceClientIpV4Setter, auxAnnounceClientIpV4Getter, auxAnnounceClientIpV4Present},
{"client-ipv6", auxAnnounceClientIpV6Setter, auxAnnounceClientIpV6Getter, auxAnnounceClientIpV6Present},
};
int auxShardIdSetter(clusterNode *n, void *value, size_t length) {
if (verifyClusterNodeId(value, length) == C_ERR) {
return C_ERR;
}
memcpy(n->shard_id, value, CLUSTER_NAMELEN);
/* if n already has replicas, make sure they all agree
* on the shard id */
for (int i = 0; i < n->num_replicas; i++) {
if (memcmp(n->replicas[i]->shard_id, n->shard_id, CLUSTER_NAMELEN) != 0) {
return C_ERR;
}
}
clusterAddNodeToShard(value, n);
return C_OK;
}
sds auxShardIdGetter(clusterNode *n, sds s) {
return sdscatprintf(s, "%.40s", n->shard_id);
}
int auxShardIdPresent(clusterNode *n) {
return strlen(n->shard_id);
}
int auxHumanNodenameSetter(clusterNode *n, void *value, size_t length) {
if (sdslen(n->human_nodename) == length && !strncmp(value, n->human_nodename, length)) {
return C_OK;
}
n->human_nodename = sdscpylen(n->human_nodename, value, length);
return C_OK;
}
sds auxHumanNodenameGetter(clusterNode *n, sds s) {
return sdscatprintf(s, "%s", n->human_nodename);
}
int auxHumanNodenamePresent(clusterNode *n) {
return sdslen(n->human_nodename);
}
int auxAnnounceClientIpV4Setter(clusterNode *n, void *value, size_t length) {
if (sdslen(n->announce_client_ipv4) == length && !strncmp(value, n->announce_client_ipv4, length)) {
/* Unchanged value */
return C_OK;
}
if (length != 0) {
/* Validate IPv4 address */
struct sockaddr_in sa;
if (inet_pton(AF_INET, (const char *)value, &(sa.sin_addr)) == 0) {
return C_ERR;
}
}
n->announce_client_ipv4 = sdscpylen(n->announce_client_ipv4, value, length);
return C_OK;
}
sds auxAnnounceClientIpV4Getter(clusterNode *n, sds s) {
return sdscatprintf(s, "%s", n->announce_client_ipv4);
}
int auxAnnounceClientIpV4Present(clusterNode *n) {
return sdslen(n->announce_client_ipv4) != 0;
}
int auxAnnounceClientIpV6Setter(clusterNode *n, void *value, size_t length) {
if (sdslen(n->announce_client_ipv6) == length && !strncmp(value, n->announce_client_ipv6, length)) {
/* Unchanged value */
return C_OK;
}
if (length != 0) {
/* Validate IPv6 address */
struct sockaddr_in6 sa;
if (inet_pton(AF_INET6, (const char *)value, &(sa.sin6_addr)) == 0) {
return C_ERR;
}
}
n->announce_client_ipv6 = sdscpylen(n->announce_client_ipv6, value, length);
return C_OK;
}
sds auxAnnounceClientIpV6Getter(clusterNode *n, sds s) {
return sdscatprintf(s, "%s", n->announce_client_ipv6);
}
int auxAnnounceClientIpV6Present(clusterNode *n) {
return sdslen(n->announce_client_ipv6) != 0;
}
int auxTcpPortSetter(clusterNode *n, void *value, size_t length) {
if (length > 5 || length < 1) {
return C_ERR;
}
char buf[length + 1];
memcpy(buf, (char *)value, length);
buf[length] = '\0';
n->tcp_port = atoi(buf);
return (n->tcp_port < 0 || n->tcp_port >= 65536) ? C_ERR : C_OK;
}
sds auxTcpPortGetter(clusterNode *n, sds s) {
return sdscatprintf(s, "%d", n->tcp_port);
}
int auxTcpPortPresent(clusterNode *n) {
return n->tcp_port >= 0 && n->tcp_port < 65536;
}
int auxTlsPortSetter(clusterNode *n, void *value, size_t length) {
if (length > 5 || length < 1) {
return C_ERR;
}
char buf[length + 1];
memcpy(buf, (char *)value, length);
buf[length] = '\0';
n->tls_port = atoi(buf);
return (n->tls_port < 0 || n->tls_port >= 65536) ? C_ERR : C_OK;
}
sds auxTlsPortGetter(clusterNode *n, sds s) {
return sdscatprintf(s, "%d", n->tls_port);
}
int auxTlsPortPresent(clusterNode *n) {
return n->tls_port >= 0 && n->tls_port < 65536;
}
/* clusterLink send queue blocks */
typedef struct {
size_t totlen; /* Total length of this block including the message */
int refcount; /* Number of cluster link send msg queues containing the message */
union {
clusterMsg msg;
clusterMsgLight msg_light;
};
} clusterMsgSendBlock;
/* -----------------------------------------------------------------------------
* Initialization
* -------------------------------------------------------------------------- */
/* Load the cluster config from 'filename'.
*
* If the file does not exist or is zero-length (this may happen because
* when we lock the nodes.conf file, we create a zero-length one for the
* sake of locking if it does not already exist), C_ERR is returned.
* If the configuration was loaded from the file, C_OK is returned. */
int clusterLoadConfig(char *filename) {
FILE *fp = fopen(filename, "r");
struct stat sb;
char *line;
int maxline, j;
if (fp == NULL) {
if (errno == ENOENT) {
return C_ERR;
} else {
serverLog(LL_WARNING, "Loading the cluster node config from %s: %s", filename, strerror(errno));
exit(1);
}
}
if (valkey_fstat(fileno(fp), &sb) == -1) {
serverLog(LL_WARNING, "Unable to obtain the cluster node config file stat %s: %s", filename, strerror(errno));
exit(1);
}
/* Check if the file is zero-length: if so return C_ERR to signal
* we have to write the config. */
if (sb.st_size == 0) {
fclose(fp);
return C_ERR;
}
/* Parse the file. Note that single lines of the cluster config file can
* be really long as they include all the hash slots of the node.
* This means in the worst possible case, half of the slots will be
* present in a single line, possibly in importing or migrating state, so
* together with the node ID of the sender/receiver.
*
* To simplify we allocate 1024+CLUSTER_SLOTS*128 bytes per line. */
maxline = 1024 + CLUSTER_SLOTS * 128;
line = zmalloc(maxline);
while (fgets(line, maxline, fp) != NULL) {
int argc, aux_argc;
sds *argv, *aux_argv;
clusterNode *n, *primary;
char *p, *s;
/* Skip blank lines, they can be created either by users manually
* editing nodes.conf or by the config writing process if stopped
* before the truncate() call. */
if (line[0] == '\n' || line[0] == '\0') continue;
/* Split the line into arguments for processing. */
argv = sdssplitargs(line, &argc);
if (argv == NULL) goto fmterr;
/* Handle the special "vars" line. Don't pretend it is the last
* line even if it actually is when generated by the server. */
if (strcasecmp(argv[0], "vars") == 0) {
if (!(argc % 2)) goto fmterr;
for (j = 1; j < argc; j += 2) {
if (strcasecmp(argv[j], "currentEpoch") == 0) {
server.cluster->currentEpoch = strtoull(argv[j + 1], NULL, 10);
} else if (strcasecmp(argv[j], "lastVoteEpoch") == 0) {
server.cluster->lastVoteEpoch = strtoull(argv[j + 1], NULL, 10);
} else {
serverLog(LL_NOTICE, "Skipping unknown cluster config variable '%s'", argv[j]);
}
}
sdsfreesplitres(argv, argc);
continue;
}
/* Regular config lines have at least eight fields */
if (argc < 8) {
sdsfreesplitres(argv, argc);
goto fmterr;
}
/* Create this node if it does not exist */
if (verifyClusterNodeId(argv[0], sdslen(argv[0])) == C_ERR) {
sdsfreesplitres(argv, argc);
goto fmterr;
}
n = clusterLookupNode(argv[0], sdslen(argv[0]));
if (!n) {
n = createClusterNode(argv[0], 0);
clusterAddNode(n);
}
/* Format for the node address and auxiliary argument information:
* ip:port[@cport][,hostname][,aux=val]*] */
aux_argv = sdssplitlen(argv[1], sdslen(argv[1]), ",", 1, &aux_argc);
if (aux_argv == NULL) {
sdsfreesplitres(argv, argc);
goto fmterr;
}
/* Hostname is an optional argument that defines the endpoint
* that can be reported to clients instead of IP. */
if (aux_argc > 1 && sdslen(aux_argv[1]) > 0) {
n->hostname = sdscpy(n->hostname, aux_argv[1]);
} else if (sdslen(n->hostname) != 0) {
sdsclear(n->hostname);
}
/* All fields after hostname are auxiliary and they take on
* the format of "aux=val" where both aux and val can contain
* characters that pass the isValidAuxChar check only. The order
* of the aux fields is insignificant. */
int aux_tcp_port = 0;
int aux_tls_port = 0;
for (int i = 2; i < aux_argc; i++) {
int field_argc;
sds *field_argv;
field_argv = sdssplitlen(aux_argv[i], sdslen(aux_argv[i]), "=", 1, &field_argc);
if (field_argv == NULL || field_argc != 2) {
/* Invalid aux field format */
if (field_argv != NULL) sdsfreesplitres(field_argv, field_argc);
sdsfreesplitres(aux_argv, aux_argc);
sdsfreesplitres(argv, argc);
goto fmterr;
}
/* Validate that both aux and value contain valid characters only */
for (unsigned j = 0; j < 2; j++) {
if (!isValidAuxString(field_argv[j], sdslen(field_argv[j]))) {
/* Invalid aux field format */
sdsfreesplitres(field_argv, field_argc);
sdsfreesplitres(aux_argv, aux_argc);
sdsfreesplitres(argv, argc);
goto fmterr;
}
}
/* Note that we don't expect lots of aux fields in the foreseeable
* future so a linear search is completely fine. */
int field_found = 0;
for (unsigned j = 0; j < numElements(auxFieldHandlers); j++) {
if (sdslen(field_argv[0]) != strlen(auxFieldHandlers[j].field) ||
memcmp(field_argv[0], auxFieldHandlers[j].field, sdslen(field_argv[0])) != 0) {
continue;
}
field_found = 1;
aux_tcp_port |= j == af_tcp_port;
aux_tls_port |= j == af_tls_port;
if (auxFieldHandlers[j].setter(n, field_argv[1], sdslen(field_argv[1])) != C_OK) {
/* Invalid aux field format */
sdsfreesplitres(field_argv, field_argc);
sdsfreesplitres(aux_argv, aux_argc);
sdsfreesplitres(argv, argc);
goto fmterr;
}
}
if (field_found == 0) {
/* Invalid aux field format */
sdsfreesplitres(field_argv, field_argc);
sdsfreesplitres(aux_argv, aux_argc);
sdsfreesplitres(argv, argc);
goto fmterr;
}
sdsfreesplitres(field_argv, field_argc);
}
/* Address and port */
if ((p = strrchr(aux_argv[0], ':')) == NULL) {
sdsfreesplitres(aux_argv, aux_argc);
sdsfreesplitres(argv, argc);
goto fmterr;
}
*p = '\0';
memcpy(n->ip, aux_argv[0], strlen(aux_argv[0]) + 1);
char *port = p + 1;
char *busp = strchr(port, '@');
if (busp) {
*busp = '\0';
busp++;
}
/* If neither TCP or TLS port is found in aux field, it is considered
* an old version of nodes.conf file.*/
if (!aux_tcp_port && !aux_tls_port) {
if (server.tls_cluster) {
n->tls_port = atoi(port);
} else {
n->tcp_port = atoi(port);
}
} else if (!aux_tcp_port) {
n->tcp_port = atoi(port);
} else if (!aux_tls_port) {
n->tls_port = atoi(port);
}
/* In older versions of nodes.conf the "@busport" part is missing.
* In this case we set it to the default offset of 10000 from the
* base port. */
n->cport = busp ? atoi(busp) : (getNodeDefaultClientPort(n) + CLUSTER_PORT_INCR);
/* The plaintext port for client in a TLS cluster (n->pport) is not
* stored in nodes.conf. It is received later over the bus protocol. */
sdsfreesplitres(aux_argv, aux_argc);
/* Parse flags */
p = s = argv[2];
while (p) {
p = strchr(s, ',');
if (p) *p = '\0';
if (!strcasecmp(s, "myself")) {
serverAssert(server.cluster->myself == NULL);
myself = server.cluster->myself = n;
n->flags |= CLUSTER_NODE_MYSELF;
} else if (!strcasecmp(s, "master") || !strcasecmp(s, "primary")) {
n->flags |= CLUSTER_NODE_PRIMARY;
} else if (!strcasecmp(s, "slave") || !strcasecmp(s, "replica")) {
n->flags |= CLUSTER_NODE_REPLICA;
} else if (!strcasecmp(s, "fail?")) {
n->flags |= CLUSTER_NODE_PFAIL;
} else if (!strcasecmp(s, "fail")) {
n->flags |= CLUSTER_NODE_FAIL;
n->fail_time = mstime();
} else if (!strcasecmp(s, "handshake")) {
n->flags |= CLUSTER_NODE_HANDSHAKE;
} else if (!strcasecmp(s, "noaddr")) {
n->flags |= CLUSTER_NODE_NOADDR;
} else if (!strcasecmp(s, "nofailover")) {
n->flags |= CLUSTER_NODE_NOFAILOVER;
} else if (!strcasecmp(s, "noflags")) {
/* nothing to do */
} else {
serverPanic("Unknown flag in %s cluster config file", SERVER_TITLE);
}
if (p) s = p + 1;
}
/* Get primary if any. Set the primary and populate primary's
* replica list. */
if (argv[3][0] != '-') {
if (verifyClusterNodeId(argv[3], sdslen(argv[3])) == C_ERR) {
sdsfreesplitres(argv, argc);
goto fmterr;
}
primary = clusterLookupNode(argv[3], sdslen(argv[3]));
if (!primary) {
primary = createClusterNode(argv[3], 0);
clusterAddNode(primary);
}
/* shard_id can be absent if we are loading a nodes.conf generated
* by an older version; we should follow the primary's
* shard_id in this case */
if (auxFieldHandlers[af_shard_id].isPresent(n) == 0) {
memcpy(n->shard_id, primary->shard_id, CLUSTER_NAMELEN);
clusterAddNodeToShard(primary->shard_id, n);
} else if (clusterGetNodesInMyShard(primary) != NULL &&
memcmp(primary->shard_id, n->shard_id, CLUSTER_NAMELEN) != 0) {
/* If the primary has been added to a shard, make sure this
* node has the same persisted shard id as the primary. */
sdsfreesplitres(argv, argc);
goto fmterr;
}
n->replicaof = primary;
clusterNodeAddReplica(primary, n);
} else if (auxFieldHandlers[af_shard_id].isPresent(n) == 0) {
/* n is a primary but it does not have a persisted shard_id.
* This happens if we are loading a nodes.conf generated by
* an older version of the server. We should manually update the
* shard membership in this case */
clusterAddNodeToShard(n->shard_id, n);
}
/* Set ping sent / pong received timestamps */
if (atoi(argv[4])) n->ping_sent = mstime();
if (atoi(argv[5])) n->pong_received = mstime();
/* Set configEpoch for this node.
* If the node is a replica, set its config epoch to 0.
* If it's a primary, load the config epoch from the configuration file. */
n->configEpoch = (nodeIsReplica(n) && n->replicaof) ? 0 : strtoull(argv[6], NULL, 10);
/* Populate hash slots served by this instance. */
for (j = 8; j < argc; j++) {
int start, stop;
if (argv[j][0] == '[') {
/* Here we handle migrating / importing slots */
int slot;
char direction;
clusterNode *cn;
p = strchr(argv[j], '-');
serverAssert(p != NULL);
*p = '\0';
direction = p[1]; /* Either '>' or '<' */
slot = atoi(argv[j] + 1);
if (slot < 0 || slot >= CLUSTER_SLOTS) {
sdsfreesplitres(argv, argc);
goto fmterr;
}
p += 3;
char *pr = strchr(p, ']');
size_t node_len = pr - p;
if (pr == NULL || verifyClusterNodeId(p, node_len) == C_ERR) {
sdsfreesplitres(argv, argc);
goto fmterr;
}
cn = clusterLookupNode(p, CLUSTER_NAMELEN);
if (!cn) {
cn = createClusterNode(p, 0);
clusterAddNode(cn);
}
if (direction == '>') {
server.cluster->migrating_slots_to[slot] = cn;
} else {
server.cluster->importing_slots_from[slot] = cn;
}
continue;
} else if ((p = strchr(argv[j], '-')) != NULL) {
*p = '\0';
start = atoi(argv[j]);
stop = atoi(p + 1);
} else {
start = stop = atoi(argv[j]);
}
if (start < 0 || start >= CLUSTER_SLOTS || stop < 0 || stop >= CLUSTER_SLOTS) {
sdsfreesplitres(argv, argc);
goto fmterr;
}
while (start <= stop) clusterAddSlot(n, start++);
}
sdsfreesplitres(argv, argc);
}
/* Config sanity check */
if (server.cluster->myself == NULL) goto fmterr;
zfree(line);
fclose(fp);
serverLog(LL_NOTICE, "Node configuration loaded, I'm %.40s", myself->name);
/* Something that should never happen: currentEpoch smaller than
* the max epoch found in the nodes configuration. However we handle this
* as some form of protection against manual editing of critical files. */
if (clusterGetMaxEpoch() > server.cluster->currentEpoch) {
server.cluster->currentEpoch = clusterGetMaxEpoch();
}
return C_OK;
fmterr:
serverLog(LL_WARNING, "Unrecoverable error: corrupted cluster config file \"%s\".", line);
zfree(line);
if (fp) fclose(fp);
exit(1);
}
/* Cluster node configuration is exactly the same as CLUSTER NODES output.
*
* This function writes the node config and returns C_OK, on error C_ERR
* is returned.
*
* Note: we need to write the file in an atomic way from the point of view
* of the POSIX filesystem semantics, so that if the server is stopped
* or crashes during the write, we'll end with either the old file or the
* new one. Since we have the full payload to write available we can use
* a single write to write the whole file. If the pre-existing file was
* bigger we pad our payload with newlines that are anyway ignored and truncate
* the file afterward. */
int clusterSaveConfig(int do_fsync) {
sds ci, tmpfilename;
size_t content_size, offset = 0;
ssize_t written_bytes;
int fd = -1;
int retval = C_ERR;
server.cluster->todo_before_sleep &= ~CLUSTER_TODO_SAVE_CONFIG;
/* Get the nodes description and concatenate our "vars" directive to
* save currentEpoch and lastVoteEpoch. */
ci = clusterGenNodesDescription(NULL, CLUSTER_NODE_HANDSHAKE, 0);
ci = sdscatprintf(ci, "vars currentEpoch %llu lastVoteEpoch %llu\n",
(unsigned long long)server.cluster->currentEpoch,
(unsigned long long)server.cluster->lastVoteEpoch);
content_size = sdslen(ci);
/* Create a temp file with the new content. */
tmpfilename = sdscatfmt(sdsempty(), "%s.tmp-%i-%I", server.cluster_configfile, (int)getpid(), mstime());
if ((fd = open(tmpfilename, O_WRONLY | O_CREAT, 0644)) == -1) {
serverLog(LL_WARNING, "Could not open temp cluster config file: %s", strerror(errno));
goto cleanup;
}
while (offset < content_size) {
written_bytes = write(fd, ci + offset, content_size - offset);
if (written_bytes <= 0) {
if (errno == EINTR) continue;
serverLog(LL_WARNING, "Failed after writing (%zd) bytes to tmp cluster config file: %s", offset,
strerror(errno));
goto cleanup;
}
offset += written_bytes;
}
if (do_fsync) {
server.cluster->todo_before_sleep &= ~CLUSTER_TODO_FSYNC_CONFIG;
if (valkey_fsync(fd) == -1) {
serverLog(LL_WARNING, "Could not sync tmp cluster config file: %s", strerror(errno));
goto cleanup;
}
}
if (rename(tmpfilename, server.cluster_configfile) == -1) {
serverLog(LL_WARNING, "Could not rename tmp cluster config file: %s", strerror(errno));
goto cleanup;
}
if (do_fsync) {
if (fsyncFileDir(server.cluster_configfile) == -1) {
serverLog(LL_WARNING, "Could not sync cluster config file dir: %s", strerror(errno));
goto cleanup;
}
}
retval = C_OK; /* If we reached this point, everything is fine. */
cleanup:
if (fd != -1) close(fd);
if (retval) unlink(tmpfilename);
sdsfree(tmpfilename);
sdsfree(ci);
return retval;
}
void clusterSaveConfigOrDie(int do_fsync) {
if (clusterSaveConfig(do_fsync) == C_ERR) {
serverLog(LL_WARNING, "Fatal: can't update cluster config file.");
exit(1);
}
}
/* Lock the cluster config using flock(), and retain the file descriptor used to
* acquire the lock so that the file will be locked as long as the process is up.
*
* This works because we always update nodes.conf with a new version
* in-place, reopening the file, and writing to it in place (later adjusting
* the length with ftruncate()).
*
* On success C_OK is returned, otherwise an error is logged and
* the function returns C_ERR to signal a lock was not acquired. */
int clusterLockConfig(char *filename) {
/* flock() does not exist on Solaris
* and a fcntl-based solution won't help, as we constantly re-open that file,
* which will release _all_ locks anyway
*/
#if !defined(__sun)
/* To lock it, we need to open the file in a way it is created if
* it does not exist, otherwise there is a race condition with other
* processes. */
int fd = open(filename, O_WRONLY | O_CREAT | O_CLOEXEC, 0644);
if (fd == -1) {
serverLog(LL_WARNING, "Can't open %s in order to acquire a lock: %s", filename, strerror(errno));
return C_ERR;
}
if (flock(fd, LOCK_EX | LOCK_NB) == -1) {
if (errno == EWOULDBLOCK) {
serverLog(LL_WARNING,
"Sorry, the cluster configuration file %s is already used "
"by a different Cluster node. Please make sure that "
"different nodes use different cluster configuration "
"files.",
filename);
} else {
serverLog(LL_WARNING, "Impossible to lock %s: %s", filename, strerror(errno));
}
close(fd);
return C_ERR;
}
/* Lock acquired: leak the 'fd' by not closing it until shutdown time, so that
* we'll retain the lock to the file as long as the process exists.
*
* After fork, the child process will get the fd opened by the parent process,
* we need save `fd` to `cluster_config_file_lock_fd`, so that in serverFork(),
* it will be closed in the child process.
* If it is not closed, when the main process is killed -9, but the child process
* (valkey-aof-rewrite) is still alive, the fd(lock) will still be held by the
* child process, and the main process will fail to get lock, means fail to start. */
server.cluster_config_file_lock_fd = fd;
#else
UNUSED(filename);
#endif /* __sun */
return C_OK;
}
/* Derives our ports to be announced in the cluster bus. */
void deriveAnnouncedPorts(int *announced_tcp_port, int *announced_tls_port, int *announced_cport) {
/* Config overriding announced ports. */
*announced_tcp_port = server.cluster_announce_port ? server.cluster_announce_port : server.port;
*announced_tls_port = server.cluster_announce_tls_port ? server.cluster_announce_tls_port : server.tls_port;
/* Derive cluster bus port. */
if (server.cluster_announce_bus_port) {
*announced_cport = server.cluster_announce_bus_port;
} else if (server.cluster_port) {
*announced_cport = server.cluster_port;
} else {
*announced_cport = defaultClientPort() + CLUSTER_PORT_INCR;
}
}
/* Some flags (currently just the NOFAILOVER flag) may need to be updated
* in the "myself" node based on the current configuration of the node,
* that may change at runtime via CONFIG SET. This function changes the
* set of flags in myself->flags accordingly. */
void clusterUpdateMyselfFlags(void) {
if (!myself) return;
int oldflags = myself->flags;
int nofailover = server.cluster_replica_no_failover ? CLUSTER_NODE_NOFAILOVER : 0;
myself->flags &= ~CLUSTER_NODE_NOFAILOVER;
myself->flags |= nofailover;
myself->flags |= CLUSTER_NODE_LIGHT_HDR_SUPPORTED;
if (myself->flags != oldflags) {
clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG | CLUSTER_TODO_UPDATE_STATE);
}
}
/* We want to take myself->port/cport/pport in sync with the
* cluster-announce-port/cluster-announce-bus-port/cluster-announce-tls-port option.
* The option can be set at runtime via CONFIG SET. */
void clusterUpdateMyselfAnnouncedPorts(void) {
if (!myself) return;
deriveAnnouncedPorts(&myself->tcp_port, &myself->tls_port, &myself->cport);
}
/* We want to take myself->ip in sync with the cluster-announce-ip option.
* The option can be set at runtime via CONFIG SET. */
void clusterUpdateMyselfIp(void) {
if (!myself) return;
static char *prev_ip = NULL;
char *curr_ip = server.cluster_announce_ip;
int changed = 0;
if (prev_ip == NULL && curr_ip != NULL)
changed = 1;
else if (prev_ip != NULL && curr_ip == NULL)
changed = 1;
else if (prev_ip && curr_ip && strcmp(prev_ip, curr_ip))
changed = 1;
if (changed) {
if (prev_ip) zfree(prev_ip);
prev_ip = curr_ip;
if (curr_ip) {
/* We always take a copy of the previous IP address, by
* duplicating the string. This way later we can check if
* the address really changed. */
prev_ip = zstrdup(prev_ip);
valkey_strlcpy(myself->ip, server.cluster_announce_ip, NET_IP_STR_LEN);
} else {
myself->ip[0] = '\0'; /* Force autodetection. */
}
}
}
static void updateSdsExtensionField(char **field, const char *value) {
if (value != NULL && !strcmp(value, *field)) {
return;