27630561c4fd52f222d1576f04a69a884b51800f
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
);
17 /* -----------------------------------------------------------------------------
19 * -------------------------------------------------------------------------- */
21 void clusterGetRandomName(char *p
) {
22 FILE *fp
= fopen("/dev/urandom","r");
23 char *charset
= "0123456789abcdef";
27 redisLog(REDIS_WARNING
,
28 "Unrecovarable error: can't open /dev/urandom:%s" ,strerror(errno
));
31 fread(p
,REDIS_CLUSTER_NAMELEN
,1,fp
);
32 for (j
= 0; j
< REDIS_CLUSTER_NAMELEN
; j
++)
33 p
[j
] = charset
[p
[j
] & 0x0F];
37 int clusterLoadConfig(char *filename
) {
38 FILE *fp
= fopen(filename
,"r");
42 if (fp
== NULL
) return REDIS_ERR
;
44 /* Parse the file. Note that single liens of the cluster config file can
45 * be really long as they include all the hash slots of the node.
46 * This means in the worst possible case REDIS_CLUSTER_SLOTS/2 integers.
47 * To simplify we allocate 1024+REDIS_CLUSTER_SLOTS*16 bytes per line. */
48 maxline
= 1024+REDIS_CLUSTER_SLOTS
*16;
49 line
= zmalloc(maxline
);
50 while(fgets(line
,maxline
,fp
) != NULL
) {
52 sds
*argv
= sdssplitargs(line
,&argc
);
53 clusterNode
*n
, *master
;
56 /* Create this node if it does not exist */
57 n
= clusterLookupNode(argv
[0]);
59 n
= createClusterNode(argv
[0],0);
62 /* Address and port */
63 if ((p
= strchr(argv
[1],':')) == NULL
) goto fmterr
;
65 memcpy(n
->ip
,argv
[1],strlen(argv
[1])+1);
73 if (!strcasecmp(s
,"myself")) {
74 redisAssert(server
.cluster
.myself
== NULL
);
75 server
.cluster
.myself
= n
;
76 n
->flags
|= REDIS_NODE_MYSELF
;
77 } else if (!strcasecmp(s
,"master")) {
78 n
->flags
|= REDIS_NODE_MASTER
;
79 } else if (!strcasecmp(s
,"slave")) {
80 n
->flags
|= REDIS_NODE_SLAVE
;
81 } else if (!strcasecmp(s
,"fail?")) {
82 n
->flags
|= REDIS_NODE_PFAIL
;
83 } else if (!strcasecmp(s
,"fail")) {
84 n
->flags
|= REDIS_NODE_FAIL
;
85 } else if (!strcasecmp(s
,"handshake")) {
86 n
->flags
|= REDIS_NODE_HANDSHAKE
;
87 } else if (!strcasecmp(s
,"noaddr")) {
88 n
->flags
|= REDIS_NODE_NOADDR
;
89 } else if (!strcasecmp(s
,"noflags")) {
92 redisPanic("Unknown flag in redis cluster config file");
97 /* Get master if any. Set the master and populate master's
99 if (argv
[3][0] != '-') {
100 master
= clusterLookupNode(argv
[3]);
102 master
= createClusterNode(argv
[3],0);
103 clusterAddNode(master
);
106 clusterNodeAddSlave(master
,n
);
109 /* Populate hash slots served by this instance. */
110 for (j
= 7; j
< argc
; j
++) {
113 if ((p
= strchr(argv
[j
],'-')) != NULL
) {
115 start
= atoi(argv
[j
]);
118 start
= stop
= atoi(argv
[j
]);
120 while(start
<= stop
) clusterAddSlot(n
, start
++);
123 sdssplitargs_free(argv
,argc
);
128 /* Config sanity check */
129 redisAssert(server
.cluster
.myself
!= NULL
);
130 redisLog(REDIS_NOTICE
,"Node configuration loaded, I'm %.40s",
131 server
.cluster
.myself
->name
);
135 redisLog(REDIS_WARNING
,"Unrecovarable error: corrupted cluster config file.");
140 /* Cluster node configuration is exactly the same as CLUSTER NODES output.
142 * This function writes the node config and returns 0, on error -1
144 int clusterSaveConfig(void) {
145 sds ci
= clusterGenNodesDescription();
148 if ((fd
= open(server
.cluster
.configfile
,O_WRONLY
|O_CREAT
|O_TRUNC
,0644))
150 if (write(fd
,ci
,sdslen(ci
)) != (ssize_t
)sdslen(ci
)) goto err
;
160 void clusterSaveConfigOrDie(void) {
161 if (clusterSaveConfig() == -1) {
162 redisLog(REDIS_WARNING
,"Fatal: can't update cluster config file.");
167 void clusterInit(void) {
170 server
.cluster
.myself
= NULL
;
171 server
.cluster
.state
= REDIS_CLUSTER_FAIL
;
172 server
.cluster
.nodes
= dictCreate(&clusterNodesDictType
,NULL
);
173 server
.cluster
.node_timeout
= 15;
174 memset(server
.cluster
.migrating_slots_to
,0,
175 sizeof(server
.cluster
.migrating_slots_to
));
176 memset(server
.cluster
.importing_slots_from
,0,
177 sizeof(server
.cluster
.importing_slots_from
));
178 memset(server
.cluster
.slots
,0,
179 sizeof(server
.cluster
.slots
));
180 if (clusterLoadConfig(server
.cluster
.configfile
) == REDIS_ERR
) {
181 /* No configuration found. We will just use the random name provided
182 * by the createClusterNode() function. */
183 server
.cluster
.myself
= createClusterNode(NULL
,REDIS_NODE_MYSELF
);
184 redisLog(REDIS_NOTICE
,"No cluster configuration found, I'm %.40s",
185 server
.cluster
.myself
->name
);
186 clusterAddNode(server
.cluster
.myself
);
189 if (saveconf
) clusterSaveConfigOrDie();
190 /* We need a listening TCP port for our cluster messaging needs */
191 server
.cfd
= anetTcpServer(server
.neterr
,
192 server
.port
+REDIS_CLUSTER_PORT_INCR
, server
.bindaddr
);
193 if (server
.cfd
== -1) {
194 redisLog(REDIS_WARNING
, "Opening cluster TCP port: %s", server
.neterr
);
197 if (aeCreateFileEvent(server
.el
, server
.cfd
, AE_READABLE
,
198 clusterAcceptHandler
, NULL
) == AE_ERR
) oom("creating file event");
201 /* -----------------------------------------------------------------------------
202 * CLUSTER communication link
203 * -------------------------------------------------------------------------- */
205 clusterLink
*createClusterLink(clusterNode
*node
) {
206 clusterLink
*link
= zmalloc(sizeof(*link
));
207 link
->sndbuf
= sdsempty();
208 link
->rcvbuf
= sdsempty();
214 /* Free a cluster link, but does not free the associated node of course.
215 * Just this function will make sure that the original node associated
216 * with this link will have the 'link' field set to NULL. */
217 void freeClusterLink(clusterLink
*link
) {
218 if (link
->fd
!= -1) {
219 aeDeleteFileEvent(server
.el
, link
->fd
, AE_WRITABLE
);
220 aeDeleteFileEvent(server
.el
, link
->fd
, AE_READABLE
);
222 sdsfree(link
->sndbuf
);
223 sdsfree(link
->rcvbuf
);
225 link
->node
->link
= NULL
;
230 void clusterAcceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
236 REDIS_NOTUSED(privdata
);
238 cfd
= anetTcpAccept(server
.neterr
, fd
, cip
, &cport
);
240 redisLog(REDIS_VERBOSE
,"Accepting cluster node: %s", server
.neterr
);
243 redisLog(REDIS_VERBOSE
,"Accepted cluster node %s:%d", cip
, cport
);
244 /* We need to create a temporary node in order to read the incoming
245 * packet in a valid contest. This node will be released once we
246 * read the packet and reply. */
247 link
= createClusterLink(NULL
);
249 aeCreateFileEvent(server
.el
,cfd
,AE_READABLE
,clusterReadHandler
,link
);
252 /* -----------------------------------------------------------------------------
254 * -------------------------------------------------------------------------- */
256 /* We have 4096 hash slots. The hash slot of a given key is obtained
257 * as the least significant 12 bits of the crc16 of the key. */
258 unsigned int keyHashSlot(char *key
, int keylen
) {
259 return crc16(key
,keylen
) & 0x0FFF;
262 /* -----------------------------------------------------------------------------
264 * -------------------------------------------------------------------------- */
266 /* Create a new cluster node, with the specified flags.
267 * If "nodename" is NULL this is considered a first handshake and a random
268 * node name is assigned to this node (it will be fixed later when we'll
269 * receive the first pong).
271 * The node is created and returned to the user, but it is not automatically
272 * added to the nodes hash table. */
273 clusterNode
*createClusterNode(char *nodename
, int flags
) {
274 clusterNode
*node
= zmalloc(sizeof(*node
));
277 memcpy(node
->name
, nodename
, REDIS_CLUSTER_NAMELEN
);
279 clusterGetRandomName(node
->name
);
281 memset(node
->slots
,0,sizeof(node
->slots
));
284 node
->slaveof
= NULL
;
285 node
->ping_sent
= node
->pong_received
= 0;
286 node
->configdigest
= NULL
;
287 node
->configdigest_ts
= 0;
292 int clusterNodeRemoveSlave(clusterNode
*master
, clusterNode
*slave
) {
295 for (j
= 0; j
< master
->numslaves
; j
++) {
296 if (master
->slaves
[j
] == slave
) {
297 memmove(master
->slaves
+j
,master
->slaves
+(j
+1),
298 (master
->numslaves
-1)-j
);
306 int clusterNodeAddSlave(clusterNode
*master
, clusterNode
*slave
) {
309 /* If it's already a slave, don't add it again. */
310 for (j
= 0; j
< master
->numslaves
; j
++)
311 if (master
->slaves
[j
] == slave
) return REDIS_ERR
;
312 master
->slaves
= zrealloc(master
->slaves
,
313 sizeof(clusterNode
*)*(master
->numslaves
+1));
314 master
->slaves
[master
->numslaves
] = slave
;
319 void clusterNodeResetSlaves(clusterNode
*n
) {
324 void freeClusterNode(clusterNode
*n
) {
327 nodename
= sdsnewlen(n
->name
, REDIS_CLUSTER_NAMELEN
);
328 redisAssert(dictDelete(server
.cluster
.nodes
,nodename
) == DICT_OK
);
330 if (n
->slaveof
) clusterNodeRemoveSlave(n
->slaveof
, n
);
331 if (n
->link
) freeClusterLink(n
->link
);
335 /* Add a node to the nodes hash table */
336 int clusterAddNode(clusterNode
*node
) {
339 retval
= dictAdd(server
.cluster
.nodes
,
340 sdsnewlen(node
->name
,REDIS_CLUSTER_NAMELEN
), node
);
341 return (retval
== DICT_OK
) ? REDIS_OK
: REDIS_ERR
;
344 /* Node lookup by name */
345 clusterNode
*clusterLookupNode(char *name
) {
346 sds s
= sdsnewlen(name
, REDIS_CLUSTER_NAMELEN
);
347 struct dictEntry
*de
;
349 de
= dictFind(server
.cluster
.nodes
,s
);
351 if (de
== NULL
) return NULL
;
352 return dictGetEntryVal(de
);
355 /* This is only used after the handshake. When we connect a given IP/PORT
356 * as a result of CLUSTER MEET we don't have the node name yet, so we
357 * pick a random one, and will fix it when we receive the PONG request using
359 void clusterRenameNode(clusterNode
*node
, char *newname
) {
361 sds s
= sdsnewlen(node
->name
, REDIS_CLUSTER_NAMELEN
);
363 redisLog(REDIS_DEBUG
,"Renaming node %.40s into %.40s",
364 node
->name
, newname
);
365 retval
= dictDelete(server
.cluster
.nodes
, s
);
367 redisAssert(retval
== DICT_OK
);
368 memcpy(node
->name
, newname
, REDIS_CLUSTER_NAMELEN
);
369 clusterAddNode(node
);
372 /* -----------------------------------------------------------------------------
373 * CLUSTER messages exchange - PING/PONG and gossip
374 * -------------------------------------------------------------------------- */
376 /* Process the gossip section of PING or PONG packets.
377 * Note that this function assumes that the packet is already sanity-checked
378 * by the caller, not in the content of the gossip section, but in the
380 void clusterProcessGossipSection(clusterMsg
*hdr
, clusterLink
*link
) {
381 uint16_t count
= ntohs(hdr
->count
);
382 clusterMsgDataGossip
*g
= (clusterMsgDataGossip
*) hdr
->data
.ping
.gossip
;
383 clusterNode
*sender
= link
->node
? link
->node
: clusterLookupNode(hdr
->sender
);
387 uint16_t flags
= ntohs(g
->flags
);
390 if (flags
== 0) ci
= sdscat(ci
,"noflags,");
391 if (flags
& REDIS_NODE_MYSELF
) ci
= sdscat(ci
,"myself,");
392 if (flags
& REDIS_NODE_MASTER
) ci
= sdscat(ci
,"master,");
393 if (flags
& REDIS_NODE_SLAVE
) ci
= sdscat(ci
,"slave,");
394 if (flags
& REDIS_NODE_PFAIL
) ci
= sdscat(ci
,"fail?,");
395 if (flags
& REDIS_NODE_FAIL
) ci
= sdscat(ci
,"fail,");
396 if (flags
& REDIS_NODE_HANDSHAKE
) ci
= sdscat(ci
,"handshake,");
397 if (flags
& REDIS_NODE_NOADDR
) ci
= sdscat(ci
,"noaddr,");
398 if (ci
[sdslen(ci
)-1] == ',') ci
[sdslen(ci
)-1] = ' ';
400 redisLog(REDIS_DEBUG
,"GOSSIP %.40s %s:%d %s",
407 /* Update our state accordingly to the gossip sections */
408 node
= clusterLookupNode(g
->nodename
);
410 /* We already know this node. Let's start updating the last
411 * time PONG figure if it is newer than our figure.
412 * Note that it's not a problem if we have a PING already
413 * in progress against this node. */
414 if (node
->pong_received
< ntohl(g
->pong_received
)) {
415 redisLog(REDIS_DEBUG
,"Node pong_received updated by gossip");
416 node
->pong_received
= ntohl(g
->pong_received
);
418 /* Mark this node as FAILED if we think it is possibly failing
419 * and another node also thinks it's failing. */
420 if (node
->flags
& REDIS_NODE_PFAIL
&&
421 (flags
& (REDIS_NODE_FAIL
|REDIS_NODE_PFAIL
)))
423 redisLog(REDIS_NOTICE
,"Received a PFAIL acknowledge from node %.40s, marking node %.40s as FAIL!", hdr
->sender
, node
->name
);
424 node
->flags
&= ~REDIS_NODE_PFAIL
;
425 node
->flags
|= REDIS_NODE_FAIL
;
426 /* Broadcast the failing node name to everybody */
427 clusterSendFail(node
->name
);
428 clusterUpdateState();
429 clusterSaveConfigOrDie();
432 /* If it's not in NOADDR state and we don't have it, we
433 * start an handshake process against this IP/PORT pairs.
435 * Note that we require that the sender of this gossip message
436 * is a well known node in our cluster, otherwise we risk
437 * joining another cluster. */
438 if (sender
&& !(flags
& REDIS_NODE_NOADDR
)) {
439 clusterNode
*newnode
;
441 redisLog(REDIS_DEBUG
,"Adding the new node");
442 newnode
= createClusterNode(NULL
,REDIS_NODE_HANDSHAKE
);
443 memcpy(newnode
->ip
,g
->ip
,sizeof(g
->ip
));
444 newnode
->port
= ntohs(g
->port
);
445 clusterAddNode(newnode
);
454 /* IP -> string conversion. 'buf' is supposed to at least be 16 bytes. */
455 void nodeIp2String(char *buf
, clusterLink
*link
) {
456 struct sockaddr_in sa
;
457 socklen_t salen
= sizeof(sa
);
459 if (getpeername(link
->fd
, (struct sockaddr
*) &sa
, &salen
) == -1)
460 redisPanic("getpeername() failed.");
461 strncpy(buf
,inet_ntoa(sa
.sin_addr
),sizeof(link
->node
->ip
));
465 /* Update the node address to the IP address that can be extracted
466 * from link->fd, and at the specified port. */
467 void nodeUpdateAddress(clusterNode
*node
, clusterLink
*link
, int port
) {
470 /* When this function is called, there is a packet to process starting
471 * at node->rcvbuf. Releasing the buffer is up to the caller, so this
472 * function should just handle the higher level stuff of processing the
473 * packet, modifying the cluster state if needed.
475 * The function returns 1 if the link is still valid after the packet
476 * was processed, otherwise 0 if the link was freed since the packet
477 * processing lead to some inconsistency error (for instance a PONG
478 * received from the wrong sender ID). */
479 int clusterProcessPacket(clusterLink
*link
) {
480 clusterMsg
*hdr
= (clusterMsg
*) link
->rcvbuf
;
481 uint32_t totlen
= ntohl(hdr
->totlen
);
482 uint16_t type
= ntohs(hdr
->type
);
485 redisLog(REDIS_DEBUG
,"--- packet to process %lu bytes (%lu) ---",
486 (unsigned long) totlen
, sdslen(link
->rcvbuf
));
487 if (totlen
< 8) return 1;
488 if (totlen
> sdslen(link
->rcvbuf
)) return 1;
489 if (type
== CLUSTERMSG_TYPE_PING
|| type
== CLUSTERMSG_TYPE_PONG
||
490 type
== CLUSTERMSG_TYPE_MEET
)
492 uint16_t count
= ntohs(hdr
->count
);
493 uint32_t explen
; /* expected length of this packet */
495 explen
= sizeof(clusterMsg
)-sizeof(union clusterMsgData
);
496 explen
+= (sizeof(clusterMsgDataGossip
)*count
);
497 if (totlen
!= explen
) return 1;
499 if (type
== CLUSTERMSG_TYPE_FAIL
) {
500 uint32_t explen
= sizeof(clusterMsg
)-sizeof(union clusterMsgData
);
502 explen
+= sizeof(clusterMsgDataFail
);
503 if (totlen
!= explen
) return 1;
506 sender
= clusterLookupNode(hdr
->sender
);
507 if (type
== CLUSTERMSG_TYPE_PING
|| type
== CLUSTERMSG_TYPE_MEET
) {
508 int update_config
= 0;
509 redisLog(REDIS_DEBUG
,"Ping packet received: %p", link
->node
);
511 /* Add this node if it is new for us and the msg type is MEET.
512 * In this stage we don't try to add the node with the right
513 * flags, slaveof pointer, and so forth, as this details will be
514 * resolved when we'll receive PONGs from the server. */
515 if (!sender
&& type
== CLUSTERMSG_TYPE_MEET
) {
518 node
= createClusterNode(NULL
,REDIS_NODE_HANDSHAKE
);
519 nodeIp2String(node
->ip
,link
);
520 node
->port
= ntohs(hdr
->port
);
521 clusterAddNode(node
);
525 /* Get info from the gossip section */
526 clusterProcessGossipSection(hdr
,link
);
528 /* Anyway reply with a PONG */
529 clusterSendPing(link
,CLUSTERMSG_TYPE_PONG
);
531 /* Update config if needed */
532 if (update_config
) clusterSaveConfigOrDie();
533 } else if (type
== CLUSTERMSG_TYPE_PONG
) {
534 int update_state
= 0;
535 int update_config
= 0;
537 redisLog(REDIS_DEBUG
,"Pong packet received: %p", link
->node
);
539 if (link
->node
->flags
& REDIS_NODE_HANDSHAKE
) {
540 /* If we already have this node, try to change the
541 * IP/port of the node with the new one. */
543 redisLog(REDIS_WARNING
,
544 "Handshake error: we already know node %.40s, updating the address if needed.", sender
->name
);
545 nodeUpdateAddress(sender
,link
,ntohs(hdr
->port
));
546 freeClusterNode(link
->node
); /* will free the link too */
550 /* First thing to do is replacing the random name with the
551 * right node name if this was an handshake stage. */
552 clusterRenameNode(link
->node
, hdr
->sender
);
553 redisLog(REDIS_DEBUG
,"Handshake with node %.40s completed.",
555 link
->node
->flags
&= ~REDIS_NODE_HANDSHAKE
;
557 } else if (memcmp(link
->node
->name
,hdr
->sender
,
558 REDIS_CLUSTER_NAMELEN
) != 0)
560 /* If the reply has a non matching node ID we
561 * disconnect this node and set it as not having an associated
563 redisLog(REDIS_DEBUG
,"PONG contains mismatching sender ID");
564 link
->node
->flags
|= REDIS_NODE_NOADDR
;
565 freeClusterLink(link
);
567 /* FIXME: remove this node if we already have it.
569 * If we already have it but the IP is different, use
570 * the new one if the old node is in FAIL, PFAIL, or NOADDR
575 /* Update our info about the node */
576 link
->node
->pong_received
= time(NULL
);
578 /* Update master/slave info */
580 if (!memcmp(hdr
->slaveof
,REDIS_NODE_NULL_NAME
,
581 sizeof(hdr
->slaveof
)))
583 sender
->flags
&= ~REDIS_NODE_SLAVE
;
584 sender
->flags
|= REDIS_NODE_MASTER
;
585 sender
->slaveof
= NULL
;
587 clusterNode
*master
= clusterLookupNode(hdr
->slaveof
);
589 sender
->flags
&= ~REDIS_NODE_MASTER
;
590 sender
->flags
|= REDIS_NODE_SLAVE
;
591 if (sender
->numslaves
) clusterNodeResetSlaves(sender
);
592 if (master
) clusterNodeAddSlave(master
,sender
);
596 /* Update our info about served slots if this new node is serving
597 * slots that are not served from our point of view. */
598 if (sender
&& sender
->flags
& REDIS_NODE_MASTER
) {
602 memcmp(sender
->slots
,hdr
->myslots
,sizeof(hdr
->myslots
)) != 0;
603 memcpy(sender
->slots
,hdr
->myslots
,sizeof(hdr
->myslots
));
605 for (j
= 0; j
< REDIS_CLUSTER_SLOTS
; j
++) {
606 if (clusterNodeGetSlotBit(sender
,j
)) {
607 if (server
.cluster
.slots
[j
] == sender
) continue;
608 if (server
.cluster
.slots
[j
] == NULL
||
609 server
.cluster
.slots
[j
]->flags
& REDIS_NODE_FAIL
)
611 server
.cluster
.slots
[j
] = sender
;
612 update_state
= update_config
= 1;
619 /* Get info from the gossip section */
620 clusterProcessGossipSection(hdr
,link
);
622 /* Update the cluster state if needed */
623 if (update_state
) clusterUpdateState();
624 if (update_config
) clusterSaveConfigOrDie();
625 } else if (type
== CLUSTERMSG_TYPE_FAIL
&& sender
) {
626 clusterNode
*failing
;
628 failing
= clusterLookupNode(hdr
->data
.fail
.about
.nodename
);
629 if (failing
&& !(failing
->flags
& REDIS_NODE_FAIL
)) {
630 redisLog(REDIS_NOTICE
,
631 "FAIL message received from %.40s about %.40s",
632 hdr
->sender
, hdr
->data
.fail
.about
.nodename
);
633 failing
->flags
|= REDIS_NODE_FAIL
;
634 failing
->flags
&= ~REDIS_NODE_PFAIL
;
635 clusterUpdateState();
636 clusterSaveConfigOrDie();
639 redisLog(REDIS_NOTICE
,"Received unknown packet type: %d", type
);
644 /* This function is called when we detect the link with this node is lost.
645 We set the node as no longer connected. The Cluster Cron will detect
646 this connection and will try to get it connected again.
648 Instead if the node is a temporary node used to accept a query, we
649 completely free the node on error. */
650 void handleLinkIOError(clusterLink
*link
) {
651 freeClusterLink(link
);
654 /* Send data. This is handled using a trivial send buffer that gets
655 * consumed by write(). We don't try to optimize this for speed too much
656 * as this is a very low traffic channel. */
657 void clusterWriteHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
658 clusterLink
*link
= (clusterLink
*) privdata
;
663 nwritten
= write(fd
, link
->sndbuf
, sdslen(link
->sndbuf
));
665 redisLog(REDIS_NOTICE
,"I/O error writing to node link: %s",
667 handleLinkIOError(link
);
670 link
->sndbuf
= sdsrange(link
->sndbuf
,nwritten
,-1);
671 if (sdslen(link
->sndbuf
) == 0)
672 aeDeleteFileEvent(server
.el
, link
->fd
, AE_WRITABLE
);
675 /* Read data. Try to read the first field of the header first to check the
676 * full length of the packet. When a whole packet is in memory this function
677 * will call the function to process the packet. And so forth. */
678 void clusterReadHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
682 clusterLink
*link
= (clusterLink
*) privdata
;
688 if (sdslen(link
->rcvbuf
) >= 4) {
689 hdr
= (clusterMsg
*) link
->rcvbuf
;
690 readlen
= ntohl(hdr
->totlen
) - sdslen(link
->rcvbuf
);
692 readlen
= 4 - sdslen(link
->rcvbuf
);
695 nread
= read(fd
,buf
,readlen
);
696 if (nread
== -1 && errno
== EAGAIN
) return; /* Just no data */
700 redisLog(REDIS_NOTICE
,"I/O error reading from node link: %s",
701 (nread
== 0) ? "connection closed" : strerror(errno
));
702 handleLinkIOError(link
);
705 /* Read data and recast the pointer to the new buffer. */
706 link
->rcvbuf
= sdscatlen(link
->rcvbuf
,buf
,nread
);
707 hdr
= (clusterMsg
*) link
->rcvbuf
;
710 /* Total length obtained? read the payload now instead of burning
711 * cycles waiting for a new event to fire. */
712 if (sdslen(link
->rcvbuf
) == 4) goto again
;
714 /* Whole packet in memory? We can process it. */
715 if (sdslen(link
->rcvbuf
) == ntohl(hdr
->totlen
)) {
716 if (clusterProcessPacket(link
)) {
717 sdsfree(link
->rcvbuf
);
718 link
->rcvbuf
= sdsempty();
723 /* Put stuff into the send buffer. */
724 void clusterSendMessage(clusterLink
*link
, unsigned char *msg
, size_t msglen
) {
725 if (sdslen(link
->sndbuf
) == 0 && msglen
!= 0)
726 aeCreateFileEvent(server
.el
,link
->fd
,AE_WRITABLE
,
727 clusterWriteHandler
,link
);
729 link
->sndbuf
= sdscatlen(link
->sndbuf
, msg
, msglen
);
732 /* Build the message header */
733 void clusterBuildMessageHdr(clusterMsg
*hdr
, int type
) {
736 memset(hdr
,0,sizeof(*hdr
));
737 hdr
->type
= htons(type
);
738 memcpy(hdr
->sender
,server
.cluster
.myself
->name
,REDIS_CLUSTER_NAMELEN
);
739 memcpy(hdr
->myslots
,server
.cluster
.myself
->slots
,
740 sizeof(hdr
->myslots
));
741 memset(hdr
->slaveof
,0,REDIS_CLUSTER_NAMELEN
);
742 if (server
.cluster
.myself
->slaveof
!= NULL
) {
743 memcpy(hdr
->slaveof
,server
.cluster
.myself
->slaveof
->name
,
744 REDIS_CLUSTER_NAMELEN
);
746 hdr
->port
= htons(server
.port
);
747 hdr
->state
= server
.cluster
.state
;
748 memset(hdr
->configdigest
,0,32); /* FIXME: set config digest */
750 if (type
== CLUSTERMSG_TYPE_FAIL
) {
751 totlen
= sizeof(clusterMsg
)-sizeof(union clusterMsgData
);
752 totlen
+= sizeof(clusterMsgDataFail
);
754 hdr
->totlen
= htonl(totlen
);
755 /* For PING, PONG, and MEET, fixing the totlen field is up to the caller */
758 /* Send a PING or PONG packet to the specified node, making sure to add enough
759 * gossip informations. */
760 void clusterSendPing(clusterLink
*link
, int type
) {
761 unsigned char buf
[1024];
762 clusterMsg
*hdr
= (clusterMsg
*) buf
;
763 int gossipcount
= 0, totlen
;
764 /* freshnodes is the number of nodes we can still use to populate the
765 * gossip section of the ping packet. Basically we start with the nodes
766 * we have in memory minus two (ourself and the node we are sending the
767 * message to). Every time we add a node we decrement the counter, so when
768 * it will drop to <= zero we know there is no more gossip info we can
770 int freshnodes
= dictSize(server
.cluster
.nodes
)-2;
772 if (link
->node
&& type
== CLUSTERMSG_TYPE_PING
)
773 link
->node
->ping_sent
= time(NULL
);
774 clusterBuildMessageHdr(hdr
,type
);
776 /* Populate the gossip fields */
777 while(freshnodes
> 0 && gossipcount
< 3) {
778 struct dictEntry
*de
= dictGetRandomKey(server
.cluster
.nodes
);
779 clusterNode
*this = dictGetEntryVal(de
);
780 clusterMsgDataGossip
*gossip
;
783 /* Not interesting to gossip about ourself.
784 * Nor to send gossip info about HANDSHAKE state nodes (zero info). */
785 if (this == server
.cluster
.myself
||
786 this->flags
& REDIS_NODE_HANDSHAKE
) {
787 freshnodes
--; /* otherwise we may loop forever. */
791 /* Check if we already added this node */
792 for (j
= 0; j
< gossipcount
; j
++) {
793 if (memcmp(hdr
->data
.ping
.gossip
[j
].nodename
,this->name
,
794 REDIS_CLUSTER_NAMELEN
) == 0) break;
796 if (j
!= gossipcount
) continue;
800 gossip
= &(hdr
->data
.ping
.gossip
[gossipcount
]);
801 memcpy(gossip
->nodename
,this->name
,REDIS_CLUSTER_NAMELEN
);
802 gossip
->ping_sent
= htonl(this->ping_sent
);
803 gossip
->pong_received
= htonl(this->pong_received
);
804 memcpy(gossip
->ip
,this->ip
,sizeof(this->ip
));
805 gossip
->port
= htons(this->port
);
806 gossip
->flags
= htons(this->flags
);
809 totlen
= sizeof(clusterMsg
)-sizeof(union clusterMsgData
);
810 totlen
+= (sizeof(clusterMsgDataGossip
)*gossipcount
);
811 hdr
->count
= htons(gossipcount
);
812 hdr
->totlen
= htonl(totlen
);
813 clusterSendMessage(link
,buf
,totlen
);
816 /* Send a message to all the nodes with a reliable link */
817 void clusterBroadcastMessage(void *buf
, size_t len
) {
821 di
= dictGetIterator(server
.cluster
.nodes
);
822 while((de
= dictNext(di
)) != NULL
) {
823 clusterNode
*node
= dictGetEntryVal(de
);
825 if (!node
->link
) continue;
826 if (node
->flags
& (REDIS_NODE_MYSELF
|REDIS_NODE_NOADDR
)) continue;
827 clusterSendMessage(node
->link
,buf
,len
);
829 dictReleaseIterator(di
);
832 /* Send a FAIL message to all the nodes we are able to contact.
833 * The FAIL message is sent when we detect that a node is failing
834 * (REDIS_NODE_PFAIL) and we also receive a gossip confirmation of this:
835 * we switch the node state to REDIS_NODE_FAIL and ask all the other
836 * nodes to do the same ASAP. */
837 void clusterSendFail(char *nodename
) {
838 unsigned char buf
[1024];
839 clusterMsg
*hdr
= (clusterMsg
*) buf
;
841 clusterBuildMessageHdr(hdr
,CLUSTERMSG_TYPE_FAIL
);
842 memcpy(hdr
->data
.fail
.about
.nodename
,nodename
,REDIS_CLUSTER_NAMELEN
);
843 clusterBroadcastMessage(buf
,ntohl(hdr
->totlen
));
846 /* -----------------------------------------------------------------------------
848 * -------------------------------------------------------------------------- */
850 /* This is executed 1 time every second */
851 void clusterCron(void) {
855 time_t min_ping_sent
= 0;
856 clusterNode
*min_ping_node
= NULL
;
858 /* Check if we have disconnected nodes and reestablish the connection. */
859 di
= dictGetIterator(server
.cluster
.nodes
);
860 while((de
= dictNext(di
)) != NULL
) {
861 clusterNode
*node
= dictGetEntryVal(de
);
863 if (node
->flags
& (REDIS_NODE_MYSELF
|REDIS_NODE_NOADDR
)) continue;
864 if (node
->link
== NULL
) {
868 fd
= anetTcpNonBlockConnect(server
.neterr
, node
->ip
,
869 node
->port
+REDIS_CLUSTER_PORT_INCR
);
870 if (fd
== -1) continue;
871 link
= createClusterLink(node
);
874 aeCreateFileEvent(server
.el
,link
->fd
,AE_READABLE
,clusterReadHandler
,link
);
875 /* If the node is flagged as MEET, we send a MEET message instead
876 * of a PING one, to force the receiver to add us in its node
878 clusterSendPing(link
, node
->flags
& REDIS_NODE_MEET
?
879 CLUSTERMSG_TYPE_MEET
: CLUSTERMSG_TYPE_PING
);
880 /* We can clear the flag after the first packet is sent.
881 * If we'll never receive a PONG, we'll never send new packets
882 * to this node. Instead after the PONG is received and we
883 * are no longer in meet/handshake status, we want to send
884 * normal PING packets. */
885 node
->flags
&= ~REDIS_NODE_MEET
;
887 redisLog(REDIS_NOTICE
,"Connecting with Node %.40s at %s:%d", node
->name
, node
->ip
, node
->port
+REDIS_CLUSTER_PORT_INCR
);
890 dictReleaseIterator(di
);
892 /* Ping some random node. Check a few random nodes and ping the one with
893 * the oldest ping_sent time */
894 for (j
= 0; j
< 5; j
++) {
895 de
= dictGetRandomKey(server
.cluster
.nodes
);
896 clusterNode
*this = dictGetEntryVal(de
);
898 if (this->link
== NULL
) continue;
899 if (this->flags
& (REDIS_NODE_MYSELF
|REDIS_NODE_HANDSHAKE
)) continue;
900 if (min_ping_node
== NULL
|| min_ping_sent
> this->ping_sent
) {
901 min_ping_node
= this;
902 min_ping_sent
= this->ping_sent
;
906 redisLog(REDIS_DEBUG
,"Pinging node %40s", min_ping_node
->name
);
907 clusterSendPing(min_ping_node
->link
, CLUSTERMSG_TYPE_PING
);
910 /* Iterate nodes to check if we need to flag something as failing */
911 di
= dictGetIterator(server
.cluster
.nodes
);
912 while((de
= dictNext(di
)) != NULL
) {
913 clusterNode
*node
= dictGetEntryVal(de
);
917 (REDIS_NODE_MYSELF
|REDIS_NODE_NOADDR
|REDIS_NODE_HANDSHAKE
|
918 REDIS_NODE_FAIL
)) continue;
919 /* Check only if we already sent a ping and did not received
921 if (node
->ping_sent
== 0 ||
922 node
->ping_sent
<= node
->pong_received
) continue;
924 delay
= time(NULL
) - node
->pong_received
;
925 if (node
->flags
& REDIS_NODE_PFAIL
) {
926 /* The PFAIL condition can be reversed without external
927 * help if it is not transitive (that is, if it does not
928 * turn into a FAIL state). */
929 if (delay
< server
.cluster
.node_timeout
)
930 node
->flags
&= ~REDIS_NODE_PFAIL
;
932 if (delay
>= server
.cluster
.node_timeout
) {
933 redisLog(REDIS_DEBUG
,"*** NODE %.40s possibly failing",
935 node
->flags
|= REDIS_NODE_PFAIL
;
939 dictReleaseIterator(di
);
942 /* -----------------------------------------------------------------------------
944 * -------------------------------------------------------------------------- */
946 /* Set the slot bit and return the old value. */
947 int clusterNodeSetSlotBit(clusterNode
*n
, int slot
) {
950 int old
= (n
->slots
[byte
] & (1<<bit
)) != 0;
951 n
->slots
[byte
] |= 1<<bit
;
955 /* Clear the slot bit and return the old value. */
956 int clusterNodeClearSlotBit(clusterNode
*n
, int slot
) {
959 int old
= (n
->slots
[byte
] & (1<<bit
)) != 0;
960 n
->slots
[byte
] &= ~(1<<bit
);
964 /* Return the slot bit from the cluster node structure. */
965 int clusterNodeGetSlotBit(clusterNode
*n
, int slot
) {
968 return (n
->slots
[byte
] & (1<<bit
)) != 0;
971 /* Add the specified slot to the list of slots that node 'n' will
972 * serve. Return REDIS_OK if the operation ended with success.
973 * If the slot is already assigned to another instance this is considered
974 * an error and REDIS_ERR is returned. */
975 int clusterAddSlot(clusterNode
*n
, int slot
) {
976 redisAssert(clusterNodeSetSlotBit(n
,slot
) == 0);
977 server
.cluster
.slots
[slot
] = server
.cluster
.myself
;
978 printf("SLOT %d added to %.40s\n", slot
, n
->name
);
982 /* -----------------------------------------------------------------------------
983 * Cluster state evaluation function
984 * -------------------------------------------------------------------------- */
985 void clusterUpdateState(void) {
989 for (j
= 0; j
< REDIS_CLUSTER_SLOTS
; j
++) {
990 if (server
.cluster
.slots
[j
] == NULL
||
991 server
.cluster
.slots
[j
]->flags
& (REDIS_NODE_FAIL
))
998 if (server
.cluster
.state
== REDIS_CLUSTER_NEEDHELP
) {
999 server
.cluster
.state
= REDIS_CLUSTER_NEEDHELP
;
1001 server
.cluster
.state
= REDIS_CLUSTER_OK
;
1004 server
.cluster
.state
= REDIS_CLUSTER_FAIL
;
1008 /* -----------------------------------------------------------------------------
1010 * -------------------------------------------------------------------------- */
1012 sds
clusterGenNodesDescription(void) {
1013 sds ci
= sdsempty();
1018 di
= dictGetIterator(server
.cluster
.nodes
);
1019 while((de
= dictNext(di
)) != NULL
) {
1020 clusterNode
*node
= dictGetEntryVal(de
);
1022 /* Node coordinates */
1023 ci
= sdscatprintf(ci
,"%.40s %s:%d ",
1029 if (node
->flags
== 0) ci
= sdscat(ci
,"noflags,");
1030 if (node
->flags
& REDIS_NODE_MYSELF
) ci
= sdscat(ci
,"myself,");
1031 if (node
->flags
& REDIS_NODE_MASTER
) ci
= sdscat(ci
,"master,");
1032 if (node
->flags
& REDIS_NODE_SLAVE
) ci
= sdscat(ci
,"slave,");
1033 if (node
->flags
& REDIS_NODE_PFAIL
) ci
= sdscat(ci
,"fail?,");
1034 if (node
->flags
& REDIS_NODE_FAIL
) ci
= sdscat(ci
,"fail,");
1035 if (node
->flags
& REDIS_NODE_HANDSHAKE
) ci
=sdscat(ci
,"handshake,");
1036 if (node
->flags
& REDIS_NODE_NOADDR
) ci
= sdscat(ci
,"noaddr,");
1037 if (ci
[sdslen(ci
)-1] == ',') ci
[sdslen(ci
)-1] = ' ';
1039 /* Slave of... or just "-" */
1041 ci
= sdscatprintf(ci
,"%.40s ",node
->slaveof
->name
);
1043 ci
= sdscatprintf(ci
,"- ");
1045 /* Latency from the POV of this node, link status */
1046 ci
= sdscatprintf(ci
,"%ld %ld %s",
1047 (long) node
->ping_sent
,
1048 (long) node
->pong_received
,
1049 node
->link
? "connected" : "disconnected");
1051 /* Slots served by this instance */
1053 for (j
= 0; j
< REDIS_CLUSTER_SLOTS
; j
++) {
1056 if ((bit
= clusterNodeGetSlotBit(node
,j
)) != 0) {
1057 if (start
== -1) start
= j
;
1059 if (start
!= -1 && (!bit
|| j
== REDIS_CLUSTER_SLOTS
-1)) {
1060 if (j
== REDIS_CLUSTER_SLOTS
-1) j
++;
1063 ci
= sdscatprintf(ci
," %d",start
);
1065 ci
= sdscatprintf(ci
," %d-%d",start
,j
-1);
1070 ci
= sdscatlen(ci
,"\n",1);
1072 dictReleaseIterator(di
);
1076 void clusterCommand(redisClient
*c
) {
1077 if (server
.cluster_enabled
== 0) {
1078 addReplyError(c
,"This instance has cluster support disabled");
1082 if (!strcasecmp(c
->argv
[1]->ptr
,"meet") && c
->argc
== 4) {
1084 struct sockaddr_in sa
;
1087 /* Perform sanity checks on IP/port */
1088 if (inet_aton(c
->argv
[2]->ptr
,&sa
.sin_addr
) == 0) {
1089 addReplyError(c
,"Invalid IP address in MEET");
1092 if (getLongFromObjectOrReply(c
, c
->argv
[3], &port
, NULL
) != REDIS_OK
||
1093 port
< 0 || port
> (65535-REDIS_CLUSTER_PORT_INCR
))
1095 addReplyError(c
,"Invalid TCP port specified");
1099 /* Finally add the node to the cluster with a random name, this
1100 * will get fixed in the first handshake (ping/pong). */
1101 n
= createClusterNode(NULL
,REDIS_NODE_HANDSHAKE
|REDIS_NODE_MEET
);
1102 strncpy(n
->ip
,inet_ntoa(sa
.sin_addr
),sizeof(n
->ip
));
1105 addReply(c
,shared
.ok
);
1106 } else if (!strcasecmp(c
->argv
[1]->ptr
,"nodes") && c
->argc
== 2) {
1108 sds ci
= clusterGenNodesDescription();
1110 o
= createObject(REDIS_STRING
,ci
);
1113 } else if (!strcasecmp(c
->argv
[1]->ptr
,"addslots") && c
->argc
>= 3) {
1116 unsigned char *slots
= zmalloc(REDIS_CLUSTER_SLOTS
);
1118 memset(slots
,0,REDIS_CLUSTER_SLOTS
);
1119 /* Check that all the arguments are parsable and that all the
1120 * slots are not already busy. */
1121 for (j
= 2; j
< c
->argc
; j
++) {
1122 if (getLongLongFromObject(c
->argv
[j
],&slot
) != REDIS_OK
||
1123 slot
< 0 || slot
> REDIS_CLUSTER_SLOTS
)
1125 addReplyError(c
,"Invalid or out of range slot index");
1129 if (server
.cluster
.slots
[slot
]) {
1130 addReplyErrorFormat(c
,"Slot %lld is already busy", slot
);
1134 if (slots
[slot
]++ == 1) {
1135 addReplyErrorFormat(c
,"Slot %d specified multiple times",
1141 for (j
= 0; j
< REDIS_CLUSTER_SLOTS
; j
++) {
1143 int retval
= clusterAddSlot(server
.cluster
.myself
,j
);
1145 redisAssert(retval
== REDIS_OK
);
1149 clusterUpdateState();
1150 clusterSaveConfigOrDie();
1151 addReply(c
,shared
.ok
);
1152 } else if (!strcasecmp(c
->argv
[1]->ptr
,"info") && c
->argc
== 2) {
1153 char *statestr
[] = {"ok","fail","needhelp"};
1154 int slots_assigned
= 0, slots_ok
= 0, slots_pfail
= 0, slots_fail
= 0;
1157 for (j
= 0; j
< REDIS_CLUSTER_SLOTS
; j
++) {
1158 clusterNode
*n
= server
.cluster
.slots
[j
];
1160 if (n
== NULL
) continue;
1162 if (n
->flags
& REDIS_NODE_FAIL
) {
1164 } else if (n
->flags
& REDIS_NODE_PFAIL
) {
1171 sds info
= sdscatprintf(sdsempty(),
1172 "cluster_state:%s\r\n"
1173 "cluster_slots_assigned:%d\r\n"
1174 "cluster_slots_ok:%d\r\n"
1175 "cluster_slots_pfail:%d\r\n"
1176 "cluster_slots_fail:%d\r\n"
1177 , statestr
[server
.cluster
.state
],
1183 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
1184 (unsigned long)sdslen(info
)));
1185 addReplySds(c
,info
);
1186 addReply(c
,shared
.crlf
);
1188 addReplyError(c
,"Wrong CLUSTER subcommand or number of arguments");
1192 /* -----------------------------------------------------------------------------
1193 * RESTORE and MIGRATE commands
1194 * -------------------------------------------------------------------------- */
1196 /* RESTORE key ttl serialized-value */
1197 void restoreCommand(redisClient
*c
) {
1201 unsigned char *data
;
1204 /* Make sure this key does not already exist here... */
1205 if (dbExists(c
->db
,c
->argv
[1])) {
1206 addReplyError(c
,"Target key name is busy.");
1210 /* Check if the TTL value makes sense */
1211 if (getLongFromObjectOrReply(c
,c
->argv
[2],&ttl
,NULL
) != REDIS_OK
) {
1213 } else if (ttl
< 0) {
1214 addReplyError(c
,"Invalid TTL value, must be >= 0");
1218 /* rdbLoadObject() only works against file descriptors so we need to
1219 * dump the serialized object into a file and reload. */
1220 snprintf(buf
,sizeof(buf
),"redis-restore-%d.tmp",getpid());
1221 fp
= fopen(buf
,"w+");
1223 redisLog(REDIS_WARNING
,"Can't open tmp file for RESTORE: %s",
1225 addReplyErrorFormat(c
,"RESTORE failed, tmp file creation error: %s",
1231 /* Write the actual data and rewind the file */
1232 data
= (unsigned char*) c
->argv
[3]->ptr
;
1233 if (fwrite(data
+1,sdslen((sds
)data
)-1,1,fp
) != 1) {
1234 redisLog(REDIS_WARNING
,"Can't write against tmp file for RESTORE: %s",
1236 addReplyError(c
,"RESTORE failed, tmp file I/O error.");
1242 /* Finally create the object from the serialized dump and
1243 * store it at the specified key. */
1244 if ((data
[0] > 4 && data
[0] < 9) ||
1246 (o
= rdbLoadObject(data
[0],fp
)) == NULL
)
1248 addReplyError(c
,"Bad data format.");
1254 /* Create the key and set the TTL if any */
1255 dbAdd(c
->db
,c
->argv
[1],o
);
1256 if (ttl
) setExpire(c
->db
,c
->argv
[1],time(NULL
)+ttl
);
1257 addReply(c
,shared
.ok
);
1260 /* MIGRATE host port key dbid timeout */
1261 void migrateCommand(redisClient
*c
) {
1273 if (getLongFromObjectOrReply(c
,c
->argv
[5],&timeout
,NULL
) != REDIS_OK
)
1275 if (getLongFromObjectOrReply(c
,c
->argv
[4],&dbid
,NULL
) != REDIS_OK
)
1277 if (timeout
<= 0) timeout
= 1;
1279 /* Check if the key is here. If not we reply with success as there is
1280 * nothing to migrate (for instance the key expired in the meantime), but
1281 * we include such information in the reply string. */
1282 if ((o
= lookupKeyRead(c
->db
,c
->argv
[3])) == NULL
) {
1283 addReplySds(c
,sdsnew("+NOKEY"));
1288 fd
= anetTcpNonBlockConnect(server
.neterr
,c
->argv
[1]->ptr
,
1289 atoi(c
->argv
[2]->ptr
));
1291 addReplyErrorFormat(c
,"Can't connect to target node: %s",
1295 if ((aeWait(fd
,AE_WRITABLE
,timeout
*1000) & AE_WRITABLE
) == 0) {
1296 addReplyError(c
,"Timeout connecting to the client");
1300 /* Create temp file */
1301 snprintf(buf
,sizeof(buf
),"redis-migrate-%d.tmp",getpid());
1302 fp
= fopen(buf
,"w+");
1304 redisLog(REDIS_WARNING
,"Can't open tmp file for MIGRATE: %s",
1306 addReplyErrorFormat(c
,"MIGRATE failed, tmp file creation error: %s.",
1312 /* Build the SELECT + RESTORE query writing it in our temp file. */
1313 if (fwriteBulkCount(fp
,'*',2) == 0) goto file_wr_err
;
1314 if (fwriteBulkString(fp
,"SELECT",6) == 0) goto file_wr_err
;
1315 if (fwriteBulkLongLong(fp
,dbid
) == 0) goto file_wr_err
;
1317 ttl
= getExpire(c
->db
,c
->argv
[3]);
1319 if (fwriteBulkCount(fp
,'*',4) == 0) goto file_wr_err
;
1320 if (fwriteBulkString(fp
,"RESTORE",7) == 0) goto file_wr_err
;
1321 if (fwriteBulkObject(fp
,c
->argv
[3]) == 0) goto file_wr_err
;
1322 if (fwriteBulkLongLong(fp
, (ttl
== -1) ? 0 : ttl
) == 0) goto file_wr_err
;
1324 /* Finally the last argument that is the serailized object payload
1325 * in the form: <type><rdb-serailized-object>. */
1326 payload_len
= rdbSavedObjectLen(o
);
1327 if (fwriteBulkCount(fp
,'$',payload_len
+1) == 0) goto file_wr_err
;
1328 if (fwrite(&type
,1,1,fp
) == 0) goto file_wr_err
;
1329 if (rdbSaveObject(fp
,o
) == -1) goto file_wr_err
;
1330 if (fwrite("\r\n",2,1,fp
) == 0) goto file_wr_err
;
1332 /* Tranfer the query to the other node */
1338 while ((nread
= fread(buf
,1,sizeof(buf
),fp
)) != 0) {
1341 nwritten
= syncWrite(fd
,buf
,nread
,timeout
);
1342 if (nwritten
!= (signed)nread
) goto socket_wr_err
;
1344 if (ferror(fp
)) goto file_rd_err
;
1347 /* Read back the reply */
1352 /* Read the two replies */
1353 if (syncReadLine(fd
, buf1
, sizeof(buf1
), timeout
) <= 0)
1355 if (syncReadLine(fd
, buf2
, sizeof(buf2
), timeout
) <= 0)
1357 if (buf1
[0] == '-' || buf2
[0] == '-') {
1358 addReplyErrorFormat(c
,"Target instance replied with error: %s",
1359 (buf1
[0] == '-') ? buf1
+1 : buf2
+1);
1361 dbDelete(c
->db
,c
->argv
[3]);
1362 addReply(c
,shared
.ok
);
1370 redisLog(REDIS_WARNING
,"Can't write on tmp file for MIGRATE: %s",
1372 addReplyErrorFormat(c
,"MIGRATE failed, tmp file write error: %s.",
1379 redisLog(REDIS_WARNING
,"Can't read from tmp file for MIGRATE: %s",
1381 addReplyErrorFormat(c
,"MIGRATE failed, tmp file read error: %s.",
1388 redisLog(REDIS_NOTICE
,"Can't write to target node for MIGRATE: %s",
1390 addReplyErrorFormat(c
,"MIGRATE failed, writing to target node: %s.",
1397 redisLog(REDIS_NOTICE
,"Can't read from target node for MIGRATE: %s",
1399 addReplyErrorFormat(c
,"MIGRATE failed, reading from target node: %s.",
1407 * DUMP is actually not used by Redis Cluster but it is the obvious
1408 * complement of RESTORE and can be useful for different applications. */
1409 void dumpCommand(redisClient
*c
) {
1417 /* Check if the key is here. */
1418 if ((o
= lookupKeyRead(c
->db
,c
->argv
[1])) == NULL
) {
1419 addReply(c
,shared
.nullbulk
);
1423 /* Create temp file */
1424 snprintf(buf
,sizeof(buf
),"redis-dump-%d.tmp",getpid());
1425 fp
= fopen(buf
,"w+");
1427 redisLog(REDIS_WARNING
,"Can't open tmp file for MIGRATE: %s",
1429 addReplyErrorFormat(c
,"DUMP failed, tmp file creation error: %s.",
1435 /* Dump the serailized object and read it back in memory.
1436 * We prefix it with a one byte containing the type ID.
1437 * This is the serialization format understood by RESTORE. */
1438 if (rdbSaveObject(fp
,o
) == -1) goto file_wr_err
;
1439 payload_len
= ftello(fp
);
1440 if (fseeko(fp
,0,SEEK_SET
) == -1) goto file_rd_err
;
1441 dump
= sdsnewlen(NULL
,payload_len
+1);
1442 if (payload_len
&& fread(dump
+1,payload_len
,1,fp
) != 1) goto file_rd_err
;
1445 if (type
== REDIS_LIST
&& o
->encoding
== REDIS_ENCODING_ZIPLIST
)
1446 type
= REDIS_LIST_ZIPLIST
;
1447 else if (type
== REDIS_HASH
&& o
->encoding
== REDIS_ENCODING_ZIPMAP
)
1448 type
= REDIS_HASH_ZIPMAP
;
1449 else if (type
== REDIS_SET
&& o
->encoding
== REDIS_ENCODING_INTSET
)
1450 type
= REDIS_SET_INTSET
;
1455 /* Transfer to the client */
1456 dumpobj
= createObject(REDIS_STRING
,dump
);
1457 addReplyBulk(c
,dumpobj
);
1458 decrRefCount(dumpobj
);
1462 redisLog(REDIS_WARNING
,"Can't write on tmp file for DUMP: %s",
1464 addReplyErrorFormat(c
,"DUMP failed, tmp file write error: %s.",
1471 redisLog(REDIS_WARNING
,"Can't read from tmp file for DUMP: %s",
1473 addReplyErrorFormat(c
,"DUMP failed, tmp file read error: %s.",
1480 /* -----------------------------------------------------------------------------
1481 * Cluster functions related to serving / redirecting clients
1482 * -------------------------------------------------------------------------- */
1484 /* Return the pointer to the cluster node that is able to serve the query
1485 * as all the keys belong to hash slots for which the node is in charge.
1487 * If keys in query spawn multiple nodes NULL is returned. */
1488 clusterNode
*getNodeByQuery(redisClient
*c
, struct redisCommand
*cmd
, robj
**argv
, int argc
, int *hashslot
) {
1489 clusterNode
*n
= NULL
;
1490 multiState
*ms
, _ms
;
1494 /* We handle all the cases as if they were EXEC commands, so we have
1495 * a common code path for everything */
1496 if (cmd
->proc
== execCommand
) {
1497 /* If REDIS_MULTI flag is not set EXEC is just going to return an
1499 if (!(c
->flags
& REDIS_MULTI
)) return server
.cluster
.myself
;
1502 /* Create a fake Multi State structure, with just one command */
1511 for (i
= 0; i
< ms
->count
; i
++) {
1512 struct redisCommand
*mcmd
;
1514 int margc
, *keyindex
, numkeys
, j
;
1516 mcmd
= ms
->commands
[i
].cmd
;
1517 margc
= ms
->commands
[i
].argc
;
1518 margv
= ms
->commands
[i
].argv
;
1520 keyindex
= getKeysFromCommand(mcmd
,margv
,margc
,&numkeys
,
1521 REDIS_GETKEYS_PRELOAD
);
1522 for (j
= 0; j
< numkeys
; j
++) {
1523 int slot
= keyHashSlot((char*)margv
[keyindex
[j
]]->ptr
,
1524 sdslen(margv
[keyindex
[j
]]->ptr
));
1525 struct clusterNode
*slotnode
;
1527 slotnode
= server
.cluster
.slots
[slot
];
1528 if (hashslot
) *hashslot
= slot
;
1529 /* Node not assigned? (Should never happen actually
1530 * if we reached this function).
1531 * Different node than the previous one?
1532 * Return NULL, the cluster can't serve multi-node requests */
1533 if (slotnode
== NULL
|| (n
&& slotnode
!= n
)) {
1534 getKeysFreeResult(keyindex
);
1540 getKeysFreeResult(keyindex
);
1542 return (n
== NULL
) ? server
.cluster
.myself
: n
;