1 #ifndef __CLUSTER_H
2 #define __CLUSTER_H
3 
4 /*-----------------------------------------------------------------------------
5  * Redis cluster data structures, defines, exported API.
6  *----------------------------------------------------------------------------*/
7 
8 #define CLUSTER_SLOTS 16384
9 #define CLUSTER_OK 0          /* Everything looks ok */
10 #define CLUSTER_FAIL 1        /* The cluster can't work */
11 #define CLUSTER_NAMELEN 40    /* sha1 hex length */
12 #define CLUSTER_PORT_INCR 10000 /* Cluster port = baseport + PORT_INCR */
13 
14 /* The following defines are amount of time, sometimes expressed as
15  * multiplicators of the node timeout value (when ending with MULT). */
16 #define CLUSTER_FAIL_REPORT_VALIDITY_MULT 2 /* Fail report validity. */
17 #define CLUSTER_FAIL_UNDO_TIME_MULT 2 /* Undo fail if master is back. */
18 #define CLUSTER_FAIL_UNDO_TIME_ADD 10 /* Some additional time. */
19 #define CLUSTER_FAILOVER_DELAY 5 /* Seconds */
20 #define CLUSTER_MF_TIMEOUT 5000 /* Milliseconds to do a manual failover. */
21 #define CLUSTER_MF_PAUSE_MULT 2 /* Master pause manual failover mult. */
22 #define CLUSTER_SLAVE_MIGRATION_DELAY 5000 /* Delay for slave migration. */
23 
24 /* Redirection errors returned by getNodeByQuery(). */
25 #define CLUSTER_REDIR_NONE 0          /* Node can serve the request. */
26 #define CLUSTER_REDIR_CROSS_SLOT 1    /* -CROSSSLOT request. */
27 #define CLUSTER_REDIR_UNSTABLE 2      /* -TRYAGAIN redirection required */
28 #define CLUSTER_REDIR_ASK 3           /* -ASK redirection required. */
29 #define CLUSTER_REDIR_MOVED 4         /* -MOVED redirection required. */
30 #define CLUSTER_REDIR_DOWN_STATE 5    /* -CLUSTERDOWN, global state. */
31 #define CLUSTER_REDIR_DOWN_UNBOUND 6  /* -CLUSTERDOWN, unbound slot. */
32 #define CLUSTER_REDIR_DOWN_RO_STATE 7 /* -CLUSTERDOWN, allow reads. */
33 
34 struct clusterNode;
35 
36 /* clusterLink encapsulates everything needed to talk with a remote node. */
37 typedef struct clusterLink {
38     mstime_t ctime;             /* Link creation time */
39     connection *conn;           /* Connection to remote node */
40     sds sndbuf;                 /* Packet send buffer */
41     char *rcvbuf;               /* Packet reception buffer */
42     size_t rcvbuf_len;          /* Used size of rcvbuf */
43     size_t rcvbuf_alloc;        /* Used size of rcvbuf */
44     struct clusterNode *node;   /* Node related to this link if any, or NULL */
45 } clusterLink;
46 
47 /* Cluster node flags and macros. */
48 #define CLUSTER_NODE_MASTER 1     /* The node is a master */
49 #define CLUSTER_NODE_SLAVE 2      /* The node is a slave */
50 #define CLUSTER_NODE_PFAIL 4      /* Failure? Need acknowledge */
51 #define CLUSTER_NODE_FAIL 8       /* The node is believed to be malfunctioning */
52 #define CLUSTER_NODE_MYSELF 16    /* This node is myself */
53 #define CLUSTER_NODE_HANDSHAKE 32 /* We have still to exchange the first ping */
54 #define CLUSTER_NODE_NOADDR   64  /* We don't know the address of this node */
55 #define CLUSTER_NODE_MEET 128     /* Send a MEET message to this node */
56 #define CLUSTER_NODE_MIGRATE_TO 256 /* Master eligible for replica migration. */
57 #define CLUSTER_NODE_NOFAILOVER 512 /* Slave will not try to failover. */
58 #define CLUSTER_NODE_NULL_NAME "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"
59 
60 #define nodeIsMaster(n) ((n)->flags & CLUSTER_NODE_MASTER)
61 #define nodeIsSlave(n) ((n)->flags & CLUSTER_NODE_SLAVE)
62 #define nodeInHandshake(n) ((n)->flags & CLUSTER_NODE_HANDSHAKE)
63 #define nodeHasAddr(n) (!((n)->flags & CLUSTER_NODE_NOADDR))
64 #define nodeWithoutAddr(n) ((n)->flags & CLUSTER_NODE_NOADDR)
65 #define nodeTimedOut(n) ((n)->flags & CLUSTER_NODE_PFAIL)
66 #define nodeFailed(n) ((n)->flags & CLUSTER_NODE_FAIL)
67 #define nodeCantFailover(n) ((n)->flags & CLUSTER_NODE_NOFAILOVER)
68 
69 /* Reasons why a slave is not able to failover. */
70 #define CLUSTER_CANT_FAILOVER_NONE 0
71 #define CLUSTER_CANT_FAILOVER_DATA_AGE 1
72 #define CLUSTER_CANT_FAILOVER_WAITING_DELAY 2
73 #define CLUSTER_CANT_FAILOVER_EXPIRED 3
74 #define CLUSTER_CANT_FAILOVER_WAITING_VOTES 4
75 #define CLUSTER_CANT_FAILOVER_RELOG_PERIOD (60*5) /* seconds. */
76 
77 /* clusterState todo_before_sleep flags. */
78 #define CLUSTER_TODO_HANDLE_FAILOVER (1<<0)
79 #define CLUSTER_TODO_UPDATE_STATE (1<<1)
80 #define CLUSTER_TODO_SAVE_CONFIG (1<<2)
81 #define CLUSTER_TODO_FSYNC_CONFIG (1<<3)
82 
83 /* Message types.
84  *
85  * Note that the PING, PONG and MEET messages are actually the same exact
86  * kind of packet. PONG is the reply to ping, in the exact format as a PING,
87  * while MEET is a special PING that forces the receiver to add the sender
88  * as a node (if it is not already in the list). */
89 #define CLUSTERMSG_TYPE_PING 0          /* Ping */
90 #define CLUSTERMSG_TYPE_PONG 1          /* Pong (reply to Ping) */
91 #define CLUSTERMSG_TYPE_MEET 2          /* Meet "let's join" message */
92 #define CLUSTERMSG_TYPE_FAIL 3          /* Mark node xxx as failing */
93 #define CLUSTERMSG_TYPE_PUBLISH 4       /* Pub/Sub Publish propagation */
94 #define CLUSTERMSG_TYPE_FAILOVER_AUTH_REQUEST 5 /* May I failover? */
95 #define CLUSTERMSG_TYPE_FAILOVER_AUTH_ACK 6     /* Yes, you have my vote */
96 #define CLUSTERMSG_TYPE_UPDATE 7        /* Another node slots configuration */
97 #define CLUSTERMSG_TYPE_MFSTART 8       /* Pause clients for manual failover */
98 #define CLUSTERMSG_TYPE_MODULE 9        /* Module cluster API message. */
99 #define CLUSTERMSG_TYPE_COUNT 10        /* Total number of message types. */
100 
101 /* Flags that a module can set in order to prevent certain Redis Cluster
102  * features to be enabled. Useful when implementing a different distributed
103  * system on top of Redis Cluster message bus, using modules. */
104 #define CLUSTER_MODULE_FLAG_NONE 0
105 #define CLUSTER_MODULE_FLAG_NO_FAILOVER (1<<1)
106 #define CLUSTER_MODULE_FLAG_NO_REDIRECTION (1<<2)
107 
108 /* This structure represent elements of node->fail_reports. */
109 typedef struct clusterNodeFailReport {
110     struct clusterNode *node;  /* Node reporting the failure condition. */
111     mstime_t time;             /* Time of the last report from this node. */
112 } clusterNodeFailReport;
113 
114 typedef struct clusterNode {
115     mstime_t ctime; /* Node object creation time. */
116     char name[CLUSTER_NAMELEN]; /* Node name, hex string, sha1-size */
117     int flags;      /* CLUSTER_NODE_... */
118     uint64_t configEpoch; /* Last configEpoch observed for this node */
119     unsigned char slots[CLUSTER_SLOTS/8]; /* slots handled by this node */
120     int numslots;   /* Number of slots handled by this node */
121     int numslaves;  /* Number of slave nodes, if this is a master */
122     struct clusterNode **slaves; /* pointers to slave nodes */
123     struct clusterNode *slaveof; /* pointer to the master node. Note that it
124                                     may be NULL even if the node is a slave
125                                     if we don't have the master node in our
126                                     tables. */
127     mstime_t ping_sent;      /* Unix time we sent latest ping */
128     mstime_t pong_received;  /* Unix time we received the pong */
129     mstime_t data_received;  /* Unix time we received any data */
130     mstime_t fail_time;      /* Unix time when FAIL flag was set */
131     mstime_t voted_time;     /* Last time we voted for a slave of this master */
132     mstime_t repl_offset_time;  /* Unix time we received offset for this node */
133     mstime_t orphaned_time;     /* Starting time of orphaned master condition */
134     long long repl_offset;      /* Last known repl offset for this node. */
135     char ip[NET_IP_STR_LEN];  /* Latest known IP address of this node */
136     int port;                   /* Latest known clients port of this node */
137     int cport;                  /* Latest known cluster port of this node. */
138     clusterLink *link;          /* TCP/IP link with this node */
139     list *fail_reports;         /* List of nodes signaling this as failing */
140 } clusterNode;
141 
142 typedef struct clusterState {
143     clusterNode *myself;  /* This node */
144     uint64_t currentEpoch;
145     int state;            /* CLUSTER_OK, CLUSTER_FAIL, ... */
146     int size;             /* Num of master nodes with at least one slot */
147     dict *nodes;          /* Hash table of name -> clusterNode structures */
148     dict *nodes_black_list; /* Nodes we don't re-add for a few seconds. */
149     clusterNode *migrating_slots_to[CLUSTER_SLOTS];
150     clusterNode *importing_slots_from[CLUSTER_SLOTS];
151     clusterNode *slots[CLUSTER_SLOTS];
152     uint64_t slots_keys_count[CLUSTER_SLOTS];
153     rax *slots_to_keys;
154     /* The following fields are used to take the slave state on elections. */
155     mstime_t failover_auth_time; /* Time of previous or next election. */
156     int failover_auth_count;    /* Number of votes received so far. */
157     int failover_auth_sent;     /* True if we already asked for votes. */
158     int failover_auth_rank;     /* This slave rank for current auth request. */
159     uint64_t failover_auth_epoch; /* Epoch of the current election. */
160     int cant_failover_reason;   /* Why a slave is currently not able to
161                                    failover. See the CANT_FAILOVER_* macros. */
162     /* Manual failover state in common. */
163     mstime_t mf_end;            /* Manual failover time limit (ms unixtime).
164                                    It is zero if there is no MF in progress. */
165     /* Manual failover state of master. */
166     clusterNode *mf_slave;      /* Slave performing the manual failover. */
167     /* Manual failover state of slave. */
168     long long mf_master_offset; /* Master offset the slave needs to start MF
169                                    or zero if still not received. */
170     int mf_can_start;           /* If non-zero signal that the manual failover
171                                    can start requesting masters vote. */
172     /* The following fields are used by masters to take state on elections. */
173     uint64_t lastVoteEpoch;     /* Epoch of the last vote granted. */
174     int todo_before_sleep; /* Things to do in clusterBeforeSleep(). */
175     /* Messages received and sent by type. */
176     long long stats_bus_messages_sent[CLUSTERMSG_TYPE_COUNT];
177     long long stats_bus_messages_received[CLUSTERMSG_TYPE_COUNT];
178     long long stats_pfail_nodes;    /* Number of nodes in PFAIL status,
179                                        excluding nodes without address. */
180 } clusterState;
181 
182 /* Redis cluster messages header */
183 
184 /* Initially we don't know our "name", but we'll find it once we connect
185  * to the first node, using the getsockname() function. Then we'll use this
186  * address for all the next messages. */
187 typedef struct {
188     char nodename[CLUSTER_NAMELEN];
189     uint32_t ping_sent;
190     uint32_t pong_received;
191     char ip[NET_IP_STR_LEN];  /* IP address last time it was seen */
192     uint16_t port;              /* base port last time it was seen */
193     uint16_t cport;             /* cluster port last time it was seen */
194     uint16_t flags;             /* node->flags copy */
195     uint32_t notused1;
196 } clusterMsgDataGossip;
197 
198 typedef struct {
199     char nodename[CLUSTER_NAMELEN];
200 } clusterMsgDataFail;
201 
202 typedef struct {
203     uint32_t channel_len;
204     uint32_t message_len;
205     unsigned char bulk_data[8]; /* 8 bytes just as placeholder. */
206 } clusterMsgDataPublish;
207 
208 typedef struct {
209     uint64_t configEpoch; /* Config epoch of the specified instance. */
210     char nodename[CLUSTER_NAMELEN]; /* Name of the slots owner. */
211     unsigned char slots[CLUSTER_SLOTS/8]; /* Slots bitmap. */
212 } clusterMsgDataUpdate;
213 
214 typedef struct {
215     uint64_t module_id;     /* ID of the sender module. */
216     uint32_t len;           /* ID of the sender module. */
217     uint8_t type;           /* Type from 0 to 255. */
218     unsigned char bulk_data[3]; /* 3 bytes just as placeholder. */
219 } clusterMsgModule;
220 
221 union clusterMsgData {
222     /* PING, MEET and PONG */
223     struct {
224         /* Array of N clusterMsgDataGossip structures */
225         clusterMsgDataGossip gossip[1];
226     } ping;
227 
228     /* FAIL */
229     struct {
230         clusterMsgDataFail about;
231     } fail;
232 
233     /* PUBLISH */
234     struct {
235         clusterMsgDataPublish msg;
236     } publish;
237 
238     /* UPDATE */
239     struct {
240         clusterMsgDataUpdate nodecfg;
241     } update;
242 
243     /* MODULE */
244     struct {
245         clusterMsgModule msg;
246     } module;
247 };
248 
249 #define CLUSTER_PROTO_VER 1 /* Cluster bus protocol version. */
250 
251 typedef struct {
252     char sig[4];        /* Signature "RCmb" (Redis Cluster message bus). */
253     uint32_t totlen;    /* Total length of this message */
254     uint16_t ver;       /* Protocol version, currently set to 1. */
255     uint16_t port;      /* TCP base port number. */
256     uint16_t type;      /* Message type */
257     uint16_t count;     /* Only used for some kind of messages. */
258     uint64_t currentEpoch;  /* The epoch accordingly to the sending node. */
259     uint64_t configEpoch;   /* The config epoch if it's a master, or the last
260                                epoch advertised by its master if it is a
261                                slave. */
262     uint64_t offset;    /* Master replication offset if node is a master or
263                            processed replication offset if node is a slave. */
264     char sender[CLUSTER_NAMELEN]; /* Name of the sender node */
265     unsigned char myslots[CLUSTER_SLOTS/8];
266     char slaveof[CLUSTER_NAMELEN];
267     char myip[NET_IP_STR_LEN];    /* Sender IP, if not all zeroed. */
268     char notused1[34];  /* 34 bytes reserved for future usage. */
269     uint16_t cport;      /* Sender TCP cluster bus port */
270     uint16_t flags;      /* Sender node flags */
271     unsigned char state; /* Cluster state from the POV of the sender */
272     unsigned char mflags[3]; /* Message flags: CLUSTERMSG_FLAG[012]_... */
273     union clusterMsgData data;
274 } clusterMsg;
275 
276 #define CLUSTERMSG_MIN_LEN (sizeof(clusterMsg)-sizeof(union clusterMsgData))
277 
278 /* Message flags better specify the packet content or are used to
279  * provide some information about the node state. */
280 #define CLUSTERMSG_FLAG0_PAUSED (1<<0) /* Master paused for manual failover. */
281 #define CLUSTERMSG_FLAG0_FORCEACK (1<<1) /* Give ACK to AUTH_REQUEST even if
282                                             master is up. */
283 
284 /* ---------------------- API exported outside cluster.c -------------------- */
285 clusterNode *getNodeByQuery(client *c, struct redisCommand *cmd, robj **argv, int argc, int *hashslot, int *ask);
286 int clusterRedirectBlockedClientIfNeeded(client *c);
287 void clusterRedirectClient(client *c, clusterNode *n, int hashslot, int error_code);
288 unsigned long getClusterConnectionsCount(void);
289 
290 #endif /* __CLUSTER_H */
291