xref: /redis-3.2.3/src/cluster.h (revision 34882878)
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_DEFAULT_NODE_TIMEOUT 15000
17 #define CLUSTER_DEFAULT_SLAVE_VALIDITY 10 /* Slave max data age factor. */
18 #define CLUSTER_DEFAULT_REQUIRE_FULL_COVERAGE 1
19 #define CLUSTER_FAIL_REPORT_VALIDITY_MULT 2 /* Fail report validity. */
20 #define CLUSTER_FAIL_UNDO_TIME_MULT 2 /* Undo fail if master is back. */
21 #define CLUSTER_FAIL_UNDO_TIME_ADD 10 /* Some additional time. */
22 #define CLUSTER_FAILOVER_DELAY 5 /* Seconds */
23 #define CLUSTER_DEFAULT_MIGRATION_BARRIER 1
24 #define CLUSTER_MF_TIMEOUT 5000 /* Milliseconds to do a manual failover. */
25 #define CLUSTER_MF_PAUSE_MULT 2 /* Master pause manual failover mult. */
26 
27 /* Redirection errors returned by getNodeByQuery(). */
28 #define CLUSTER_REDIR_NONE 0          /* Node can serve the request. */
29 #define CLUSTER_REDIR_CROSS_SLOT 1    /* -CROSSSLOT request. */
30 #define CLUSTER_REDIR_UNSTABLE 2      /* -TRYAGAIN redirection required */
31 #define CLUSTER_REDIR_ASK 3           /* -ASK redirection required. */
32 #define CLUSTER_REDIR_MOVED 4         /* -MOVED redirection required. */
33 #define CLUSTER_REDIR_DOWN_STATE 5    /* -CLUSTERDOWN, global state. */
34 #define CLUSTER_REDIR_DOWN_UNBOUND 6  /* -CLUSTERDOWN, unbound slot. */
35 
36 struct clusterNode;
37 
38 /* clusterLink encapsulates everything needed to talk with a remote node. */
39 typedef struct clusterLink {
40     mstime_t ctime;             /* Link creation time */
41     int fd;                     /* TCP socket file descriptor */
42     sds sndbuf;                 /* Packet send buffer */
43     sds rcvbuf;                 /* Packet reception buffer */
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 elegible for replica migration. */
57 #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"
58 
59 #define nodeIsMaster(n) ((n)->flags & CLUSTER_NODE_MASTER)
60 #define nodeIsSlave(n) ((n)->flags & CLUSTER_NODE_SLAVE)
61 #define nodeInHandshake(n) ((n)->flags & CLUSTER_NODE_HANDSHAKE)
62 #define nodeHasAddr(n) (!((n)->flags & CLUSTER_NODE_NOADDR))
63 #define nodeWithoutAddr(n) ((n)->flags & CLUSTER_NODE_NOADDR)
64 #define nodeTimedOut(n) ((n)->flags & CLUSTER_NODE_PFAIL)
65 #define nodeFailed(n) ((n)->flags & CLUSTER_NODE_FAIL)
66 
67 /* Reasons why a slave is not able to failover. */
68 #define CLUSTER_CANT_FAILOVER_NONE 0
69 #define CLUSTER_CANT_FAILOVER_DATA_AGE 1
70 #define CLUSTER_CANT_FAILOVER_WAITING_DELAY 2
71 #define CLUSTER_CANT_FAILOVER_EXPIRED 3
72 #define CLUSTER_CANT_FAILOVER_WAITING_VOTES 4
73 #define CLUSTER_CANT_FAILOVER_RELOG_PERIOD (60*5) /* seconds. */
74 
75 /* This structure represent elements of node->fail_reports. */
76 typedef struct clusterNodeFailReport {
77     struct clusterNode *node;  /* Node reporting the failure condition. */
78     mstime_t time;             /* Time of the last report from this node. */
79 } clusterNodeFailReport;
80 
81 typedef struct clusterNode {
82     mstime_t ctime; /* Node object creation time. */
83     char name[CLUSTER_NAMELEN]; /* Node name, hex string, sha1-size */
84     int flags;      /* CLUSTER_NODE_... */
85     uint64_t configEpoch; /* Last configEpoch observed for this node */
86     unsigned char slots[CLUSTER_SLOTS/8]; /* slots handled by this node */
87     int numslots;   /* Number of slots handled by this node */
88     int numslaves;  /* Number of slave nodes, if this is a master */
89     struct clusterNode **slaves; /* pointers to slave nodes */
90     struct clusterNode *slaveof; /* pointer to the master node */
91     mstime_t ping_sent;      /* Unix time we sent latest ping */
92     mstime_t pong_received;  /* Unix time we received the pong */
93     mstime_t fail_time;      /* Unix time when FAIL flag was set */
94     mstime_t voted_time;     /* Last time we voted for a slave of this master */
95     mstime_t repl_offset_time;  /* Unix time we received offset for this node */
96     long long repl_offset;      /* Last known repl offset for this node. */
97     char ip[NET_IP_STR_LEN];  /* Latest known IP address of this node */
98     int port;                   /* Latest known port of this node */
99     clusterLink *link;          /* TCP/IP link with this node */
100     list *fail_reports;         /* List of nodes signaling this as failing */
101 } clusterNode;
102 
103 typedef struct clusterState {
104     clusterNode *myself;  /* This node */
105     uint64_t currentEpoch;
106     int state;            /* CLUSTER_OK, CLUSTER_FAIL, ... */
107     int size;             /* Num of master nodes with at least one slot */
108     dict *nodes;          /* Hash table of name -> clusterNode structures */
109     dict *nodes_black_list; /* Nodes we don't re-add for a few seconds. */
110     clusterNode *migrating_slots_to[CLUSTER_SLOTS];
111     clusterNode *importing_slots_from[CLUSTER_SLOTS];
112     clusterNode *slots[CLUSTER_SLOTS];
113     zskiplist *slots_to_keys;
114     /* The following fields are used to take the slave state on elections. */
115     mstime_t failover_auth_time; /* Time of previous or next election. */
116     int failover_auth_count;    /* Number of votes received so far. */
117     int failover_auth_sent;     /* True if we already asked for votes. */
118     int failover_auth_rank;     /* This slave rank for current auth request. */
119     uint64_t failover_auth_epoch; /* Epoch of the current election. */
120     int cant_failover_reason;   /* Why a slave is currently not able to
121                                    failover. See the CANT_FAILOVER_* macros. */
122     /* Manual failover state in common. */
123     mstime_t mf_end;            /* Manual failover time limit (ms unixtime).
124                                    It is zero if there is no MF in progress. */
125     /* Manual failover state of master. */
126     clusterNode *mf_slave;      /* Slave performing the manual failover. */
127     /* Manual failover state of slave. */
128     long long mf_master_offset; /* Master offset the slave needs to start MF
129                                    or zero if stil not received. */
130     int mf_can_start;           /* If non-zero signal that the manual failover
131                                    can start requesting masters vote. */
132     /* The followign fields are used by masters to take state on elections. */
133     uint64_t lastVoteEpoch;     /* Epoch of the last vote granted. */
134     int todo_before_sleep; /* Things to do in clusterBeforeSleep(). */
135     long long stats_bus_messages_sent;  /* Num of msg sent via cluster bus. */
136     long long stats_bus_messages_received; /* Num of msg rcvd via cluster bus.*/
137 } clusterState;
138 
139 /* clusterState todo_before_sleep flags. */
140 #define CLUSTER_TODO_HANDLE_FAILOVER (1<<0)
141 #define CLUSTER_TODO_UPDATE_STATE (1<<1)
142 #define CLUSTER_TODO_SAVE_CONFIG (1<<2)
143 #define CLUSTER_TODO_FSYNC_CONFIG (1<<3)
144 
145 /* Redis cluster messages header */
146 
147 /* Note that the PING, PONG and MEET messages are actually the same exact
148  * kind of packet. PONG is the reply to ping, in the exact format as a PING,
149  * while MEET is a special PING that forces the receiver to add the sender
150  * as a node (if it is not already in the list). */
151 #define CLUSTERMSG_TYPE_PING 0          /* Ping */
152 #define CLUSTERMSG_TYPE_PONG 1          /* Pong (reply to Ping) */
153 #define CLUSTERMSG_TYPE_MEET 2          /* Meet "let's join" message */
154 #define CLUSTERMSG_TYPE_FAIL 3          /* Mark node xxx as failing */
155 #define CLUSTERMSG_TYPE_PUBLISH 4       /* Pub/Sub Publish propagation */
156 #define CLUSTERMSG_TYPE_FAILOVER_AUTH_REQUEST 5 /* May I failover? */
157 #define CLUSTERMSG_TYPE_FAILOVER_AUTH_ACK 6     /* Yes, you have my vote */
158 #define CLUSTERMSG_TYPE_UPDATE 7        /* Another node slots configuration */
159 #define CLUSTERMSG_TYPE_MFSTART 8       /* Pause clients for manual failover */
160 
161 /* Initially we don't know our "name", but we'll find it once we connect
162  * to the first node, using the getsockname() function. Then we'll use this
163  * address for all the next messages. */
164 typedef struct {
165     char nodename[CLUSTER_NAMELEN];
166     uint32_t ping_sent;
167     uint32_t pong_received;
168     char ip[NET_IP_STR_LEN];  /* IP address last time it was seen */
169     uint16_t port;              /* port last time it was seen */
170     uint16_t flags;             /* node->flags copy */
171     uint16_t notused1;          /* Some room for future improvements. */
172     uint32_t notused2;
173 } clusterMsgDataGossip;
174 
175 typedef struct {
176     char nodename[CLUSTER_NAMELEN];
177 } clusterMsgDataFail;
178 
179 typedef struct {
180     uint32_t channel_len;
181     uint32_t message_len;
182     /* We can't reclare bulk_data as bulk_data[] since this structure is
183      * nested. The 8 bytes are removed from the count during the message
184      * length computation. */
185     unsigned char bulk_data[8];
186 } clusterMsgDataPublish;
187 
188 typedef struct {
189     uint64_t configEpoch; /* Config epoch of the specified instance. */
190     char nodename[CLUSTER_NAMELEN]; /* Name of the slots owner. */
191     unsigned char slots[CLUSTER_SLOTS/8]; /* Slots bitmap. */
192 } clusterMsgDataUpdate;
193 
194 union clusterMsgData {
195     /* PING, MEET and PONG */
196     struct {
197         /* Array of N clusterMsgDataGossip structures */
198         clusterMsgDataGossip gossip[1];
199     } ping;
200 
201     /* FAIL */
202     struct {
203         clusterMsgDataFail about;
204     } fail;
205 
206     /* PUBLISH */
207     struct {
208         clusterMsgDataPublish msg;
209     } publish;
210 
211     /* UPDATE */
212     struct {
213         clusterMsgDataUpdate nodecfg;
214     } update;
215 };
216 
217 #define CLUSTER_PROTO_VER 0 /* Cluster bus protocol version. */
218 
219 typedef struct {
220     char sig[4];        /* Siganture "RCmb" (Redis Cluster message bus). */
221     uint32_t totlen;    /* Total length of this message */
222     uint16_t ver;       /* Protocol version, currently set to 0. */
223     uint16_t notused0;  /* 2 bytes not used. */
224     uint16_t type;      /* Message type */
225     uint16_t count;     /* Only used for some kind of messages. */
226     uint64_t currentEpoch;  /* The epoch accordingly to the sending node. */
227     uint64_t configEpoch;   /* The config epoch if it's a master, or the last
228                                epoch advertised by its master if it is a
229                                slave. */
230     uint64_t offset;    /* Master replication offset if node is a master or
231                            processed replication offset if node is a slave. */
232     char sender[CLUSTER_NAMELEN]; /* Name of the sender node */
233     unsigned char myslots[CLUSTER_SLOTS/8];
234     char slaveof[CLUSTER_NAMELEN];
235     char notused1[32];  /* 32 bytes reserved for future usage. */
236     uint16_t port;      /* Sender TCP base port */
237     uint16_t flags;     /* Sender node flags */
238     unsigned char state; /* Cluster state from the POV of the sender */
239     unsigned char mflags[3]; /* Message flags: CLUSTERMSG_FLAG[012]_... */
240     union clusterMsgData data;
241 } clusterMsg;
242 
243 #define CLUSTERMSG_MIN_LEN (sizeof(clusterMsg)-sizeof(union clusterMsgData))
244 
245 /* Message flags better specify the packet content or are used to
246  * provide some information about the node state. */
247 #define CLUSTERMSG_FLAG0_PAUSED (1<<0) /* Master paused for manual failover. */
248 #define CLUSTERMSG_FLAG0_FORCEACK (1<<1) /* Give ACK to AUTH_REQUEST even if
249                                             master is up. */
250 
251 /* ---------------------- API exported outside cluster.c -------------------- */
252 clusterNode *getNodeByQuery(client *c, struct redisCommand *cmd, robj **argv, int argc, int *hashslot, int *ask);
253 int clusterRedirectBlockedClientIfNeeded(client *c);
254 void clusterRedirectClient(client *c, clusterNode *n, int hashslot, int error_code);
255 
256 #endif /* __CLUSTER_H */
257