]>
git.saurik.com Git - redis.git/blob - src/cluster.c
6d117acadf306ee548eee7c3abbe9cdcf5aef6de
7 void clusterAcceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
8 void clusterReadHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
9 void clusterSendPing(clusterLink
*link
, int type
);
10 void clusterSendFail(char *nodename
);
11 void clusterUpdateState(void);
12 int clusterNodeGetSlotBit(clusterNode
*n
, int slot
);
13 sds
clusterGenNodesDescription(void);
14 clusterNode
*clusterLookupNode(char *name
);
15 int clusterNodeAddSlave(clusterNode
*master
, clusterNode
*slave
);
16 int clusterAddSlot(clusterNode
*n
, int slot
);
18 /* -----------------------------------------------------------------------------
20 * -------------------------------------------------------------------------- */
22 void clusterGetRandomName(char *p
) {
23 FILE *fp
= fopen("/dev/urandom","r");
24 char *charset
= "0123456789abcdef";
28 redisLog(REDIS_WARNING
,
29 "Unrecovarable error: can't open /dev/urandom:%s" ,strerror(errno
));
32 fread(p
,REDIS_CLUSTER_NAMELEN
,1,fp
);
33 for (j
= 0; j
< REDIS_CLUSTER_NAMELEN
; j
++)
34 p
[j
] = charset
[p
[j
] & 0x0F];
38 int clusterLoadConfig(char *filename
) {
39 FILE *fp
= fopen(filename
,"r");
43 if (fp
== NULL
) return REDIS_ERR
;
45 /* Parse the file. Note that single liens of the cluster config file can
46 * be really long as they include all the hash slots of the node.
47 * This means in the worst possible case REDIS_CLUSTER_SLOTS/2 integers.
48 * To simplify we allocate 1024+REDIS_CLUSTER_SLOTS*16 bytes per line. */
49 maxline
= 1024+REDIS_CLUSTER_SLOTS
*16;
50 line
= zmalloc(maxline
);
51 while(fgets(line
,maxline
,fp
) != NULL
) {
53 sds
*argv
= sdssplitargs(line
,&argc
);
54 clusterNode
*n
, *master
;
57 /* Create this node if it does not exist */
58 n
= clusterLookupNode(argv
[0]);
60 n
= createClusterNode(argv
[0],0);
63 /* Address and port */
64 if ((p
= strchr(argv
[1],':')) == NULL
) goto fmterr
;
66 memcpy(n
->ip
,argv
[1],strlen(argv
[1])+1);
74 if (!strcasecmp(s
,"myself")) {
75 redisAssert(server
.cluster
.myself
== NULL
);
76 server
.cluster
.myself
= n
;
77 n
->flags
|= REDIS_NODE_MYSELF
;
78 } else if (!strcasecmp(s
,"master")) {
79 n
->flags
|= REDIS_NODE_MASTER
;
80 } else if (!strcasecmp(s
,"slave")) {
81 n
->flags
|= REDIS_NODE_SLAVE
;
82 } else if (!strcasecmp(s
,"fail?")) {
83 n
->flags
|= REDIS_NODE_PFAIL
;
84 } else if (!strcasecmp(s
,"fail")) {
85 n
->flags
|= REDIS_NODE_FAIL
;
86 } else if (!strcasecmp(s
,"handshake")) {
87 n
->flags
|= REDIS_NODE_HANDSHAKE
;
88 } else if (!strcasecmp(s
,"noaddr")) {
89 n
->flags
|= REDIS_NODE_NOADDR
;
90 } else if (!strcasecmp(s
,"noflags")) {
93 redisPanic("Unknown flag in redis cluster config file");
98 /* Get master if any. Set the master and populate master's
100 if (argv
[3][0] != '-') {
101 master
= clusterLookupNode(argv
[3]);
103 master
= createClusterNode(argv
[3],0);
104 clusterAddNode(master
);
107 clusterNodeAddSlave(master
,n
);
110 /* Populate hash slots served by this instance. */
111 for (j
= 7; j
< argc
; j
++) {
114 if ((p
= strchr(argv
[j
],'-')) != NULL
) {
116 start
= atoi(argv
[j
]);
119 start
= stop
= atoi(argv
[j
]);
121 while(start
<= stop
) clusterAddSlot(n
, start
++);
124 sdssplitargs_free(argv
,argc
);
129 /* Config sanity check */
130 redisAssert(server
.cluster
.myself
!= NULL
);
131 redisLog(REDIS_NOTICE
,"Node configuration loaded, I'm %.40s",
132 server
.cluster
.myself
->name
);
136 redisLog(REDIS_WARNING
,"Unrecovarable error: corrupted cluster config file.");
141 /* Cluster node configuration is exactly the same as CLUSTER NODES output.
143 * This function writes the node config and returns 0, on error -1
145 int clusterSaveConfig(void) {
146 sds ci
= clusterGenNodesDescription();
149 if ((fd
= open(server
.cluster
.configfile
,O_WRONLY
|O_CREAT
|O_TRUNC
,0644))
151 if (write(fd
,ci
,sdslen(ci
)) != (ssize_t
)sdslen(ci
)) goto err
;
161 void clusterSaveConfigOrDie(void) {
162 if (clusterSaveConfig() == -1) {
163 redisLog(REDIS_WARNING
,"Fatal: can't update cluster config file.");
168 void clusterInit(void) {
171 server
.cluster
.myself
= NULL
;
172 server
.cluster
.state
= REDIS_CLUSTER_FAIL
;
173 server
.cluster
.nodes
= dictCreate(&clusterNodesDictType
,NULL
);
174 server
.cluster
.node_timeout
= 15;
175 memset(server
.cluster
.migrating_slots_to
,0,
176 sizeof(server
.cluster
.migrating_slots_to
));
177 memset(server
.cluster
.importing_slots_from
,0,
178 sizeof(server
.cluster
.importing_slots_from
));
179 memset(server
.cluster
.slots
,0,
180 sizeof(server
.cluster
.slots
));
181 if (clusterLoadConfig(server
.cluster
.configfile
) == REDIS_ERR
) {
182 /* No configuration found. We will just use the random name provided
183 * by the createClusterNode() function. */
184 server
.cluster
.myself
= createClusterNode(NULL
,REDIS_NODE_MYSELF
);
185 redisLog(REDIS_NOTICE
,"No cluster configuration found, I'm %.40s",
186 server
.cluster
.myself
->name
);
187 clusterAddNode(server
.cluster
.myself
);
190 if (saveconf
) clusterSaveConfigOrDie();
191 /* We need a listening TCP port for our cluster messaging needs */
192 server
.cfd
= anetTcpServer(server
.neterr
,
193 server
.port
+REDIS_CLUSTER_PORT_INCR
, server
.bindaddr
);
194 if (server
.cfd
== -1) {
195 redisLog(REDIS_WARNING
, "Opening cluster TCP port: %s", server
.neterr
);
198 if (aeCreateFileEvent(server
.el
, server
.cfd
, AE_READABLE
,
199 clusterAcceptHandler
, NULL
) == AE_ERR
) oom("creating file event");
202 /* -----------------------------------------------------------------------------
203 * CLUSTER communication link
204 * -------------------------------------------------------------------------- */
206 clusterLink
*createClusterLink(clusterNode
*node
) {
207 clusterLink
*link
= zmalloc(sizeof(*link
));
208 link
->sndbuf
= sdsempty();
209 link
->rcvbuf
= sdsempty();
215 /* Free a cluster link, but does not free the associated node of course.
216 * Just this function will make sure that the original node associated
217 * with this link will have the 'link' field set to NULL. */
218 void freeClusterLink(clusterLink
*link
) {
219 if (link
->fd
!= -1) {
220 aeDeleteFileEvent(server
.el
, link
->fd
, AE_WRITABLE
);
221 aeDeleteFileEvent(server
.el
, link
->fd
, AE_READABLE
);
223 sdsfree(link
->sndbuf
);
224 sdsfree(link
->rcvbuf
);
226 link
->node
->link
= NULL
;
231 void clusterAcceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
237 REDIS_NOTUSED(privdata
);
239 cfd
= anetTcpAccept(server
.neterr
, fd
, cip
, &cport
);
241 redisLog(REDIS_VERBOSE
,"Accepting cluster node: %s", server
.neterr
);
244 redisLog(REDIS_VERBOSE
,"Accepted cluster node %s:%d", cip
, cport
);
245 /* We need to create a temporary node in order to read the incoming
246 * packet in a valid contest. This node will be released once we
247 * read the packet and reply. */
248 link
= createClusterLink(NULL
);
250 aeCreateFileEvent(server
.el
,cfd
,AE_READABLE
,clusterReadHandler
,link
);
253 /* -----------------------------------------------------------------------------
255 * -------------------------------------------------------------------------- */
257 /* We have 4096 hash slots. The hash slot of a given key is obtained
258 * as the least significant 12 bits of the crc16 of the key. */
259 unsigned int keyHashSlot(char *key
, int keylen
) {
260 return crc16(key
,keylen
) & 0x0FFF;
263 /* -----------------------------------------------------------------------------
265 * -------------------------------------------------------------------------- */
267 /* Create a new cluster node, with the specified flags.
268 * If "nodename" is NULL this is considered a first handshake and a random
269 * node name is assigned to this node (it will be fixed later when we'll
270 * receive the first pong).
272 * The node is created and returned to the user, but it is not automatically
273 * added to the nodes hash table. */
274 clusterNode
*createClusterNode(char *nodename
, int flags
) {
275 clusterNode
*node
= zmalloc(sizeof(*node
));
278 memcpy(node
->name
, nodename
, REDIS_CLUSTER_NAMELEN
);
280 clusterGetRandomName(node
->name
);
282 memset(node
->slots
,0,sizeof(node
->slots
));
285 node
->slaveof
= NULL
;
286 node
->ping_sent
= node
->pong_received
= 0;
287 node
->configdigest
= NULL
;
288 node
->configdigest_ts
= 0;
293 int clusterNodeRemoveSlave(clusterNode
*master
, clusterNode
*slave
) {
296 for (j
= 0; j
< master
->numslaves
; j
++) {
297 if (master
->slaves
[j
] == slave
) {
298 memmove(master
->slaves
+j
,master
->slaves
+(j
+1),
299 (master
->numslaves
-1)-j
);
307 int clusterNodeAddSlave(clusterNode
*master
, clusterNode
*slave
) {
310 /* If it's already a slave, don't add it again. */
311 for (j
= 0; j
< master
->numslaves
; j
++)
312 if (master
->slaves
[j
] == slave
) return REDIS_ERR
;
313 master
->slaves
= zrealloc(master
->slaves
,
314 sizeof(clusterNode
*)*(master
->numslaves
+1));
315 master
->slaves
[master
->numslaves
] = slave
;
320 void clusterNodeResetSlaves(clusterNode
*n
) {
325 void freeClusterNode(clusterNode
*n
) {
328 nodename
= sdsnewlen(n
->name
, REDIS_CLUSTER_NAMELEN
);
329 redisAssert(dictDelete(server
.cluster
.nodes
,nodename
) == DICT_OK
);
331 if (n
->slaveof
) clusterNodeRemoveSlave(n
->slaveof
, n
);
332 if (n
->link
) freeClusterLink(n
->link
);
336 /* Add a node to the nodes hash table */
337 int clusterAddNode(clusterNode
*node
) {
340 retval
= dictAdd(server
.cluster
.nodes
,
341 sdsnewlen(node
->name
,REDIS_CLUSTER_NAMELEN
), node
);
342 return (retval
== DICT_OK
) ? REDIS_OK
: REDIS_ERR
;
345 /* Node lookup by name */
346 clusterNode
*clusterLookupNode(char *name
) {
347 sds s
= sdsnewlen(name
, REDIS_CLUSTER_NAMELEN
);
348 struct dictEntry
*de
;
350 de
= dictFind(server
.cluster
.nodes
,s
);
352 if (de
== NULL
) return NULL
;
353 return dictGetEntryVal(de
);
356 /* This is only used after the handshake. When we connect a given IP/PORT
357 * as a result of CLUSTER MEET we don't have the node name yet, so we
358 * pick a random one, and will fix it when we receive the PONG request using
360 void clusterRenameNode(clusterNode
*node
, char *newname
) {
362 sds s
= sdsnewlen(node
->name
, REDIS_CLUSTER_NAMELEN
);
364 redisLog(REDIS_DEBUG
,"Renaming node %.40s into %.40s",
365 node
->name
, newname
);
366 retval
= dictDelete(server
.cluster
.nodes
, s
);
368 redisAssert(retval
== DICT_OK
);
369 memcpy(node
->name
, newname
, REDIS_CLUSTER_NAMELEN
);
370 clusterAddNode(node
);
373 /* -----------------------------------------------------------------------------
374 * CLUSTER messages exchange - PING/PONG and gossip
375 * -------------------------------------------------------------------------- */
377 /* Process the gossip section of PING or PONG packets.
378 * Note that this function assumes that the packet is already sanity-checked
379 * by the caller, not in the content of the gossip section, but in the
381 void clusterProcessGossipSection(clusterMsg
*hdr
, clusterLink
*link
) {
382 uint16_t count
= ntohs(hdr
->count
);
383 clusterMsgDataGossip
*g
= (clusterMsgDataGossip
*) hdr
->data
.ping
.gossip
;
384 clusterNode
*sender
= link
->node
? link
->node
: clusterLookupNode(hdr
->sender
);
388 uint16_t flags
= ntohs(g
->flags
);
391 if (flags
== 0) ci
= sdscat(ci
,"noflags,");
392 if (flags
& REDIS_NODE_MYSELF
) ci
= sdscat(ci
,"myself,");
393 if (flags
& REDIS_NODE_MASTER
) ci
= sdscat(ci
,"master,");
394 if (flags
& REDIS_NODE_SLAVE
) ci
= sdscat(ci
,"slave,");
395 if (flags
& REDIS_NODE_PFAIL
) ci
= sdscat(ci
,"fail?,");
396 if (flags
& REDIS_NODE_FAIL
) ci
= sdscat(ci
,"fail,");
397 if (flags
& REDIS_NODE_HANDSHAKE
) ci
= sdscat(ci
,"handshake,");
398 if (flags
& REDIS_NODE_NOADDR
) ci
= sdscat(ci
,"noaddr,");
399 if (ci
[sdslen(ci
)-1] == ',') ci
[sdslen(ci
)-1] = ' ';
401 redisLog(REDIS_DEBUG
,"GOSSIP %.40s %s:%d %s",
408 /* Update our state accordingly to the gossip sections */
409 node
= clusterLookupNode(g
->nodename
);
411 /* We already know this node. Let's start updating the last
412 * time PONG figure if it is newer than our figure.
413 * Note that it's not a problem if we have a PING already
414 * in progress against this node. */
415 if (node
->pong_received
< ntohl(g
->pong_received
)) {
416 redisLog(REDIS_DEBUG
,"Node pong_received updated by gossip");
417 node
->pong_received
= ntohl(g
->pong_received
);
419 /* Mark this node as FAILED if we think it is possibly failing
420 * and another node also thinks it's failing. */
421 if (node
->flags
& REDIS_NODE_PFAIL
&&
422 (flags
& (REDIS_NODE_FAIL
|REDIS_NODE_PFAIL
)))
424 redisLog(REDIS_NOTICE
,"Received a PFAIL acknowledge from node %.40s, marking node %.40s as FAIL!", hdr
->sender
, node
->name
);
425 node
->flags
&= ~REDIS_NODE_PFAIL
;
426 node
->flags
|= REDIS_NODE_FAIL
;
427 /* Broadcast the failing node name to everybody */
428 clusterSendFail(node
->name
);
429 clusterUpdateState();
430 clusterSaveConfigOrDie();
433 /* If it's not in NOADDR state and we don't have it, we
434 * start an handshake process against this IP/PORT pairs.
436 * Note that we require that the sender of this gossip message
437 * is a well known node in our cluster, otherwise we risk
438 * joining another cluster. */
439 if (sender
&& !(flags
& REDIS_NODE_NOADDR
)) {
440 clusterNode
*newnode
;
442 redisLog(REDIS_DEBUG
,"Adding the new node");
443 newnode
= createClusterNode(NULL
,REDIS_NODE_HANDSHAKE
);
444 memcpy(newnode
->ip
,g
->ip
,sizeof(g
->ip
));
445 newnode
->port
= ntohs(g
->port
);
446 clusterAddNode(newnode
);
455 /* IP -> string conversion. 'buf' is supposed to at least be 16 bytes. */
456 void nodeIp2String(char *buf
, clusterLink
*link
) {
457 struct sockaddr_in sa
;
458 socklen_t salen
= sizeof(sa
);
460 if (getpeername(link
->fd
, (struct sockaddr
*) &sa
, &salen
) == -1)
461 redisPanic("getpeername() failed.");
462 strncpy(buf
,inet_ntoa(sa
.sin_addr
),sizeof(link
->node
->ip
));
466 /* Update the node address to the IP address that can be extracted
467 * from link->fd, and at the specified port. */
468 void nodeUpdateAddress(clusterNode
*node
, clusterLink
*link
, int port
) {
471 /* When this function is called, there is a packet to process starting
472 * at node->rcvbuf. Releasing the buffer is up to the caller, so this
473 * function should just handle the higher level stuff of processing the
474 * packet, modifying the cluster state if needed.
476 * The function returns 1 if the link is still valid after the packet
477 * was processed, otherwise 0 if the link was freed since the packet
478 * processing lead to some inconsistency error (for instance a PONG
479 * received from the wrong sender ID). */
480 int clusterProcessPacket(clusterLink
*link
) {
481 clusterMsg
*hdr
= (clusterMsg
*) link
->rcvbuf
;
482 uint32_t totlen
= ntohl(hdr
->totlen
);
483 uint16_t type
= ntohs(hdr
->type
);
486 redisLog(REDIS_DEBUG
,"--- packet to process %lu bytes (%lu) ---",
487 (unsigned long) totlen
, sdslen(link
->rcvbuf
));
488 if (totlen
< 8) return 1;
489 if (totlen
> sdslen(link
->rcvbuf
)) return 1;
490 if (type
== CLUSTERMSG_TYPE_PING
|| type
== CLUSTERMSG_TYPE_PONG
||
491 type
== CLUSTERMSG_TYPE_MEET
)
493 uint16_t count
= ntohs(hdr
->count
);
494 uint32_t explen
; /* expected length of this packet */
496 explen
= sizeof(clusterMsg
)-sizeof(union clusterMsgData
);
497 explen
+= (sizeof(clusterMsgDataGossip
)*count
);
498 if (totlen
!= explen
) return 1;
500 if (type
== CLUSTERMSG_TYPE_FAIL
) {
501 uint32_t explen
= sizeof(clusterMsg
)-sizeof(union clusterMsgData
);
503 explen
+= sizeof(clusterMsgDataFail
);
504 if (totlen
!= explen
) return 1;
507 sender
= clusterLookupNode(hdr
->sender
);
508 if (type
== CLUSTERMSG_TYPE_PING
|| type
== CLUSTERMSG_TYPE_MEET
) {
509 int update_config
= 0;
510 redisLog(REDIS_DEBUG
,"Ping packet received: %p", link
->node
);
512 /* Add this node if it is new for us and the msg type is MEET.
513 * In this stage we don't try to add the node with the right
514 * flags, slaveof pointer, and so forth, as this details will be
515 * resolved when we'll receive PONGs from the server. */
516 if (!sender
&& type
== CLUSTERMSG_TYPE_MEET
) {
519 node
= createClusterNode(NULL
,REDIS_NODE_HANDSHAKE
);
520 nodeIp2String(node
->ip
,link
);
521 node
->port
= ntohs(hdr
->port
);
522 clusterAddNode(node
);
526 /* Get info from the gossip section */
527 clusterProcessGossipSection(hdr
,link
);
529 /* Anyway reply with a PONG */
530 clusterSendPing(link
,CLUSTERMSG_TYPE_PONG
);
532 /* Update config if needed */
533 if (update_config
) clusterSaveConfigOrDie();
534 } else if (type
== CLUSTERMSG_TYPE_PONG
) {
535 int update_state
= 0;
536 int update_config
= 0;
538 redisLog(REDIS_DEBUG
,"Pong packet received: %p", link
->node
);
540 if (link
->node
->flags
& REDIS_NODE_HANDSHAKE
) {
541 /* If we already have this node, try to change the
542 * IP/port of the node with the new one. */
544 redisLog(REDIS_WARNING
,
545 "Handshake error: we already know node %.40s, updating the address if needed.", sender
->name
);
546 nodeUpdateAddress(sender
,link
,ntohs(hdr
->port
));
547 freeClusterNode(link
->node
); /* will free the link too */
551 /* First thing to do is replacing the random name with the
552 * right node name if this was an handshake stage. */
553 clusterRenameNode(link
->node
, hdr
->sender
);
554 redisLog(REDIS_DEBUG
,"Handshake with node %.40s completed.",
556 link
->node
->flags
&= ~REDIS_NODE_HANDSHAKE
;
558 } else if (memcmp(link
->node
->name
,hdr
->sender
,
559 REDIS_CLUSTER_NAMELEN
) != 0)
561 /* If the reply has a non matching node ID we
562 * disconnect this node and set it as not having an associated
564 redisLog(REDIS_DEBUG
,"PONG contains mismatching sender ID");
565 link
->node
->flags
|= REDIS_NODE_NOADDR
;
566 freeClusterLink(link
);
568 /* FIXME: remove this node if we already have it.
570 * If we already have it but the IP is different, use
571 * the new one if the old node is in FAIL, PFAIL, or NOADDR
576 /* Update our info about the node */
577 link
->node
->pong_received
= time(NULL
);
579 /* Update master/slave info */
581 if (!memcmp(hdr
->slaveof
,REDIS_NODE_NULL_NAME
,
582 sizeof(hdr
->slaveof
)))
584 sender
->flags
&= ~REDIS_NODE_SLAVE
;
585 sender
->flags
|= REDIS_NODE_MASTER
;
586 sender
->slaveof
= NULL
;
588 clusterNode
*master
= clusterLookupNode(hdr
->slaveof
);
590 sender
->flags
&= ~REDIS_NODE_MASTER
;
591 sender
->flags
|= REDIS_NODE_SLAVE
;
592 if (sender
->numslaves
) clusterNodeResetSlaves(sender
);
593 if (master
) clusterNodeAddSlave(master
,sender
);
597 /* Update our info about served slots if this new node is serving
598 * slots that are not served from our point of view. */
599 if (sender
&& sender
->flags
& REDIS_NODE_MASTER
) {
603 memcmp(sender
->slots
,hdr
->myslots
,sizeof(hdr
->myslots
)) != 0;
604 memcpy(sender
->slots
,hdr
->myslots
,sizeof(hdr
->myslots
));
606 for (j
= 0; j
< REDIS_CLUSTER_SLOTS
; j
++) {
607 if (clusterNodeGetSlotBit(sender
,j
)) {
608 if (server
.cluster
.slots
[j
] == sender
) continue;
609 if (server
.cluster
.slots
[j
] == NULL
||
610 server
.cluster
.slots
[j
]->flags
& REDIS_NODE_FAIL
)
612 server
.cluster
.slots
[j
] = sender
;
613 update_state
= update_config
= 1;
620 /* Get info from the gossip section */
621 clusterProcessGossipSection(hdr
,link
);
623 /* Update the cluster state if needed */
624 if (update_state
) clusterUpdateState();
625 if (update_config
) clusterSaveConfigOrDie();
626 } else if (type
== CLUSTERMSG_TYPE_FAIL
&& sender
) {
627 clusterNode
*failing
;
629 failing
= clusterLookupNode(hdr
->data
.fail
.about
.nodename
);
630 if (failing
&& !(failing
->flags
& REDIS_NODE_FAIL
)) {
631 redisLog(REDIS_NOTICE
,
632 "FAIL message received from %.40s about %.40s",
633 hdr
->sender
, hdr
->data
.fail
.about
.nodename
);
634 failing
->flags
|= REDIS_NODE_FAIL
;
635 failing
->flags
&= ~REDIS_NODE_PFAIL
;
636 clusterUpdateState();
637 clusterSaveConfigOrDie();
640 redisLog(REDIS_NOTICE
,"Received unknown packet type: %d", type
);
645 /* This function is called when we detect the link with this node is lost.
646 We set the node as no longer connected. The Cluster Cron will detect
647 this connection and will try to get it connected again.
649 Instead if the node is a temporary node used to accept a query, we
650 completely free the node on error. */
651 void handleLinkIOError(clusterLink
*link
) {
652 freeClusterLink(link
);
655 /* Send data. This is handled using a trivial send buffer that gets
656 * consumed by write(). We don't try to optimize this for speed too much
657 * as this is a very low traffic channel. */
658 void clusterWriteHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
659 clusterLink
*link
= (clusterLink
*) privdata
;
664 nwritten
= write(fd
, link
->sndbuf
, sdslen(link
->sndbuf
));
666 redisLog(REDIS_NOTICE
,"I/O error writing to node link: %s",
668 handleLinkIOError(link
);
671 link
->sndbuf
= sdsrange(link
->sndbuf
,nwritten
,-1);
672 if (sdslen(link
->sndbuf
) == 0)
673 aeDeleteFileEvent(server
.el
, link
->fd
, AE_WRITABLE
);
676 /* Read data. Try to read the first field of the header first to check the
677 * full length of the packet. When a whole packet is in memory this function
678 * will call the function to process the packet. And so forth. */
679 void clusterReadHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
683 clusterLink
*link
= (clusterLink
*) privdata
;
689 if (sdslen(link
->rcvbuf
) >= 4) {
690 hdr
= (clusterMsg
*) link
->rcvbuf
;
691 readlen
= ntohl(hdr
->totlen
) - sdslen(link
->rcvbuf
);
693 readlen
= 4 - sdslen(link
->rcvbuf
);
696 nread
= read(fd
,buf
,readlen
);
697 if (nread
== -1 && errno
== EAGAIN
) return; /* Just no data */
701 redisLog(REDIS_NOTICE
,"I/O error reading from node link: %s",
702 (nread
== 0) ? "connection closed" : strerror(errno
));
703 handleLinkIOError(link
);
706 /* Read data and recast the pointer to the new buffer. */
707 link
->rcvbuf
= sdscatlen(link
->rcvbuf
,buf
,nread
);
708 hdr
= (clusterMsg
*) link
->rcvbuf
;
711 /* Total length obtained? read the payload now instead of burning
712 * cycles waiting for a new event to fire. */
713 if (sdslen(link
->rcvbuf
) == 4) goto again
;
715 /* Whole packet in memory? We can process it. */
716 if (sdslen(link
->rcvbuf
) == ntohl(hdr
->totlen
)) {
717 if (clusterProcessPacket(link
)) {
718 sdsfree(link
->rcvbuf
);
719 link
->rcvbuf
= sdsempty();
724 /* Put stuff into the send buffer. */
725 void clusterSendMessage(clusterLink
*link
, unsigned char *msg
, size_t msglen
) {
726 if (sdslen(link
->sndbuf
) == 0 && msglen
!= 0)
727 aeCreateFileEvent(server
.el
,link
->fd
,AE_WRITABLE
,
728 clusterWriteHandler
,link
);
730 link
->sndbuf
= sdscatlen(link
->sndbuf
, msg
, msglen
);
733 /* Build the message header */
734 void clusterBuildMessageHdr(clusterMsg
*hdr
, int type
) {
737 memset(hdr
,0,sizeof(*hdr
));
738 hdr
->type
= htons(type
);
739 memcpy(hdr
->sender
,server
.cluster
.myself
->name
,REDIS_CLUSTER_NAMELEN
);
740 memcpy(hdr
->myslots
,server
.cluster
.myself
->slots
,
741 sizeof(hdr
->myslots
));
742 memset(hdr
->slaveof
,0,REDIS_CLUSTER_NAMELEN
);
743 if (server
.cluster
.myself
->slaveof
!= NULL
) {
744 memcpy(hdr
->slaveof
,server
.cluster
.myself
->slaveof
->name
,
745 REDIS_CLUSTER_NAMELEN
);
747 hdr
->port
= htons(server
.port
);
748 hdr
->state
= server
.cluster
.state
;
749 memset(hdr
->configdigest
,0,32); /* FIXME: set config digest */
751 if (type
== CLUSTERMSG_TYPE_FAIL
) {
752 totlen
= sizeof(clusterMsg
)-sizeof(union clusterMsgData
);
753 totlen
+= sizeof(clusterMsgDataFail
);
755 hdr
->totlen
= htonl(totlen
);
756 /* For PING, PONG, and MEET, fixing the totlen field is up to the caller */
759 /* Send a PING or PONG packet to the specified node, making sure to add enough
760 * gossip informations. */
761 void clusterSendPing(clusterLink
*link
, int type
) {
762 unsigned char buf
[1024];
763 clusterMsg
*hdr
= (clusterMsg
*) buf
;
764 int gossipcount
= 0, totlen
;
765 /* freshnodes is the number of nodes we can still use to populate the
766 * gossip section of the ping packet. Basically we start with the nodes
767 * we have in memory minus two (ourself and the node we are sending the
768 * message to). Every time we add a node we decrement the counter, so when
769 * it will drop to <= zero we know there is no more gossip info we can
771 int freshnodes
= dictSize(server
.cluster
.nodes
)-2;
773 if (link
->node
&& type
== CLUSTERMSG_TYPE_PING
)
774 link
->node
->ping_sent
= time(NULL
);
775 clusterBuildMessageHdr(hdr
,type
);
777 /* Populate the gossip fields */
778 while(freshnodes
> 0 && gossipcount
< 3) {
779 struct dictEntry
*de
= dictGetRandomKey(server
.cluster
.nodes
);
780 clusterNode
*this = dictGetEntryVal(de
);
781 clusterMsgDataGossip
*gossip
;
784 /* Not interesting to gossip about ourself.
785 * Nor to send gossip info about HANDSHAKE state nodes (zero info). */
786 if (this == server
.cluster
.myself
||
787 this->flags
& REDIS_NODE_HANDSHAKE
) {
788 freshnodes
--; /* otherwise we may loop forever. */
792 /* Check if we already added this node */
793 for (j
= 0; j
< gossipcount
; j
++) {
794 if (memcmp(hdr
->data
.ping
.gossip
[j
].nodename
,this->name
,
795 REDIS_CLUSTER_NAMELEN
) == 0) break;
797 if (j
!= gossipcount
) continue;
801 gossip
= &(hdr
->data
.ping
.gossip
[gossipcount
]);
802 memcpy(gossip
->nodename
,this->name
,REDIS_CLUSTER_NAMELEN
);
803 gossip
->ping_sent
= htonl(this->ping_sent
);
804 gossip
->pong_received
= htonl(this->pong_received
);
805 memcpy(gossip
->ip
,this->ip
,sizeof(this->ip
));
806 gossip
->port
= htons(this->port
);
807 gossip
->flags
= htons(this->flags
);
810 totlen
= sizeof(clusterMsg
)-sizeof(union clusterMsgData
);
811 totlen
+= (sizeof(clusterMsgDataGossip
)*gossipcount
);
812 hdr
->count
= htons(gossipcount
);
813 hdr
->totlen
= htonl(totlen
);
814 clusterSendMessage(link
,buf
,totlen
);
817 /* Send a message to all the nodes with a reliable link */
818 void clusterBroadcastMessage(void *buf
, size_t len
) {
822 di
= dictGetIterator(server
.cluster
.nodes
);
823 while((de
= dictNext(di
)) != NULL
) {
824 clusterNode
*node
= dictGetEntryVal(de
);
826 if (!node
->link
) continue;
827 if (node
->flags
& (REDIS_NODE_MYSELF
|REDIS_NODE_NOADDR
)) continue;
828 clusterSendMessage(node
->link
,buf
,len
);
830 dictReleaseIterator(di
);
833 /* Send a FAIL message to all the nodes we are able to contact.
834 * The FAIL message is sent when we detect that a node is failing
835 * (REDIS_NODE_PFAIL) and we also receive a gossip confirmation of this:
836 * we switch the node state to REDIS_NODE_FAIL and ask all the other
837 * nodes to do the same ASAP. */
838 void clusterSendFail(char *nodename
) {
839 unsigned char buf
[1024];
840 clusterMsg
*hdr
= (clusterMsg
*) buf
;
842 clusterBuildMessageHdr(hdr
,CLUSTERMSG_TYPE_FAIL
);
843 memcpy(hdr
->data
.fail
.about
.nodename
,nodename
,REDIS_CLUSTER_NAMELEN
);
844 clusterBroadcastMessage(buf
,ntohl(hdr
->totlen
));
847 /* -----------------------------------------------------------------------------
849 * -------------------------------------------------------------------------- */
851 /* This is executed 1 time every second */
852 void clusterCron(void) {
856 time_t min_ping_sent
= 0;
857 clusterNode
*min_ping_node
= NULL
;
859 /* Check if we have disconnected nodes and reestablish the connection. */
860 di
= dictGetIterator(server
.cluster
.nodes
);
861 while((de
= dictNext(di
)) != NULL
) {
862 clusterNode
*node
= dictGetEntryVal(de
);
864 if (node
->flags
& (REDIS_NODE_MYSELF
|REDIS_NODE_NOADDR
)) continue;
865 if (node
->link
== NULL
) {
869 fd
= anetTcpNonBlockConnect(server
.neterr
, node
->ip
,
870 node
->port
+REDIS_CLUSTER_PORT_INCR
);
871 if (fd
== -1) continue;
872 link
= createClusterLink(node
);
875 aeCreateFileEvent(server
.el
,link
->fd
,AE_READABLE
,clusterReadHandler
,link
);
876 /* If the node is flagged as MEET, we send a MEET message instead
877 * of a PING one, to force the receiver to add us in its node
879 clusterSendPing(link
, node
->flags
& REDIS_NODE_MEET
?
880 CLUSTERMSG_TYPE_MEET
: CLUSTERMSG_TYPE_PING
);
881 /* We can clear the flag after the first packet is sent.
882 * If we'll never receive a PONG, we'll never send new packets
883 * to this node. Instead after the PONG is received and we
884 * are no longer in meet/handshake status, we want to send
885 * normal PING packets. */
886 node
->flags
&= ~REDIS_NODE_MEET
;
888 redisLog(REDIS_NOTICE
,"Connecting with Node %.40s at %s:%d", node
->name
, node
->ip
, node
->port
+REDIS_CLUSTER_PORT_INCR
);
891 dictReleaseIterator(di
);
893 /* Ping some random node. Check a few random nodes and ping the one with
894 * the oldest ping_sent time */
895 for (j
= 0; j
< 5; j
++) {
896 de
= dictGetRandomKey(server
.cluster
.nodes
);
897 clusterNode
*this = dictGetEntryVal(de
);
899 if (this->link
== NULL
) continue;
900 if (this->flags
& (REDIS_NODE_MYSELF
|REDIS_NODE_HANDSHAKE
)) continue;
901 if (min_ping_node
== NULL
|| min_ping_sent
> this->ping_sent
) {
902 min_ping_node
= this;
903 min_ping_sent
= this->ping_sent
;
907 redisLog(REDIS_DEBUG
,"Pinging node %40s", min_ping_node
->name
);
908 clusterSendPing(min_ping_node
->link
, CLUSTERMSG_TYPE_PING
);
911 /* Iterate nodes to check if we need to flag something as failing */
912 di
= dictGetIterator(server
.cluster
.nodes
);
913 while((de
= dictNext(di
)) != NULL
) {
914 clusterNode
*node
= dictGetEntryVal(de
);
918 (REDIS_NODE_MYSELF
|REDIS_NODE_NOADDR
|REDIS_NODE_HANDSHAKE
|
919 REDIS_NODE_FAIL
)) continue;
920 /* Check only if we already sent a ping and did not received
922 if (node
->ping_sent
== 0 ||
923 node
->ping_sent
<= node
->pong_received
) continue;
925 delay
= time(NULL
) - node
->pong_received
;
926 if (node
->flags
& REDIS_NODE_PFAIL
) {
927 /* The PFAIL condition can be reversed without external
928 * help if it is not transitive (that is, if it does not
929 * turn into a FAIL state). */
930 if (delay
< server
.cluster
.node_timeout
)
931 node
->flags
&= ~REDIS_NODE_PFAIL
;
933 if (delay
>= server
.cluster
.node_timeout
) {
934 redisLog(REDIS_DEBUG
,"*** NODE %.40s possibly failing",
936 node
->flags
|= REDIS_NODE_PFAIL
;
940 dictReleaseIterator(di
);
943 /* -----------------------------------------------------------------------------
945 * -------------------------------------------------------------------------- */
947 /* Set the slot bit and return the old value. */
948 int clusterNodeSetSlotBit(clusterNode
*n
, int slot
) {
951 int old
= (n
->slots
[byte
] & (1<<bit
)) != 0;
952 n
->slots
[byte
] |= 1<<bit
;
956 /* Clear the slot bit and return the old value. */
957 int clusterNodeClearSlotBit(clusterNode
*n
, int slot
) {
960 int old
= (n
->slots
[byte
] & (1<<bit
)) != 0;
961 n
->slots
[byte
] &= ~(1<<bit
);
965 /* Return the slot bit from the cluster node structure. */
966 int clusterNodeGetSlotBit(clusterNode
*n
, int slot
) {
969 return (n
->slots
[byte
] & (1<<bit
)) != 0;
972 /* Add the specified slot to the list of slots that node 'n' will
973 * serve. Return REDIS_OK if the operation ended with success.
974 * If the slot is already assigned to another instance this is considered
975 * an error and REDIS_ERR is returned. */
976 int clusterAddSlot(clusterNode
*n
, int slot
) {
977 redisAssert(clusterNodeSetSlotBit(n
,slot
) == 0);
978 server
.cluster
.slots
[slot
] = server
.cluster
.myself
;
979 printf("SLOT %d added to %.40s\n", slot
, n
->name
);
983 /* -----------------------------------------------------------------------------
984 * Cluster state evaluation function
985 * -------------------------------------------------------------------------- */
986 void clusterUpdateState(void) {
990 for (j
= 0; j
< REDIS_CLUSTER_SLOTS
; j
++) {
991 if (server
.cluster
.slots
[j
] == NULL
||
992 server
.cluster
.slots
[j
]->flags
& (REDIS_NODE_FAIL
))
999 if (server
.cluster
.state
== REDIS_CLUSTER_NEEDHELP
) {
1000 server
.cluster
.state
= REDIS_CLUSTER_NEEDHELP
;
1002 server
.cluster
.state
= REDIS_CLUSTER_OK
;
1005 server
.cluster
.state
= REDIS_CLUSTER_FAIL
;
1009 /* -----------------------------------------------------------------------------
1011 * -------------------------------------------------------------------------- */
1013 sds
clusterGenNodesDescription(void) {
1014 sds ci
= sdsempty();
1019 di
= dictGetIterator(server
.cluster
.nodes
);
1020 while((de
= dictNext(di
)) != NULL
) {
1021 clusterNode
*node
= dictGetEntryVal(de
);
1023 /* Node coordinates */
1024 ci
= sdscatprintf(ci
,"%.40s %s:%d ",
1030 if (node
->flags
== 0) ci
= sdscat(ci
,"noflags,");
1031 if (node
->flags
& REDIS_NODE_MYSELF
) ci
= sdscat(ci
,"myself,");
1032 if (node
->flags
& REDIS_NODE_MASTER
) ci
= sdscat(ci
,"master,");
1033 if (node
->flags
& REDIS_NODE_SLAVE
) ci
= sdscat(ci
,"slave,");
1034 if (node
->flags
& REDIS_NODE_PFAIL
) ci
= sdscat(ci
,"fail?,");
1035 if (node
->flags
& REDIS_NODE_FAIL
) ci
= sdscat(ci
,"fail,");
1036 if (node
->flags
& REDIS_NODE_HANDSHAKE
) ci
=sdscat(ci
,"handshake,");
1037 if (node
->flags
& REDIS_NODE_NOADDR
) ci
= sdscat(ci
,"noaddr,");
1038 if (ci
[sdslen(ci
)-1] == ',') ci
[sdslen(ci
)-1] = ' ';
1040 /* Slave of... or just "-" */
1042 ci
= sdscatprintf(ci
,"%.40s ",node
->slaveof
->name
);
1044 ci
= sdscatprintf(ci
,"- ");
1046 /* Latency from the POV of this node, link status */
1047 ci
= sdscatprintf(ci
,"%ld %ld %s",
1048 (long) node
->ping_sent
,
1049 (long) node
->pong_received
,
1050 node
->link
? "connected" : "disconnected");
1052 /* Slots served by this instance */
1054 for (j
= 0; j
< REDIS_CLUSTER_SLOTS
; j
++) {
1057 if ((bit
= clusterNodeGetSlotBit(node
,j
)) != 0) {
1058 if (start
== -1) start
= j
;
1060 if (start
!= -1 && (!bit
|| j
== REDIS_CLUSTER_SLOTS
-1)) {
1061 if (j
== REDIS_CLUSTER_SLOTS
-1) j
++;
1064 ci
= sdscatprintf(ci
," %d",start
);
1066 ci
= sdscatprintf(ci
," %d-%d",start
,j
-1);
1071 ci
= sdscatlen(ci
,"\n",1);
1073 dictReleaseIterator(di
);
1077 void clusterCommand(redisClient
*c
) {
1078 if (server
.cluster_enabled
== 0) {
1079 addReplyError(c
,"This instance has cluster support disabled");
1083 if (!strcasecmp(c
->argv
[1]->ptr
,"meet") && c
->argc
== 4) {
1085 struct sockaddr_in sa
;
1088 /* Perform sanity checks on IP/port */
1089 if (inet_aton(c
->argv
[2]->ptr
,&sa
.sin_addr
) == 0) {
1090 addReplyError(c
,"Invalid IP address in MEET");
1093 if (getLongFromObjectOrReply(c
, c
->argv
[3], &port
, NULL
) != REDIS_OK
||
1094 port
< 0 || port
> (65535-REDIS_CLUSTER_PORT_INCR
))
1096 addReplyError(c
,"Invalid TCP port specified");
1100 /* Finally add the node to the cluster with a random name, this
1101 * will get fixed in the first handshake (ping/pong). */
1102 n
= createClusterNode(NULL
,REDIS_NODE_HANDSHAKE
|REDIS_NODE_MEET
);
1103 strncpy(n
->ip
,inet_ntoa(sa
.sin_addr
),sizeof(n
->ip
));
1106 addReply(c
,shared
.ok
);
1107 } else if (!strcasecmp(c
->argv
[1]->ptr
,"nodes") && c
->argc
== 2) {
1109 sds ci
= clusterGenNodesDescription();
1111 o
= createObject(REDIS_STRING
,ci
);
1114 } else if (!strcasecmp(c
->argv
[1]->ptr
,"addslots") && c
->argc
>= 3) {
1117 unsigned char *slots
= zmalloc(REDIS_CLUSTER_SLOTS
);
1119 memset(slots
,0,REDIS_CLUSTER_SLOTS
);
1120 /* Check that all the arguments are parsable and that all the
1121 * slots are not already busy. */
1122 for (j
= 2; j
< c
->argc
; j
++) {
1123 if (getLongLongFromObject(c
->argv
[j
],&slot
) != REDIS_OK
||
1124 slot
< 0 || slot
> REDIS_CLUSTER_SLOTS
)
1126 addReplyError(c
,"Invalid or out of range slot index");
1130 if (server
.cluster
.slots
[slot
]) {
1131 addReplyErrorFormat(c
,"Slot %lld is already busy", slot
);
1135 if (slots
[slot
]++ == 1) {
1136 addReplyErrorFormat(c
,"Slot %d specified multiple times",
1142 for (j
= 0; j
< REDIS_CLUSTER_SLOTS
; j
++) {
1144 int retval
= clusterAddSlot(server
.cluster
.myself
,j
);
1146 redisAssert(retval
== REDIS_OK
);
1150 clusterUpdateState();
1151 clusterSaveConfigOrDie();
1152 addReply(c
,shared
.ok
);
1153 } else if (!strcasecmp(c
->argv
[1]->ptr
,"info") && c
->argc
== 2) {
1154 char *statestr
[] = {"ok","fail","needhelp"};
1155 int slots_assigned
= 0, slots_ok
= 0, slots_pfail
= 0, slots_fail
= 0;
1158 for (j
= 0; j
< REDIS_CLUSTER_SLOTS
; j
++) {
1159 clusterNode
*n
= server
.cluster
.slots
[j
];
1161 if (n
== NULL
) continue;
1163 if (n
->flags
& REDIS_NODE_FAIL
) {
1165 } else if (n
->flags
& REDIS_NODE_PFAIL
) {
1172 sds info
= sdscatprintf(sdsempty(),
1173 "cluster_state:%s\r\n"
1174 "cluster_slots_assigned:%d\r\n"
1175 "cluster_slots_ok:%d\r\n"
1176 "cluster_slots_pfail:%d\r\n"
1177 "cluster_slots_fail:%d\r\n"
1178 , statestr
[server
.cluster
.state
],
1184 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
1185 (unsigned long)sdslen(info
)));
1186 addReplySds(c
,info
);
1187 addReply(c
,shared
.crlf
);
1189 addReplyError(c
,"Wrong CLUSTER subcommand or number of arguments");
1193 /* -----------------------------------------------------------------------------
1194 * RESTORE and MIGRATE commands
1195 * -------------------------------------------------------------------------- */
1197 /* RESTORE key ttl serialized-value */
1198 void restoreCommand(redisClient
*c
) {
1202 unsigned char *data
;
1205 /* Make sure this key does not already exist here... */
1206 if (dbExists(c
->db
,c
->argv
[1])) {
1207 addReplyError(c
,"Target key name is busy.");
1211 /* Check if the TTL value makes sense */
1212 if (getLongFromObjectOrReply(c
,c
->argv
[2],&ttl
,NULL
) != REDIS_OK
) {
1214 } else if (ttl
< 0) {
1215 addReplyError(c
,"Invalid TTL value, must be >= 0");
1219 /* rdbLoadObject() only works against file descriptors so we need to
1220 * dump the serialized object into a file and reload. */
1221 snprintf(buf
,sizeof(buf
),"redis-restore-%d.tmp",getpid());
1222 fp
= fopen(buf
,"w+");
1224 redisLog(REDIS_WARNING
,"Can't open tmp file for RESTORE: %s",
1226 addReplyErrorFormat(c
,"RESTORE failed, tmp file creation error: %s",
1232 /* Write the actual data and rewind the file */
1233 data
= (unsigned char*) c
->argv
[3]->ptr
;
1234 if (fwrite(data
+1,sdslen((sds
)data
)-1,1,fp
) != 1) {
1235 redisLog(REDIS_WARNING
,"Can't write against tmp file for RESTORE: %s",
1237 addReplyError(c
,"RESTORE failed, tmp file I/O error.");
1243 /* Finally create the object from the serialized dump and
1244 * store it at the specified key. */
1245 if ((data
[0] > 4 && data
[0] < 9) ||
1247 (o
= rdbLoadObject(data
[0],fp
)) == NULL
)
1249 addReplyError(c
,"Bad data format.");
1255 /* Create the key and set the TTL if any */
1256 dbAdd(c
->db
,c
->argv
[1],o
);
1257 if (ttl
) setExpire(c
->db
,c
->argv
[1],time(NULL
)+ttl
);
1258 addReply(c
,shared
.ok
);
1261 /* MIGRATE host port key dbid timeout */
1262 void migrateCommand(redisClient
*c
) {
1274 if (getLongFromObjectOrReply(c
,c
->argv
[5],&timeout
,NULL
) != REDIS_OK
)
1276 if (getLongFromObjectOrReply(c
,c
->argv
[4],&dbid
,NULL
) != REDIS_OK
)
1278 if (timeout
<= 0) timeout
= 1;
1280 /* Check if the key is here. If not we reply with success as there is
1281 * nothing to migrate (for instance the key expired in the meantime), but
1282 * we include such information in the reply string. */
1283 if ((o
= lookupKeyRead(c
->db
,c
->argv
[3])) == NULL
) {
1284 addReplySds(c
,sdsnew("+NOKEY"));
1289 fd
= anetTcpNonBlockConnect(server
.neterr
,c
->argv
[1]->ptr
,
1290 atoi(c
->argv
[2]->ptr
));
1292 addReplyErrorFormat(c
,"Can't connect to target node: %s",
1296 if ((aeWait(fd
,AE_WRITABLE
,timeout
*1000) & AE_WRITABLE
) == 0) {
1297 addReplyError(c
,"Timeout connecting to the client");
1301 /* Create temp file */
1302 snprintf(buf
,sizeof(buf
),"redis-migrate-%d.tmp",getpid());
1303 fp
= fopen(buf
,"w+");
1305 redisLog(REDIS_WARNING
,"Can't open tmp file for MIGRATE: %s",
1307 addReplyErrorFormat(c
,"MIGRATE failed, tmp file creation error: %s.",
1313 /* Build the SELECT + RESTORE query writing it in our temp file. */
1314 if (fwriteBulkCount(fp
,'*',2) == 0) goto file_wr_err
;
1315 if (fwriteBulkString(fp
,"SELECT",6) == 0) goto file_wr_err
;
1316 if (fwriteBulkLongLong(fp
,dbid
) == 0) goto file_wr_err
;
1318 ttl
= getExpire(c
->db
,c
->argv
[3]);
1320 if (fwriteBulkCount(fp
,'*',4) == 0) goto file_wr_err
;
1321 if (fwriteBulkString(fp
,"RESTORE",7) == 0) goto file_wr_err
;
1322 if (fwriteBulkObject(fp
,c
->argv
[3]) == 0) goto file_wr_err
;
1323 if (fwriteBulkLongLong(fp
, (ttl
== -1) ? 0 : ttl
) == 0) goto file_wr_err
;
1325 /* Finally the last argument that is the serailized object payload
1326 * in the form: <type><rdb-serailized-object>. */
1327 payload_len
= rdbSavedObjectLen(o
);
1328 if (fwriteBulkCount(fp
,'$',payload_len
+1) == 0) goto file_wr_err
;
1329 if (fwrite(&type
,1,1,fp
) == 0) goto file_wr_err
;
1330 if (rdbSaveObject(fp
,o
) == -1) goto file_wr_err
;
1331 if (fwrite("\r\n",2,1,fp
) == 0) goto file_wr_err
;
1333 /* Tranfer the query to the other node */
1339 while ((nread
= fread(buf
,1,sizeof(buf
),fp
)) != 0) {
1342 nwritten
= syncWrite(fd
,buf
,nread
,timeout
);
1343 if (nwritten
!= (signed)nread
) goto socket_wr_err
;
1345 if (ferror(fp
)) goto file_rd_err
;
1348 /* Read back the reply */
1353 /* Read the two replies */
1354 if (syncReadLine(fd
, buf1
, sizeof(buf1
), timeout
) <= 0)
1356 if (syncReadLine(fd
, buf2
, sizeof(buf2
), timeout
) <= 0)
1358 if (buf1
[0] == '-' || buf2
[0] == '-') {
1359 addReplyErrorFormat(c
,"Target instance replied with error: %s",
1360 (buf1
[0] == '-') ? buf1
+1 : buf2
+1);
1362 dbDelete(c
->db
,c
->argv
[3]);
1363 addReply(c
,shared
.ok
);
1371 redisLog(REDIS_WARNING
,"Can't write on tmp file for MIGRATE: %s",
1373 addReplyErrorFormat(c
,"MIGRATE failed, tmp file write error: %s.",
1380 redisLog(REDIS_WARNING
,"Can't read from tmp file for MIGRATE: %s",
1382 addReplyErrorFormat(c
,"MIGRATE failed, tmp file read error: %s.",
1389 redisLog(REDIS_NOTICE
,"Can't write to target node for MIGRATE: %s",
1391 addReplyErrorFormat(c
,"MIGRATE failed, writing to target node: %s.",
1398 redisLog(REDIS_NOTICE
,"Can't read from target node for MIGRATE: %s",
1400 addReplyErrorFormat(c
,"MIGRATE failed, reading from target node: %s.",
1408 * DUMP is actually not used by Redis Cluster but it is the obvious
1409 * complement of RESTORE and can be useful for different applications. */
1410 void dumpCommand(redisClient
*c
) {
1418 /* Check if the key is here. */
1419 if ((o
= lookupKeyRead(c
->db
,c
->argv
[1])) == NULL
) {
1420 addReply(c
,shared
.nullbulk
);
1424 /* Create temp file */
1425 snprintf(buf
,sizeof(buf
),"redis-dump-%d.tmp",getpid());
1426 fp
= fopen(buf
,"w+");
1428 redisLog(REDIS_WARNING
,"Can't open tmp file for MIGRATE: %s",
1430 addReplyErrorFormat(c
,"DUMP failed, tmp file creation error: %s.",
1436 /* Dump the serailized object and read it back in memory.
1437 * We prefix it with a one byte containing the type ID.
1438 * This is the serialization format understood by RESTORE. */
1439 if (rdbSaveObject(fp
,o
) == -1) goto file_wr_err
;
1440 payload_len
= ftello(fp
);
1441 if (fseeko(fp
,0,SEEK_SET
) == -1) goto file_rd_err
;
1442 dump
= sdsnewlen(NULL
,payload_len
+1);
1443 if (payload_len
&& fread(dump
+1,payload_len
,1,fp
) != 1) goto file_rd_err
;
1446 if (type
== REDIS_LIST
&& o
->encoding
== REDIS_ENCODING_ZIPLIST
)
1447 type
= REDIS_LIST_ZIPLIST
;
1448 else if (type
== REDIS_HASH
&& o
->encoding
== REDIS_ENCODING_ZIPMAP
)
1449 type
= REDIS_HASH_ZIPMAP
;
1450 else if (type
== REDIS_SET
&& o
->encoding
== REDIS_ENCODING_INTSET
)
1451 type
= REDIS_SET_INTSET
;
1456 /* Transfer to the client */
1457 dumpobj
= createObject(REDIS_STRING
,dump
);
1458 addReplyBulk(c
,dumpobj
);
1459 decrRefCount(dumpobj
);
1463 redisLog(REDIS_WARNING
,"Can't write on tmp file for DUMP: %s",
1465 addReplyErrorFormat(c
,"DUMP failed, tmp file write error: %s.",
1472 redisLog(REDIS_WARNING
,"Can't read from tmp file for DUMP: %s",
1474 addReplyErrorFormat(c
,"DUMP failed, tmp file read error: %s.",
1481 /* -----------------------------------------------------------------------------
1482 * Cluster functions related to serving / redirecting clients
1483 * -------------------------------------------------------------------------- */
1485 /* Return the pointer to the cluster node that is able to serve the query
1486 * as all the keys belong to hash slots for which the node is in charge.
1488 * If keys in query spawn multiple nodes NULL is returned. */
1489 clusterNode
*getNodeByQuery(redisClient
*c
, struct redisCommand
*cmd
, robj
**argv
, int argc
, int *hashslot
) {
1490 clusterNode
*n
= NULL
;
1491 multiState
*ms
, _ms
;
1495 /* We handle all the cases as if they were EXEC commands, so we have
1496 * a common code path for everything */
1497 if (cmd
->proc
== execCommand
) {
1498 /* If REDIS_MULTI flag is not set EXEC is just going to return an
1500 if (!(c
->flags
& REDIS_MULTI
)) return server
.cluster
.myself
;
1503 /* Create a fake Multi State structure, with just one command */
1512 for (i
= 0; i
< ms
->count
; i
++) {
1513 struct redisCommand
*mcmd
;
1515 int margc
, *keyindex
, numkeys
, j
;
1517 mcmd
= ms
->commands
[i
].cmd
;
1518 margc
= ms
->commands
[i
].argc
;
1519 margv
= ms
->commands
[i
].argv
;
1521 keyindex
= getKeysFromCommand(mcmd
,margv
,margc
,&numkeys
,
1522 REDIS_GETKEYS_PRELOAD
);
1523 for (j
= 0; j
< numkeys
; j
++) {
1524 int slot
= keyHashSlot((char*)margv
[keyindex
[j
]]->ptr
,
1525 sdslen(margv
[keyindex
[j
]]->ptr
));
1526 struct clusterNode
*slotnode
;
1528 slotnode
= server
.cluster
.slots
[slot
];
1529 if (hashslot
) *hashslot
= slot
;
1530 /* Node not assigned? (Should never happen actually
1531 * if we reached this function).
1532 * Different node than the previous one?
1533 * Return NULL, the cluster can't serve multi-node requests */
1534 if (slotnode
== NULL
|| (n
&& slotnode
!= n
)) {
1535 getKeysFreeResult(keyindex
);
1541 getKeysFreeResult(keyindex
);
1543 return (n
== NULL
) ? server
.cluster
.myself
: n
;