]>
Commit | Line | Data |
---|---|---|
120ba392 | 1 | /* Redis Sentinel implementation |
2 | * ----------------------------- | |
3 | * | |
4 | * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com> | |
5 | * All rights reserved. | |
6 | * | |
7 | * Redistribution and use in source and binary forms, with or without | |
8 | * modification, are permitted provided that the following conditions are met: | |
9 | * | |
10 | * * Redistributions of source code must retain the above copyright notice, | |
11 | * this list of conditions and the following disclaimer. | |
12 | * * Redistributions in binary form must reproduce the above copyright | |
13 | * notice, this list of conditions and the following disclaimer in the | |
14 | * documentation and/or other materials provided with the distribution. | |
15 | * * Neither the name of Redis nor the names of its contributors may be used | |
16 | * to endorse or promote products derived from this software without | |
17 | * specific prior written permission. | |
18 | * | |
19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |
20 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
21 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | |
22 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE | |
23 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR | |
24 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF | |
25 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS | |
26 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN | |
27 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) | |
28 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE | |
29 | * POSSIBILITY OF SUCH DAMAGE. | |
30 | */ | |
31 | ||
32 | #include "redis.h" | |
33 | #include "hiredis.h" | |
34 | #include "async.h" | |
35 | ||
36 | #include <ctype.h> | |
37 | #include <arpa/inet.h> | |
38 | #include <sys/socket.h> | |
39 | ||
40 | #define REDIS_SENTINEL_PORT 26379 | |
41 | ||
42 | /* ======================== Sentinel global state =========================== */ | |
43 | ||
44 | typedef long long mstime_t; /* millisecond time type. */ | |
45 | ||
46 | /* Address object, used to describe an ip:port pair. */ | |
47 | typedef struct sentinelAddr { | |
48 | char *ip; | |
49 | int port; | |
50 | } sentinelAddr; | |
51 | ||
52 | /* A Sentinel Redis Instance object is monitoring. */ | |
53 | #define SRI_MASTER (1<<0) | |
54 | #define SRI_SLAVE (1<<1) | |
55 | #define SRI_SENTINEL (1<<2) | |
56 | #define SRI_DISCONNECTED (1<<3) | |
57 | #define SRI_S_DOWN (1<<4) /* Subjectively down (no quorum). */ | |
58 | #define SRI_O_DOWN (1<<5) /* Objectively down (quorum reached). */ | |
59 | #define SRI_MASTER_DOWN (1<<6) /* A Sentinel with this flag set thinks that | |
60 | its master is down. */ | |
61 | /* SRI_CAN_FAILOVER when set in an SRI_MASTER instance means that we are | |
62 | * allowed to perform the failover for this master. | |
63 | * When set in a SRI_SENTINEL instance means that sentinel is allowed to | |
64 | * perform the failover on its master. */ | |
65 | #define SRI_CAN_FAILOVER (1<<7) | |
66 | #define SRI_FAILOVER_IN_PROGRESS (1<<8) /* Failover is in progress for | |
67 | this master. */ | |
68 | #define SRI_I_AM_THE_LEADER (1<<9) /* We are the leader for this master. */ | |
69 | #define SRI_PROMOTED (1<<10) /* Slave selected for promotion. */ | |
70 | #define SRI_RECONF_SENT (1<<11) /* SLAVEOF <newmaster> sent. */ | |
71 | #define SRI_RECONF_INPROG (1<<12) /* Slave synchronization in progress. */ | |
72 | #define SRI_RECONF_DONE (1<<13) /* Slave synchronized with new master. */ | |
73 | ||
74 | #define SENTINEL_INFO_PERIOD 10000 | |
75 | #define SENTINEL_PING_PERIOD 1000 | |
76 | #define SENTINEL_ASK_PERIOD 1000 | |
77 | #define SENTINEL_PUBLISH_PERIOD 5000 | |
78 | #define SENTINEL_DOWN_AFTER_PERIOD 30000 | |
79 | #define SENTINEL_HELLO_CHANNEL "__sentinel__:hello" | |
80 | #define SENTINEL_TILT_TRIGGER 2000 | |
81 | #define SENTINEL_TILT_PERIOD (SENTINEL_PING_PERIOD*30) | |
82 | #define SENTINEL_DEFAULT_SLAVE_PRIORITY 100 | |
83 | #define SENTINEL_PROMOTION_RETRY_PERIOD 30000 | |
84 | #define SENTINEL_SLAVE_RECONF_RETRY_PERIOD 10000 | |
85 | #define SENTINEL_DEFAULT_PARALLEL_SYNCS 1 | |
86 | #define SENTINEL_MIN_LINK_RECONNECT_PERIOD 15000 | |
87 | #define SENTINEL_DEFAULT_FAILOVER_TIMEOUT (60*15*1000) | |
88 | #define SENTINEL_MAX_PENDING_COMMANDS 100 | |
89 | #define SENTINEL_EXTENDED_SDOWN_MULTIPLIER 10 | |
90 | ||
91 | /* How many milliseconds is an information valid? This applies for instance | |
92 | * to the reply to SENTINEL IS-MASTER-DOWN-BY-ADDR replies. */ | |
93 | #define SENTINEL_INFO_VALIDITY_TIME 5000 | |
94 | #define SENTINEL_FAILOVER_FIXED_DELAY 5000 | |
95 | #define SENTINEL_FAILOVER_MAX_RANDOM_DELAY 10000 | |
96 | ||
97 | /* Failover machine different states. */ | |
98 | #define SENTINEL_FAILOVER_STATE_NONE 0 /* No failover in progress. */ | |
99 | #define SENTINEL_FAILOVER_STATE_WAIT_START 1 /* Wait for failover_start_time*/ | |
100 | #define SENTINEL_FAILOVER_STATE_SELECT_SLAVE 2 /* Select slave to promote */ | |
101 | #define SENTINEL_FAILOVER_STATE_SEND_SLAVEOF_NOONE 3 /* Slave -> Master */ | |
102 | #define SENTINEL_FAILOVER_STATE_WAIT_PROMOTION 4 /* Wait slave to change role */ | |
103 | #define SENTINEL_FAILOVER_STATE_RECONF_SLAVES 5 /* SLAVEOF newmaster */ | |
104 | #define SENTINEL_FAILOVER_STATE_WAIT_NEXT_SLAVE 6 /* wait replication */ | |
105 | #define SENTINEL_FAILOVER_STATE_ALERT_CLIENTS 7 /* Run user script. */ | |
106 | #define SENTINEL_FAILOVER_STATE_WAIT_ALERT_SCRIPT 8 /* Wait script exec. */ | |
107 | #define SENTINEL_FAILOVER_STATE_DETECT_END 9 /* Check for failover end. */ | |
108 | #define SENTINEL_FAILOVER_STATE_UPDATE_CONFIG 10 /* Monitor promoted slave. */ | |
109 | ||
110 | #define SENTINEL_MASTER_LINK_STATUS_UP 0 | |
111 | #define SENTINEL_MASTER_LINK_STATUS_DOWN 1 | |
112 | ||
e47236d8 | 113 | /* Generic flags that can be used with different functions. */ |
114 | #define SENTINEL_NO_FLAGS 0 | |
115 | #define SENTINEL_GENERATE_EVENT 1 | |
116 | ||
120ba392 | 117 | typedef struct sentinelRedisInstance { |
118 | int flags; /* See SRI_... defines */ | |
119 | char *name; /* Master name from the point of view of this sentinel. */ | |
120 | char *runid; /* run ID of this instance. */ | |
121 | sentinelAddr *addr; /* Master host. */ | |
122 | redisAsyncContext *cc; /* Hiredis context for commands. */ | |
123 | redisAsyncContext *pc; /* Hiredis context for Pub / Sub. */ | |
124 | int pending_commands; /* Number of commands sent waiting for a reply. */ | |
125 | mstime_t cc_conn_time; /* cc connection time. */ | |
126 | mstime_t pc_conn_time; /* pc connection time. */ | |
127 | mstime_t pc_last_activity; /* Last time we received any message. */ | |
128 | mstime_t last_avail_time; /* Last time the instance replied to ping with | |
129 | a reply we consider valid. */ | |
130 | mstime_t last_pong_time; /* Last time the instance replied to ping, | |
131 | whatever the reply was. That's used to check | |
132 | if the link is idle and must be reconnected. */ | |
133 | mstime_t last_pub_time; /* Last time we sent hello via Pub/Sub. */ | |
134 | mstime_t last_hello_time; /* Only used if SRI_SENTINEL is set. Last time | |
135 | we received an hello from this Sentinel | |
136 | via Pub/Sub. */ | |
137 | mstime_t last_master_down_reply_time; /* Time of last reply to | |
138 | SENTINEL is-master-down command. */ | |
139 | mstime_t s_down_since_time; /* Subjectively down since time. */ | |
140 | mstime_t o_down_since_time; /* Objectively down since time. */ | |
141 | mstime_t down_after_period; /* Consider it down after that period. */ | |
142 | mstime_t info_refresh; /* Time at which we received INFO output from it. */ | |
143 | ||
144 | /* Master specific. */ | |
145 | dict *sentinels; /* Other sentinels monitoring the same master. */ | |
146 | dict *slaves; /* Slaves for this master instance. */ | |
147 | int quorum; /* Number of sentinels that need to agree on failure. */ | |
148 | int parallel_syncs; /* How many slaves to reconfigure at same time. */ | |
149 | ||
150 | /* Slave specific. */ | |
151 | mstime_t master_link_down_time; /* Slave replication link down time. */ | |
152 | int slave_priority; /* Slave priority according to its INFO output. */ | |
153 | mstime_t slave_reconf_sent_time; /* Time at which we sent SLAVE OF <new> */ | |
154 | struct sentinelRedisInstance *master; /* Master instance if SRI_SLAVE is set. */ | |
155 | char *slave_master_host; /* Master host as reported by INFO */ | |
156 | int slave_master_port; /* Master port as reported by INFO */ | |
157 | int slave_master_link_status; /* Master link status as reported by INFO */ | |
158 | /* Failover */ | |
159 | char *leader; /* If this is a master instance, this is the runid of | |
160 | the Sentinel that should perform the failover. If | |
161 | this is a Sentinel, this is the runid of the Sentinel | |
162 | that this other Sentinel is voting as leader. | |
163 | This field is valid only if SRI_MASTER_DOWN is | |
164 | set on the Sentinel instance. */ | |
165 | int failover_state; /* See SENTINEL_FAILOVER_STATE_* defines. */ | |
166 | mstime_t failover_state_change_time; | |
167 | mstime_t failover_start_time; /* When to start to failover if leader. */ | |
168 | mstime_t failover_timeout; /* Max time to refresh failover state. */ | |
169 | struct sentinelRedisInstance *promoted_slave; /* Promoted slave instance. */ | |
170 | /* Scripts executed to notify admin or reconfigure clients: when they | |
171 | * are set to NULL no script is executed. */ | |
172 | char *notify_script; | |
173 | char *client_reconfig_script; | |
174 | } sentinelRedisInstance; | |
175 | ||
176 | /* Main state. */ | |
177 | struct sentinelState { | |
178 | dict *masters; /* Dictionary of master sentinelRedisInstances. | |
179 | Key is the instance name, value is the | |
180 | sentinelRedisInstance structure pointer. */ | |
181 | int tilt; /* Are we in TILT mode? */ | |
182 | mstime_t tilt_start_time; /* When TITL started. */ | |
183 | mstime_t previous_time; /* Time last time we ran the time handler. */ | |
184 | } sentinel; | |
185 | ||
186 | /* ======================= hiredis ae.c adapters ============================= | |
187 | * Note: this implementation is taken from hiredis/adapters/ae.h, however | |
188 | * we have our modified copy for Sentinel in order to use our allocator | |
189 | * and to have full control over how the adapter works. */ | |
190 | ||
191 | typedef struct redisAeEvents { | |
192 | redisAsyncContext *context; | |
193 | aeEventLoop *loop; | |
194 | int fd; | |
195 | int reading, writing; | |
196 | } redisAeEvents; | |
197 | ||
198 | static void redisAeReadEvent(aeEventLoop *el, int fd, void *privdata, int mask) { | |
199 | ((void)el); ((void)fd); ((void)mask); | |
200 | ||
201 | redisAeEvents *e = (redisAeEvents*)privdata; | |
202 | redisAsyncHandleRead(e->context); | |
203 | } | |
204 | ||
205 | static void redisAeWriteEvent(aeEventLoop *el, int fd, void *privdata, int mask) { | |
206 | ((void)el); ((void)fd); ((void)mask); | |
207 | ||
208 | redisAeEvents *e = (redisAeEvents*)privdata; | |
209 | redisAsyncHandleWrite(e->context); | |
210 | } | |
211 | ||
212 | static void redisAeAddRead(void *privdata) { | |
213 | redisAeEvents *e = (redisAeEvents*)privdata; | |
214 | aeEventLoop *loop = e->loop; | |
215 | if (!e->reading) { | |
216 | e->reading = 1; | |
217 | aeCreateFileEvent(loop,e->fd,AE_READABLE,redisAeReadEvent,e); | |
218 | } | |
219 | } | |
220 | ||
221 | static void redisAeDelRead(void *privdata) { | |
222 | redisAeEvents *e = (redisAeEvents*)privdata; | |
223 | aeEventLoop *loop = e->loop; | |
224 | if (e->reading) { | |
225 | e->reading = 0; | |
226 | aeDeleteFileEvent(loop,e->fd,AE_READABLE); | |
227 | } | |
228 | } | |
229 | ||
230 | static void redisAeAddWrite(void *privdata) { | |
231 | redisAeEvents *e = (redisAeEvents*)privdata; | |
232 | aeEventLoop *loop = e->loop; | |
233 | if (!e->writing) { | |
234 | e->writing = 1; | |
235 | aeCreateFileEvent(loop,e->fd,AE_WRITABLE,redisAeWriteEvent,e); | |
236 | } | |
237 | } | |
238 | ||
239 | static void redisAeDelWrite(void *privdata) { | |
240 | redisAeEvents *e = (redisAeEvents*)privdata; | |
241 | aeEventLoop *loop = e->loop; | |
242 | if (e->writing) { | |
243 | e->writing = 0; | |
244 | aeDeleteFileEvent(loop,e->fd,AE_WRITABLE); | |
245 | } | |
246 | } | |
247 | ||
248 | static void redisAeCleanup(void *privdata) { | |
249 | redisAeEvents *e = (redisAeEvents*)privdata; | |
250 | redisAeDelRead(privdata); | |
251 | redisAeDelWrite(privdata); | |
252 | zfree(e); | |
253 | } | |
254 | ||
255 | static int redisAeAttach(aeEventLoop *loop, redisAsyncContext *ac) { | |
256 | redisContext *c = &(ac->c); | |
257 | redisAeEvents *e; | |
258 | ||
259 | /* Nothing should be attached when something is already attached */ | |
260 | if (ac->ev.data != NULL) | |
261 | return REDIS_ERR; | |
262 | ||
263 | /* Create container for context and r/w events */ | |
264 | e = (redisAeEvents*)zmalloc(sizeof(*e)); | |
265 | e->context = ac; | |
266 | e->loop = loop; | |
267 | e->fd = c->fd; | |
268 | e->reading = e->writing = 0; | |
269 | ||
270 | /* Register functions to start/stop listening for events */ | |
271 | ac->ev.addRead = redisAeAddRead; | |
272 | ac->ev.delRead = redisAeDelRead; | |
273 | ac->ev.addWrite = redisAeAddWrite; | |
274 | ac->ev.delWrite = redisAeDelWrite; | |
275 | ac->ev.cleanup = redisAeCleanup; | |
276 | ac->ev.data = e; | |
277 | ||
278 | return REDIS_OK; | |
279 | } | |
280 | ||
281 | /* ============================= Prototypes ================================= */ | |
282 | ||
283 | void sentinelLinkEstablishedCallback(const redisAsyncContext *c, int status); | |
284 | void sentinelDisconnectCallback(const redisAsyncContext *c, int status); | |
285 | void sentinelReceiveHelloMessages(redisAsyncContext *c, void *reply, void *privdata); | |
286 | sentinelRedisInstance *sentinelGetMasterByName(char *name); | |
287 | char *sentinelGetSubjectiveLeader(sentinelRedisInstance *master); | |
288 | char *sentinelGetObjectiveLeader(sentinelRedisInstance *master); | |
289 | int yesnotoi(char *s); | |
290 | void sentinelDisconnectInstanceFromContext(const redisAsyncContext *c); | |
e47236d8 | 291 | void sentinelKillLink(sentinelRedisInstance *ri, redisAsyncContext *c); |
120ba392 | 292 | const char *sentinelRedisInstanceTypeStr(sentinelRedisInstance *ri); |
293 | ||
294 | /* ========================= Dictionary types =============================== */ | |
295 | ||
296 | unsigned int dictSdsHash(const void *key); | |
297 | int dictSdsKeyCompare(void *privdata, const void *key1, const void *key2); | |
298 | void releaseSentinelRedisInstance(sentinelRedisInstance *ri); | |
299 | ||
300 | void dictInstancesValDestructor (void *privdata, void *obj) { | |
301 | releaseSentinelRedisInstance(obj); | |
302 | } | |
303 | ||
304 | /* Instance name (sds) -> instance (sentinelRedisInstance pointer) | |
305 | * | |
306 | * also used for: sentinelRedisInstance->sentinels dictionary that maps | |
307 | * sentinels ip:port to last seen time in Pub/Sub hello message. */ | |
308 | dictType instancesDictType = { | |
309 | dictSdsHash, /* hash function */ | |
310 | NULL, /* key dup */ | |
311 | NULL, /* val dup */ | |
312 | dictSdsKeyCompare, /* key compare */ | |
313 | NULL, /* key destructor */ | |
314 | dictInstancesValDestructor /* val destructor */ | |
315 | }; | |
316 | ||
317 | /* Instance runid (sds) -> votes (long casted to void*) | |
318 | * | |
319 | * This is useful into sentinelGetObjectiveLeader() function in order to | |
320 | * count the votes and understand who is the leader. */ | |
321 | dictType leaderVotesDictType = { | |
322 | dictSdsHash, /* hash function */ | |
323 | NULL, /* key dup */ | |
324 | NULL, /* val dup */ | |
325 | dictSdsKeyCompare, /* key compare */ | |
326 | NULL, /* key destructor */ | |
327 | NULL /* val destructor */ | |
328 | }; | |
329 | ||
330 | /* =========================== Initialization =============================== */ | |
331 | ||
332 | void sentinelCommand(redisClient *c); | |
333 | ||
334 | struct redisCommand sentinelcmds[] = { | |
335 | {"ping",pingCommand,1,"",0,NULL,0,0,0,0,0}, | |
336 | {"sentinel",sentinelCommand,-2,"",0,NULL,0,0,0,0,0}, | |
337 | {"subscribe",subscribeCommand,-2,"",0,NULL,0,0,0,0,0}, | |
338 | {"unsubscribe",unsubscribeCommand,-1,"",0,NULL,0,0,0,0,0}, | |
339 | {"psubscribe",psubscribeCommand,-2,"",0,NULL,0,0,0,0,0}, | |
340 | {"punsubscribe",punsubscribeCommand,-1,"",0,NULL,0,0,0,0,0} | |
341 | }; | |
342 | ||
343 | /* This function overwrites a few normal Redis config default with Sentinel | |
344 | * specific defaults. */ | |
345 | void initSentinelConfig(void) { | |
346 | server.port = REDIS_SENTINEL_PORT; | |
347 | } | |
348 | ||
349 | /* Perform the Sentinel mode initialization. */ | |
350 | void initSentinel(void) { | |
351 | int j; | |
352 | ||
353 | /* Remove usual Redis commands from the command table, then just add | |
354 | * the SENTINEL command. */ | |
355 | dictEmpty(server.commands); | |
356 | for (j = 0; j < sizeof(sentinelcmds)/sizeof(sentinelcmds[0]); j++) { | |
357 | int retval; | |
358 | struct redisCommand *cmd = sentinelcmds+j; | |
359 | ||
360 | retval = dictAdd(server.commands, sdsnew(cmd->name), cmd); | |
361 | redisAssert(retval == DICT_OK); | |
362 | } | |
363 | ||
364 | /* Initialize various data structures. */ | |
365 | sentinel.masters = dictCreate(&instancesDictType,NULL); | |
366 | sentinel.tilt = 0; | |
367 | sentinel.tilt_start_time = mstime(); | |
368 | sentinel.previous_time = mstime(); | |
369 | } | |
370 | ||
371 | /* ============================== sentinelAddr ============================== */ | |
372 | ||
373 | /* Create a sentinelAddr object and return it on success. | |
374 | * On error NULL is returned and errno is set to: | |
375 | * ENOENT: Can't resolve the hostname. | |
376 | * EINVAL: Invalid port number. | |
377 | */ | |
378 | sentinelAddr *createSentinelAddr(char *hostname, int port) { | |
379 | char buf[32]; | |
380 | sentinelAddr *sa; | |
381 | ||
382 | if (port <= 0 || port > 65535) { | |
383 | errno = EINVAL; | |
384 | return NULL; | |
385 | } | |
386 | if (anetResolve(NULL,hostname,buf) == ANET_ERR) { | |
387 | errno = ENOENT; | |
388 | return NULL; | |
389 | } | |
390 | sa = zmalloc(sizeof(*sa)); | |
391 | sa->ip = sdsnew(buf); | |
392 | sa->port = port; | |
393 | return sa; | |
394 | } | |
395 | ||
396 | /* Free a Sentinel address. Can't fail. */ | |
397 | void releaseSentinelAddr(sentinelAddr *sa) { | |
398 | sdsfree(sa->ip); | |
399 | zfree(sa); | |
400 | } | |
401 | ||
402 | /* =========================== Events notification ========================== */ | |
403 | ||
404 | void sentinelCallNotificationScript(char *scriptpath, char *type, char *msg) { | |
405 | /* TODO: implement it. */ | |
406 | } | |
407 | ||
408 | /* Send an event to log, pub/sub, user notification script. | |
409 | * | |
410 | * 'level' is the log level for logging. Only REDIS_WARNING events will trigger | |
411 | * the execution of the user notification script. | |
412 | * | |
413 | * 'type' is the message type, also used as a pub/sub channel name. | |
414 | * | |
415 | * 'ri', is the redis instance target of this event if applicable, and is | |
416 | * used to obtain the path of the notification script to execute. | |
417 | * | |
418 | * The remaining arguments are printf-alike. | |
419 | * If the format specifier starts with the two characters "%@" then ri is | |
420 | * not NULL, and the message is prefixed with an instance identifier in the | |
421 | * following format: | |
422 | * | |
423 | * <instance type> <instance name> <ip> <port> | |
424 | * | |
425 | * If the instance type is not master, than the additional string is | |
426 | * added to specify the originating master: | |
427 | * | |
428 | * @ <master name> <master ip> <master port> | |
429 | * | |
430 | * Any other specifier after "%@" is processed by printf itself. | |
431 | */ | |
432 | void sentinelEvent(int level, char *type, sentinelRedisInstance *ri, | |
433 | const char *fmt, ...) { | |
434 | va_list ap; | |
435 | char msg[REDIS_MAX_LOGMSG_LEN]; | |
436 | robj *channel, *payload; | |
437 | ||
438 | /* Handle %@ */ | |
439 | if (fmt[0] == '%' && fmt[1] == '@') { | |
440 | sentinelRedisInstance *master = (ri->flags & SRI_MASTER) ? | |
441 | NULL : ri->master; | |
442 | ||
443 | if (master) { | |
444 | snprintf(msg, sizeof(msg), "%s %s %s %d @ %s %s %d", | |
445 | sentinelRedisInstanceTypeStr(ri), | |
446 | ri->name, ri->addr->ip, ri->addr->port, | |
447 | master->name, master->addr->ip, master->addr->port); | |
448 | } else { | |
449 | snprintf(msg, sizeof(msg), "%s %s %s %d", | |
450 | sentinelRedisInstanceTypeStr(ri), | |
451 | ri->name, ri->addr->ip, ri->addr->port); | |
452 | } | |
453 | fmt += 2; | |
454 | } else { | |
455 | msg[0] = '\0'; | |
456 | } | |
457 | ||
458 | /* Use vsprintf for the rest of the formatting if any. */ | |
459 | if (fmt[0] != '\0') { | |
460 | va_start(ap, fmt); | |
461 | vsnprintf(msg+strlen(msg), sizeof(msg)-strlen(msg), fmt, ap); | |
462 | va_end(ap); | |
463 | } | |
464 | ||
465 | /* Log the message if the log level allows it to be logged. */ | |
466 | if (level >= server.verbosity) | |
467 | redisLog(level,"%s %s",type,msg); | |
468 | ||
469 | /* Publish the message via Pub/Sub if it's not a debugging one. */ | |
470 | if (level != REDIS_DEBUG) { | |
471 | channel = createStringObject(type,strlen(type)); | |
472 | payload = createStringObject(msg,strlen(msg)); | |
473 | pubsubPublishMessage(channel,payload); | |
474 | decrRefCount(channel); | |
475 | decrRefCount(payload); | |
476 | } | |
477 | ||
478 | /* Call the notification script if applicable. */ | |
479 | if (level == REDIS_WARNING && ri != NULL) { | |
480 | sentinelRedisInstance *master = (ri->flags & SRI_MASTER) ? | |
481 | ri : ri->master; | |
482 | if (master->notify_script) { | |
483 | sentinelCallNotificationScript(master->notify_script,type,msg); | |
484 | } | |
485 | } | |
486 | } | |
487 | ||
488 | /* ========================== sentinelRedisInstance ========================= */ | |
489 | ||
490 | /* Create a redis instance, the following fields must be populated by the | |
491 | * caller if needed: | |
492 | * runid: set to NULL but will be populated once INFO output is received. | |
493 | * info_refresh: is set to 0 to mean that we never received INFO so far. | |
494 | * | |
495 | * If SRI_MASTER is set into initial flags the instance is added to | |
496 | * sentinel.masters table. | |
497 | * | |
498 | * if SRI_SLAVE or SRI_SENTINEL is set then 'master' must be not NULL and the | |
499 | * instance is added into master->slaves or master->sentinels table. | |
500 | * | |
501 | * If the instance is a slave or sentinel, the name parameter is ignored and | |
502 | * is created automatically as hostname:port. | |
503 | * | |
504 | * The function fails if hostname can't be resolved or port is out of range. | |
505 | * When this happens NULL is returned and errno is set accordingly to the | |
506 | * createSentinelAddr() function. | |
507 | * | |
508 | * The function may also fail and return NULL with errno set to EBUSY if | |
509 | * a master or slave with the same name already exists. */ | |
510 | sentinelRedisInstance *createSentinelRedisInstance(char *name, int flags, char *hostname, int port, int quorum, sentinelRedisInstance *master) { | |
511 | sentinelRedisInstance *ri; | |
512 | sentinelAddr *addr; | |
513 | dict *table; | |
514 | char slavename[128], *sdsname; | |
515 | ||
516 | redisAssert(flags & (SRI_MASTER|SRI_SLAVE|SRI_SENTINEL)); | |
517 | redisAssert((flags & SRI_MASTER) || master != NULL); | |
518 | ||
519 | /* Check address validity. */ | |
520 | addr = createSentinelAddr(hostname,port); | |
521 | if (addr == NULL) return NULL; | |
522 | ||
523 | /* For slaves and sentinel we use ip:port as name. */ | |
524 | if (flags & (SRI_SLAVE|SRI_SENTINEL)) { | |
525 | snprintf(slavename,sizeof(slavename),"%s:%d",hostname,port); | |
526 | name = slavename; | |
527 | } | |
528 | ||
529 | /* Make sure the entry is not duplicated. This may happen when the same | |
530 | * name for a master is used multiple times inside the configuration or | |
531 | * if we try to add multiple times a slave or sentinel with same ip/port | |
532 | * to a master. */ | |
533 | if (flags & SRI_MASTER) table = sentinel.masters; | |
534 | else if (flags & SRI_SLAVE) table = master->slaves; | |
535 | else if (flags & SRI_SENTINEL) table = master->sentinels; | |
536 | sdsname = sdsnew(name); | |
537 | if (dictFind(table,sdsname)) { | |
538 | sdsfree(sdsname); | |
539 | errno = EBUSY; | |
540 | return NULL; | |
541 | } | |
542 | ||
543 | /* Create the instance object. */ | |
544 | ri = zmalloc(sizeof(*ri)); | |
545 | /* Note that all the instances are started in the disconnected state, | |
546 | * the event loop will take care of connecting them. */ | |
547 | ri->flags = flags | SRI_DISCONNECTED; | |
548 | ri->name = sdsname; | |
549 | ri->runid = NULL; | |
550 | ri->addr = addr; | |
551 | ri->cc = NULL; | |
552 | ri->pc = NULL; | |
553 | ri->pending_commands = 0; | |
554 | ri->cc_conn_time = 0; | |
555 | ri->pc_conn_time = 0; | |
556 | ri->pc_last_activity = 0; | |
557 | ri->last_avail_time = mstime(); | |
558 | ri->last_pong_time = mstime(); | |
559 | ri->last_pub_time = mstime(); | |
560 | ri->last_hello_time = mstime(); | |
561 | ri->last_master_down_reply_time = mstime(); | |
562 | ri->s_down_since_time = 0; | |
563 | ri->o_down_since_time = 0; | |
564 | ri->down_after_period = master ? master->down_after_period : | |
565 | SENTINEL_DOWN_AFTER_PERIOD; | |
566 | ri->master_link_down_time = 0; | |
567 | ri->slave_priority = SENTINEL_DEFAULT_SLAVE_PRIORITY; | |
568 | ri->slave_reconf_sent_time = 0; | |
569 | ri->slave_master_host = NULL; | |
570 | ri->slave_master_port = 0; | |
571 | ri->slave_master_link_status = SENTINEL_MASTER_LINK_STATUS_DOWN; | |
572 | ri->sentinels = dictCreate(&instancesDictType,NULL); | |
573 | ri->quorum = quorum; | |
574 | ri->parallel_syncs = SENTINEL_DEFAULT_PARALLEL_SYNCS; | |
575 | ri->master = master; | |
576 | ri->slaves = dictCreate(&instancesDictType,NULL); | |
577 | ri->info_refresh = 0; | |
578 | ||
579 | /* Failover state. */ | |
580 | ri->leader = NULL; | |
581 | ri->failover_state = SENTINEL_FAILOVER_STATE_NONE; | |
582 | ri->failover_state_change_time = 0; | |
583 | ri->failover_start_time = 0; | |
584 | ri->failover_timeout = SENTINEL_DEFAULT_FAILOVER_TIMEOUT; | |
585 | ri->promoted_slave = NULL; | |
586 | ri->notify_script = NULL; | |
587 | ri->client_reconfig_script = NULL; | |
588 | ||
589 | /* Add into the right table. */ | |
590 | dictAdd(table, ri->name, ri); | |
591 | return ri; | |
592 | } | |
593 | ||
594 | /* Release this instance and all its slaves, sentinels, hiredis connections. | |
595 | * This function also takes care of unlinking the instance from the main | |
596 | * masters table (if it is a master) or from its master sentinels/slaves table | |
597 | * if it is a slave or sentinel. */ | |
598 | void releaseSentinelRedisInstance(sentinelRedisInstance *ri) { | |
599 | /* Release all its slaves or sentinels if any. */ | |
600 | dictRelease(ri->sentinels); | |
601 | dictRelease(ri->slaves); | |
602 | ||
e47236d8 | 603 | /* Release hiredis connections. */ |
604 | if (ri->cc) sentinelKillLink(ri,ri->cc); | |
605 | if (ri->pc) sentinelKillLink(ri,ri->pc); | |
120ba392 | 606 | |
607 | /* Free other resources. */ | |
608 | sdsfree(ri->name); | |
609 | sdsfree(ri->runid); | |
610 | sdsfree(ri->notify_script); | |
611 | sdsfree(ri->client_reconfig_script); | |
612 | sdsfree(ri->slave_master_host); | |
613 | sdsfree(ri->leader); | |
614 | releaseSentinelAddr(ri->addr); | |
615 | ||
616 | /* Clear state into the master if needed. */ | |
617 | if ((ri->flags & SRI_SLAVE) && (ri->flags & SRI_PROMOTED) && ri->master) | |
618 | ri->master->promoted_slave = NULL; | |
619 | ||
620 | zfree(ri); | |
621 | } | |
622 | ||
623 | /* Lookup a slave in a master Redis instance, by ip and port. */ | |
624 | sentinelRedisInstance *sentinelRedisInstanceLookupSlave( | |
625 | sentinelRedisInstance *ri, char *ip, int port) | |
626 | { | |
627 | sds key; | |
628 | sentinelRedisInstance *slave; | |
629 | ||
630 | redisAssert(ri->flags & SRI_MASTER); | |
631 | key = sdscatprintf(sdsempty(),"%s:%d",ip,port); | |
632 | slave = dictFetchValue(ri->slaves,key); | |
633 | sdsfree(key); | |
634 | return slave; | |
635 | } | |
636 | ||
637 | /* Return the name of the type of the instance as a string. */ | |
638 | const char *sentinelRedisInstanceTypeStr(sentinelRedisInstance *ri) { | |
639 | if (ri->flags & SRI_MASTER) return "master"; | |
640 | else if (ri->flags & SRI_SLAVE) return "slave"; | |
641 | else if (ri->flags & SRI_SENTINEL) return "sentinel"; | |
642 | else return "unknown"; | |
643 | } | |
644 | ||
645 | /* This function removes all the instances found in the dictionary of instances | |
646 | * 'd', having either: | |
647 | * | |
648 | * 1) The same ip/port as specified. | |
649 | * 2) The same runid. | |
650 | * | |
651 | * "1" and "2" don't need to verify at the same time, just one is enough. | |
652 | * If "runid" is NULL it is not checked. | |
653 | * Similarly if "ip" is NULL it is not checked. | |
654 | * | |
655 | * This function is useful because every time we add a new Sentinel into | |
656 | * a master's Sentinels dictionary, we want to be very sure about not | |
657 | * having duplicated instances for any reason. This is so important because | |
658 | * we use those other sentinels in order to run our quorum protocol to | |
659 | * understand if it's time to proceeed with the fail over. | |
660 | * | |
661 | * Making sure no duplication is possible we greately improve the robustness | |
662 | * of the quorum (otherwise we may end counting the same instance multiple | |
663 | * times for some reason). | |
664 | * | |
665 | * The function returns the number of Sentinels removed. */ | |
666 | int removeMatchingSentinelsFromMaster(sentinelRedisInstance *master, char *ip, int port, char *runid) { | |
667 | dictIterator *di; | |
668 | dictEntry *de; | |
669 | int removed = 0; | |
670 | ||
671 | di = dictGetSafeIterator(master->sentinels); | |
672 | while((de = dictNext(di)) != NULL) { | |
673 | sentinelRedisInstance *ri = dictGetVal(de); | |
674 | ||
675 | if ((ri->runid && runid && strcmp(ri->runid,runid) == 0) || | |
676 | (ip && strcmp(ri->addr->ip,ip) == 0 && port == ri->addr->port)) | |
677 | { | |
678 | dictDelete(master->sentinels,ri->name); | |
679 | removed++; | |
680 | } | |
681 | } | |
682 | dictReleaseIterator(di); | |
683 | return removed; | |
684 | } | |
685 | ||
686 | /* Search an instance with the same runid, ip and port into a dictionary | |
687 | * of instances. Return NULL if not found, otherwise return the instance | |
688 | * pointer. | |
689 | * | |
690 | * runid or ip can be NULL. In such a case the search is performed only | |
691 | * by the non-NULL field. */ | |
692 | sentinelRedisInstance *getSentinelRedisInstanceByAddrAndRunID(dict *instances, char *ip, int port, char *runid) { | |
693 | dictIterator *di; | |
694 | dictEntry *de; | |
695 | sentinelRedisInstance *instance = NULL; | |
696 | ||
697 | redisAssert(ip || runid); /* User must pass at least one search param. */ | |
698 | di = dictGetIterator(instances); | |
699 | while((de = dictNext(di)) != NULL) { | |
700 | sentinelRedisInstance *ri = dictGetVal(de); | |
701 | ||
702 | if (runid && !ri->runid) continue; | |
703 | if ((runid == NULL || strcmp(ri->runid, runid) == 0) && | |
704 | (ip == NULL || (strcmp(ri->addr->ip, ip) == 0 && | |
705 | ri->addr->port == port))) | |
706 | { | |
707 | instance = ri; | |
708 | break; | |
709 | } | |
710 | } | |
711 | dictReleaseIterator(di); | |
712 | return instance; | |
713 | } | |
714 | ||
715 | /* Simple master lookup by name */ | |
716 | sentinelRedisInstance *sentinelGetMasterByName(char *name) { | |
717 | sentinelRedisInstance *ri; | |
718 | sds sdsname = sdsnew(name); | |
719 | ||
720 | ri = dictFetchValue(sentinel.masters,sdsname); | |
721 | sdsfree(sdsname); | |
722 | return ri; | |
723 | } | |
724 | ||
725 | /* Add the specified flags to all the instances in the specified dictionary. */ | |
726 | void sentinelAddFlagsToDictOfRedisInstances(dict *instances, int flags) { | |
727 | dictIterator *di; | |
728 | dictEntry *de; | |
729 | ||
730 | di = dictGetIterator(instances); | |
731 | while((de = dictNext(di)) != NULL) { | |
732 | sentinelRedisInstance *ri = dictGetVal(de); | |
733 | ri->flags |= flags; | |
734 | } | |
735 | dictReleaseIterator(di); | |
736 | } | |
737 | ||
738 | /* Remove the specified flags to all the instances in the specified | |
739 | * dictionary. */ | |
740 | void sentinelDelFlagsToDictOfRedisInstances(dict *instances, int flags) { | |
741 | dictIterator *di; | |
742 | dictEntry *de; | |
743 | ||
744 | di = dictGetIterator(instances); | |
745 | while((de = dictNext(di)) != NULL) { | |
746 | sentinelRedisInstance *ri = dictGetVal(de); | |
747 | ri->flags &= ~flags; | |
748 | } | |
749 | dictReleaseIterator(di); | |
750 | } | |
751 | ||
752 | /* Reset the state of a monitored master: | |
753 | * 1) Remove all slaves. | |
754 | * 2) Remove all sentinels. | |
755 | * 3) Remove most of the flags resulting from runtime operations. | |
756 | * 4) Reset timers to their default value. | |
757 | * 5) In the process of doing this undo the failover if in progress. | |
758 | * 6) Disconnect the connections with the master (will reconnect automatically). | |
759 | */ | |
e47236d8 | 760 | void sentinelResetMaster(sentinelRedisInstance *ri, int flags) { |
120ba392 | 761 | redisAssert(ri->flags & SRI_MASTER); |
762 | dictRelease(ri->slaves); | |
763 | dictRelease(ri->sentinels); | |
764 | ri->slaves = dictCreate(&instancesDictType,NULL); | |
765 | ri->sentinels = dictCreate(&instancesDictType,NULL); | |
e47236d8 | 766 | if (ri->cc) sentinelKillLink(ri,ri->cc); |
767 | if (ri->pc) sentinelKillLink(ri,ri->pc); | |
120ba392 | 768 | ri->flags &= SRI_MASTER|SRI_CAN_FAILOVER|SRI_DISCONNECTED; |
769 | if (ri->leader) { | |
770 | sdsfree(ri->leader); | |
771 | ri->leader = NULL; | |
772 | } | |
773 | ri->failover_state = SENTINEL_FAILOVER_STATE_NONE; | |
774 | ri->failover_state_change_time = 0; | |
775 | ri->failover_start_time = 0; | |
776 | ri->promoted_slave = NULL; | |
e47236d8 | 777 | sdsfree(ri->runid); |
778 | sdsfree(ri->slave_master_host); | |
779 | ri->runid = NULL; | |
780 | ri->slave_master_host = NULL; | |
781 | if (flags & SENTINEL_GENERATE_EVENT) | |
782 | sentinelEvent(REDIS_WARNING,"+reset-master",ri,"%@"); | |
120ba392 | 783 | } |
784 | ||
785 | /* Call sentinelResetMaster() on every master with a name matching the specified | |
786 | * pattern. */ | |
e47236d8 | 787 | int sentinelResetMastersByPattern(char *pattern, int flags) { |
120ba392 | 788 | dictIterator *di; |
789 | dictEntry *de; | |
790 | int reset = 0; | |
791 | ||
792 | di = dictGetIterator(sentinel.masters); | |
793 | while((de = dictNext(di)) != NULL) { | |
794 | sentinelRedisInstance *ri = dictGetVal(de); | |
795 | ||
796 | if (ri->name) { | |
797 | if (stringmatch(pattern,ri->name,0)) { | |
e47236d8 | 798 | sentinelResetMaster(ri,flags); |
120ba392 | 799 | reset++; |
800 | } | |
801 | } | |
802 | } | |
803 | dictReleaseIterator(di); | |
804 | return reset; | |
805 | } | |
806 | ||
e47236d8 | 807 | /* Reset the specified master with sentinelResetMaster(), and also change |
808 | * the ip:port address, but take the name of the instance unmodified. | |
809 | * | |
810 | * This is used to handle the +switch-master and +redirect-to-master events. | |
811 | * | |
812 | * The function returns REDIS_ERR if the address can't be resolved for some | |
813 | * reason. Otherwise REDIS_OK is returned. | |
814 | * | |
815 | * TODO: make this reset so that original sentinels are re-added with | |
816 | * same ip / port / runid. | |
817 | */ | |
818 | ||
819 | int sentinelResetMasterAndChangeAddress(sentinelRedisInstance *master, char *ip, int port) { | |
820 | sentinelAddr *oldaddr, *newaddr; | |
821 | ||
822 | newaddr = createSentinelAddr(ip,port); | |
823 | if (newaddr == NULL) return REDIS_ERR; | |
824 | sentinelResetMaster(master,SENTINEL_NO_FLAGS); | |
825 | oldaddr = master->addr; | |
826 | master->addr = newaddr; | |
827 | /* Release the old address at the end so we are safe even if the function | |
828 | * gets the master->addr->ip and master->addr->port as arguments. */ | |
829 | releaseSentinelAddr(oldaddr); | |
830 | return REDIS_OK; | |
831 | } | |
832 | ||
120ba392 | 833 | /* ============================ Config handling ============================= */ |
834 | char *sentinelHandleConfiguration(char **argv, int argc) { | |
835 | sentinelRedisInstance *ri; | |
836 | ||
837 | if (!strcasecmp(argv[0],"monitor") && argc == 5) { | |
838 | /* monitor <name> <host> <port> <quorum> */ | |
839 | int quorum = atoi(argv[4]); | |
840 | ||
841 | if (quorum <= 0) return "Quorum must be 1 or greater."; | |
842 | if (createSentinelRedisInstance(argv[1],SRI_MASTER,argv[2], | |
843 | atoi(argv[3]),quorum,NULL) == NULL) | |
844 | { | |
845 | switch(errno) { | |
846 | case EBUSY: return "Duplicated master name."; | |
847 | case ENOENT: return "Can't resolve master instance hostname."; | |
848 | case EINVAL: return "Invalid port number"; | |
849 | } | |
850 | } | |
851 | } else if (!strcasecmp(argv[0],"down-after-milliseconds") && argc == 3) { | |
852 | /* down-after-milliseconds <name> <milliseconds> */ | |
853 | ri = sentinelGetMasterByName(argv[1]); | |
854 | if (!ri) return "No such master with specified name."; | |
855 | ri->down_after_period = atoi(argv[2]); | |
856 | if (ri->down_after_period <= 0) | |
857 | return "negative or zero time parameter."; | |
858 | } else if (!strcasecmp(argv[0],"failover-timeout") && argc == 3) { | |
859 | /* failover-timeout <name> <milliseconds> */ | |
860 | ri = sentinelGetMasterByName(argv[1]); | |
861 | if (!ri) return "No such master with specified name."; | |
862 | ri->failover_timeout = atoi(argv[2]); | |
863 | if (ri->failover_timeout <= 0) | |
864 | return "negative or zero time parameter."; | |
865 | } else if (!strcasecmp(argv[0],"can-failover") && argc == 3) { | |
866 | /* can-failover <name> <yes/no> */ | |
867 | int yesno = yesnotoi(argv[2]); | |
868 | ||
869 | ri = sentinelGetMasterByName(argv[1]); | |
870 | if (!ri) return "No such master with specified name."; | |
871 | if (yesno == -1) return "Argument must be either yes or no."; | |
872 | if (yesno) | |
873 | ri->flags |= SRI_CAN_FAILOVER; | |
874 | else | |
875 | ri->flags &= ~SRI_CAN_FAILOVER; | |
876 | } else if (!strcasecmp(argv[0],"parallel-syncs") && argc == 3) { | |
877 | /* parallel-syncs <name> <milliseconds> */ | |
878 | ri = sentinelGetMasterByName(argv[1]); | |
879 | if (!ri) return "No such master with specified name."; | |
880 | ri->parallel_syncs = atoi(argv[2]); | |
881 | } else { | |
882 | return "Unrecognized sentinel configuration statement."; | |
883 | } | |
884 | return NULL; | |
885 | } | |
886 | ||
887 | /* ====================== hiredis connection handling ======================= */ | |
888 | ||
e47236d8 | 889 | /* Completely disconnect an hiredis link from an instance. */ |
890 | void sentinelKillLink(sentinelRedisInstance *ri, redisAsyncContext *c) { | |
891 | if (ri->cc == c) ri->cc = NULL; | |
892 | if (ri->pc == c) ri->pc = NULL; | |
893 | c->data = NULL; | |
894 | ri->flags |= SRI_DISCONNECTED; | |
895 | redisAsyncFree(c); | |
896 | } | |
897 | ||
120ba392 | 898 | /* This function takes an hiredis context that is in an error condition |
899 | * and make sure to mark the instance as disconnected performing the | |
900 | * cleanup needed. | |
901 | * | |
902 | * Note: we don't free the hiredis context as hiredis will do it for us | |
903 | * for async conenctions. */ | |
904 | void sentinelDisconnectInstanceFromContext(const redisAsyncContext *c) { | |
905 | sentinelRedisInstance *ri = c->data; | |
e01a415d | 906 | int pubsub; |
120ba392 | 907 | |
e01a415d | 908 | if (ri == NULL) return; /* The instance no longer exists. */ |
909 | ||
910 | pubsub = (ri->pc == c); | |
120ba392 | 911 | sentinelEvent(REDIS_DEBUG, pubsub ? "-pubsub-link" : "-cmd-link", ri, |
912 | "%@ #%s", c->errstr); | |
913 | if (pubsub) | |
914 | ri->pc = NULL; | |
915 | else | |
916 | ri->cc = NULL; | |
917 | ri->flags |= SRI_DISCONNECTED; | |
918 | } | |
919 | ||
920 | void sentinelLinkEstablishedCallback(const redisAsyncContext *c, int status) { | |
921 | if (status != REDIS_OK) { | |
922 | sentinelDisconnectInstanceFromContext(c); | |
923 | } else { | |
924 | sentinelRedisInstance *ri = c->data; | |
925 | int pubsub = (ri->pc == c); | |
926 | ||
927 | sentinelEvent(REDIS_DEBUG, pubsub ? "+pubsub-link" : "+cmd-link", ri, | |
928 | "%@"); | |
929 | } | |
930 | } | |
931 | ||
932 | void sentinelDisconnectCallback(const redisAsyncContext *c, int status) { | |
e47236d8 | 933 | printf("DISCONNECT CALLBACK CALLED: %p (%p)\n", (void*)c, (void*)c->data); |
120ba392 | 934 | sentinelDisconnectInstanceFromContext(c); |
935 | } | |
936 | ||
937 | /* Create the async connections for the specified instance if the instance | |
938 | * is disconnected. Note that the SRI_DISCONNECTED flag is set even if just | |
939 | * one of the two links (commands and pub/sub) is missing. */ | |
940 | void sentinelReconnectInstance(sentinelRedisInstance *ri) { | |
941 | if (!(ri->flags & SRI_DISCONNECTED)) return; | |
942 | ||
943 | /* Commands connection. */ | |
944 | if (ri->cc == NULL) { | |
945 | ri->cc = redisAsyncConnect(ri->addr->ip,ri->addr->port); | |
946 | if (ri->cc->err) { | |
947 | sentinelEvent(REDIS_DEBUG,"-cmd-link-reconnection",ri,"%@ #%s", | |
948 | ri->cc->errstr); | |
e47236d8 | 949 | sentinelKillLink(ri,ri->cc); |
120ba392 | 950 | } else { |
951 | ri->cc_conn_time = mstime(); | |
952 | ri->cc->data = ri; | |
953 | redisAeAttach(server.el,ri->cc); | |
954 | redisAsyncSetConnectCallback(ri->cc, | |
955 | sentinelLinkEstablishedCallback); | |
956 | redisAsyncSetDisconnectCallback(ri->cc, | |
957 | sentinelDisconnectCallback); | |
958 | } | |
959 | } | |
960 | /* Pub / Sub */ | |
961 | if ((ri->flags & SRI_MASTER) && ri->pc == NULL) { | |
962 | ri->pc = redisAsyncConnect(ri->addr->ip,ri->addr->port); | |
963 | if (ri->pc->err) { | |
964 | sentinelEvent(REDIS_DEBUG,"-pubsub-link-reconnection",ri,"%@ #%s", | |
965 | ri->pc->errstr); | |
e47236d8 | 966 | sentinelKillLink(ri,ri->pc); |
120ba392 | 967 | } else { |
968 | int retval; | |
969 | ||
970 | ri->pc_conn_time = mstime(); | |
971 | ri->pc->data = ri; | |
972 | redisAeAttach(server.el,ri->pc); | |
973 | redisAsyncSetConnectCallback(ri->pc, | |
974 | sentinelLinkEstablishedCallback); | |
975 | redisAsyncSetDisconnectCallback(ri->pc, | |
976 | sentinelDisconnectCallback); | |
977 | /* Now we subscribe to the Sentinels "Hello" channel. */ | |
978 | retval = redisAsyncCommand(ri->pc, | |
979 | sentinelReceiveHelloMessages, NULL, "SUBSCRIBE %s", | |
980 | SENTINEL_HELLO_CHANNEL); | |
981 | if (retval != REDIS_OK) { | |
982 | /* If we can't subscribe, the Pub/Sub connection is useless | |
983 | * and we can simply disconnect it and try again. */ | |
e47236d8 | 984 | sentinelKillLink(ri,ri->pc); |
120ba392 | 985 | return; |
986 | } | |
987 | } | |
988 | } | |
989 | /* Clear the DISCONNECTED flags only if we have both the connections | |
990 | * (or just the commands connection if this is a slave or a | |
991 | * sentinel instance). */ | |
992 | if (ri->cc && (ri->flags & (SRI_SLAVE|SRI_SENTINEL) || ri->pc)) | |
993 | ri->flags &= ~SRI_DISCONNECTED; | |
994 | } | |
995 | ||
996 | /* ======================== Redis instances pinging ======================== */ | |
997 | ||
998 | /* Process the INFO output from masters. */ | |
999 | void sentinelRefreshInstanceInfo(sentinelRedisInstance *ri, const char *info) { | |
1000 | sds *lines; | |
1001 | int numlines, j; | |
1002 | int role = 0; | |
e01a415d | 1003 | int runid_changed = 0; /* true if runid changed. */ |
1004 | int first_runid = 0; /* true if this is the first runid we receive. */ | |
120ba392 | 1005 | |
1006 | /* The following fields must be reset to a given value in the case they | |
1007 | * are not found at all in the INFO output. */ | |
1008 | ri->master_link_down_time = 0; | |
1009 | ||
1010 | /* Process line by line. */ | |
1011 | lines = sdssplitlen(info,strlen(info),"\r\n",2,&numlines); | |
1012 | for (j = 0; j < numlines; j++) { | |
1013 | sentinelRedisInstance *slave; | |
1014 | sds l = lines[j]; | |
1015 | ||
1016 | /* run_id:<40 hex chars>*/ | |
1017 | if (sdslen(l) >= 47 && !memcmp(l,"run_id:",7)) { | |
1018 | if (ri->runid == NULL) { | |
1019 | ri->runid = sdsnewlen(l+7,40); | |
e01a415d | 1020 | first_runid = 1; |
120ba392 | 1021 | } else { |
e01a415d | 1022 | if (strncmp(ri->runid,l+7,40) != 0) { |
1023 | runid_changed = 1; | |
1024 | sentinelEvent(REDIS_NOTICE,"+reboot",ri,"%@"); | |
1025 | sdsfree(ri->runid); | |
1026 | ri->runid = sdsnewlen(l+7,40); | |
1027 | } | |
120ba392 | 1028 | } |
1029 | } | |
1030 | ||
1031 | /* slave0:<ip>,<port>,<state> */ | |
1032 | if ((ri->flags & SRI_MASTER) && | |
1033 | sdslen(l) >= 7 && | |
1034 | !memcmp(l,"slave",5) && isdigit(l[5])) | |
1035 | { | |
1036 | char *ip, *port, *end; | |
1037 | ||
1038 | ip = strchr(l,':'); if (!ip) continue; | |
1039 | ip++; /* Now ip points to start of ip address. */ | |
1040 | port = strchr(ip,','); if (!port) continue; | |
1041 | *port = '\0'; /* nul term for easy access. */ | |
1042 | port++; /* Now port points to start of port number. */ | |
1043 | end = strchr(port,','); if (!end) continue; | |
1044 | *end = '\0'; /* nul term for easy access. */ | |
1045 | ||
1046 | /* Check if we already have this slave into our table, | |
1047 | * otherwise add it. */ | |
1048 | if (sentinelRedisInstanceLookupSlave(ri,ip,atoi(port)) == NULL) { | |
1049 | if ((slave = createSentinelRedisInstance(NULL,SRI_SLAVE,ip, | |
1050 | atoi(port), ri->quorum,ri)) != NULL) | |
1051 | { | |
1052 | sentinelEvent(REDIS_NOTICE,"+slave",slave,"%@"); | |
1053 | } | |
1054 | } | |
1055 | } | |
1056 | ||
1057 | /* master_link_down_since_seconds:<seconds> */ | |
1058 | if (sdslen(l) >= 32 && | |
1059 | !memcmp(l,"master_link_down_since_seconds",30)) | |
1060 | { | |
1061 | ri->master_link_down_time = strtoll(l+31,NULL,10)*1000; | |
1062 | } | |
1063 | ||
1064 | /* role:<role> */ | |
1065 | if (!memcmp(l,"role:master",11)) role = SRI_MASTER; | |
1066 | else if (!memcmp(l,"role:slave",10)) role = SRI_SLAVE; | |
1067 | ||
1068 | if (role == SRI_SLAVE) { | |
1069 | /* master_host:<host> */ | |
1070 | if (sdslen(l) >= 12 && !memcmp(l,"master_host:",12)) { | |
1071 | sdsfree(ri->slave_master_host); | |
1072 | ri->slave_master_host = sdsnew(l+12); | |
1073 | } | |
1074 | ||
1075 | /* master_port:<port> */ | |
1076 | if (sdslen(l) >= 12 && !memcmp(l,"master_port:",12)) | |
1077 | ri->slave_master_port = atoi(l+12); | |
1078 | ||
1079 | /* master_link_status:<status> */ | |
1080 | if (sdslen(l) >= 19 && !memcmp(l,"master_link_status:",19)) { | |
1081 | ri->slave_master_link_status = | |
1082 | (strcasecmp(l+19,"up") == 0) ? | |
1083 | SENTINEL_MASTER_LINK_STATUS_UP : | |
1084 | SENTINEL_MASTER_LINK_STATUS_DOWN; | |
1085 | } | |
1086 | } | |
1087 | } | |
1088 | ri->info_refresh = mstime(); | |
1089 | sdsfreesplitres(lines,numlines); | |
1090 | ||
1091 | if (sentinel.tilt) return; | |
1092 | ||
e47236d8 | 1093 | /* Act if a master turned into a slave. */ |
1094 | if ((ri->flags & SRI_MASTER) && role == SRI_SLAVE) { | |
1095 | if (first_runid && ri->slave_master_host) { | |
1096 | /* If it is the first time we receive INFO from it, but it's | |
1097 | * a slave while it was configured as a master, we want to monitor | |
1098 | * its master instead. */ | |
1099 | sentinelEvent(REDIS_WARNING,"+redirect-to-master",ri, | |
1100 | "%s %s %d %s %d", | |
1101 | ri->name, ri->addr->ip, ri->addr->port, | |
1102 | ri->slave_master_host, ri->slave_master_port); | |
1103 | sentinelResetMasterAndChangeAddress(ri,ri->slave_master_host, | |
1104 | ri->slave_master_port); | |
1105 | return; | |
1106 | } | |
1107 | } | |
1108 | ||
120ba392 | 1109 | /* Act if a slave turned into a master. */ |
1110 | if ((ri->flags & SRI_SLAVE) && role == SRI_MASTER) { | |
e01a415d | 1111 | if (!(ri->master->flags & SRI_FAILOVER_IN_PROGRESS) && |
1112 | (runid_changed || first_runid)) | |
1113 | { | |
e01a415d | 1114 | /* If a slave turned into a master, but at the same time the |
1115 | * runid has changed, or it is simply the first time we see and | |
1116 | * INFO output from this instance, this is a reboot with a wrong | |
1117 | * configuration. | |
1118 | * | |
1119 | * Log the event and remove the slave. */ | |
e47236d8 | 1120 | int retval; |
1121 | ||
e01a415d | 1122 | sentinelEvent(REDIS_WARNING,"-slave-restart-as-master",ri,"%@ #removing it from the attached slaves"); |
1123 | retval = dictDelete(ri->master->slaves,ri->name); | |
1124 | redisAssert(retval == REDIS_OK); | |
1125 | return; | |
1126 | } else if (ri->flags & SRI_PROMOTED) { | |
120ba392 | 1127 | /* If this is a promoted slave we can change state to the |
1128 | * failover state machine. */ | |
1129 | if (ri->master && | |
1130 | (ri->master->flags & SRI_FAILOVER_IN_PROGRESS) && | |
1131 | (ri->master->flags & SRI_I_AM_THE_LEADER) && | |
1132 | (ri->master->failover_state == | |
1133 | SENTINEL_FAILOVER_STATE_WAIT_PROMOTION)) | |
1134 | { | |
1135 | ri->master->failover_state = SENTINEL_FAILOVER_STATE_RECONF_SLAVES; | |
1136 | ri->master->failover_state_change_time = mstime(); | |
1137 | sentinelEvent(REDIS_WARNING,"+promoted-slave",ri,"%@"); | |
1138 | sentinelEvent(REDIS_WARNING,"+failover-state-reconf-slaves", | |
1139 | ri->master,"%@"); | |
1140 | } | |
1141 | } else { | |
1142 | /* Otherwise we interpret this as the start of the failover. */ | |
1143 | if (ri->master && | |
1144 | (ri->master->flags & SRI_FAILOVER_IN_PROGRESS) == 0) | |
1145 | { | |
1146 | ri->master->flags |= SRI_FAILOVER_IN_PROGRESS; | |
1147 | sentinelEvent(REDIS_WARNING,"failover-detected",ri->master,"%@"); | |
1148 | ri->master->failover_state = SENTINEL_FAILOVER_STATE_DETECT_END; | |
1149 | ri->master->failover_state_change_time = mstime(); | |
1150 | ri->master->promoted_slave = ri; | |
1151 | ri->flags |= SRI_PROMOTED; | |
1152 | /* We are an observer, so we can only assume that the leader | |
1153 | * is reconfiguring the slave instances. For this reason we | |
1154 | * set all the instances as RECONF_SENT waiting for progresses | |
1155 | * on this side. */ | |
1156 | sentinelAddFlagsToDictOfRedisInstances(ri->master->slaves, | |
1157 | SRI_RECONF_SENT); | |
1158 | } | |
1159 | } | |
1160 | } | |
1161 | ||
1162 | /* Detect if the slave that is in the process of being reconfigured | |
1163 | * changed state. */ | |
1164 | if ((ri->flags & SRI_SLAVE) && role == SRI_SLAVE && | |
1165 | (ri->flags & (SRI_RECONF_SENT|SRI_RECONF_INPROG))) | |
1166 | { | |
1167 | /* SRI_RECONF_SENT -> SRI_RECONF_INPROG. */ | |
1168 | if ((ri->flags & SRI_RECONF_SENT) && | |
1169 | ri->slave_master_host && | |
1170 | strcmp(ri->slave_master_host, | |
1171 | ri->master->promoted_slave->addr->ip) == 0 && | |
1172 | ri->slave_master_port == ri->master->promoted_slave->addr->port) | |
1173 | { | |
1174 | ri->flags &= ~SRI_RECONF_SENT; | |
1175 | ri->flags |= SRI_RECONF_INPROG; | |
1176 | sentinelEvent(REDIS_NOTICE,"+slave-reconf-inprog",ri,"%@"); | |
1177 | } | |
1178 | ||
1179 | /* SRI_RECONF_INPROG -> SRI_RECONF_DONE */ | |
1180 | if ((ri->flags & SRI_RECONF_INPROG) && | |
1181 | ri->slave_master_link_status == SENTINEL_MASTER_LINK_STATUS_UP) | |
1182 | { | |
1183 | ri->flags &= ~SRI_RECONF_INPROG; | |
1184 | ri->flags |= SRI_RECONF_DONE; | |
1185 | sentinelEvent(REDIS_NOTICE,"+slave-reconf-done",ri,"%@"); | |
1186 | /* If we are moving forward (a new slave is now configured) | |
1187 | * we update the change_time as we are conceptually passing | |
1188 | * to the next slave. */ | |
1189 | ri->failover_state_change_time = mstime(); | |
1190 | } | |
1191 | } | |
1192 | } | |
1193 | ||
1194 | void sentinelInfoReplyCallback(redisAsyncContext *c, void *reply, void *privdata) { | |
1195 | sentinelRedisInstance *ri = c->data; | |
1196 | redisReply *r; | |
1197 | ||
8ab7e998 | 1198 | if (ri) ri->pending_commands--; |
1199 | if (!reply || !ri) return; | |
120ba392 | 1200 | r = reply; |
1201 | ||
1202 | if (r->type == REDIS_REPLY_STRING) { | |
1203 | sentinelRefreshInstanceInfo(ri,r->str); | |
1204 | } | |
1205 | } | |
1206 | ||
1207 | /* Just discard the reply. We use this when we are not monitoring the return | |
1208 | * value of the command but its effects directly. */ | |
1209 | void sentinelDiscardReplyCallback(redisAsyncContext *c, void *reply, void *privdata) { | |
1210 | sentinelRedisInstance *ri = c->data; | |
1211 | ||
8ab7e998 | 1212 | if (ri) ri->pending_commands--; |
120ba392 | 1213 | } |
1214 | ||
1215 | void sentinelPingReplyCallback(redisAsyncContext *c, void *reply, void *privdata) { | |
1216 | sentinelRedisInstance *ri = c->data; | |
1217 | redisReply *r; | |
1218 | ||
8ab7e998 | 1219 | if (ri) ri->pending_commands--; |
1220 | if (!reply || !ri) return; | |
120ba392 | 1221 | r = reply; |
1222 | ||
1223 | if (r->type == REDIS_REPLY_STATUS || | |
1224 | r->type == REDIS_REPLY_ERROR) { | |
1225 | /* Update the "instance available" field only if this is an | |
1226 | * acceptable reply. */ | |
1227 | if (strncmp(r->str,"PONG",4) == 0 || | |
1228 | strncmp(r->str,"LOADING",7) == 0 || | |
1229 | strncmp(r->str,"MASTERDOWN",10) == 0) | |
1230 | { | |
1231 | ri->last_avail_time = mstime(); | |
1232 | } | |
1233 | } | |
1234 | ri->last_pong_time = mstime(); | |
1235 | } | |
1236 | ||
1237 | /* This is called when we get the reply about the PUBLISH command we send | |
1238 | * to the master to advertise this sentinel. */ | |
1239 | void sentinelPublishReplyCallback(redisAsyncContext *c, void *reply, void *privdata) { | |
1240 | sentinelRedisInstance *ri = c->data; | |
1241 | redisReply *r; | |
1242 | ||
8ab7e998 | 1243 | if (ri) ri->pending_commands--; |
1244 | if (!reply || !ri) return; | |
120ba392 | 1245 | r = reply; |
1246 | ||
1247 | /* Only update pub_time if we actually published our message. Otherwise | |
1248 | * we'll retry against in 100 milliseconds. */ | |
1249 | if (r->type != REDIS_REPLY_ERROR) | |
1250 | ri->last_pub_time = mstime(); | |
1251 | } | |
1252 | ||
1253 | /* This is our Pub/Sub callback for the Hello channel. It's useful in order | |
1254 | * to discover other sentinels attached at the same master. */ | |
1255 | void sentinelReceiveHelloMessages(redisAsyncContext *c, void *reply, void *privdata) { | |
1256 | sentinelRedisInstance *ri = c->data; | |
1257 | redisReply *r; | |
1258 | ||
8ab7e998 | 1259 | if (!reply || !ri) return; |
120ba392 | 1260 | r = reply; |
1261 | ||
1262 | /* Update the last activity in the pubsub channel. Note that since we | |
1263 | * receive our messages as well this timestamp can be used to detect | |
1264 | * if the link is probably diconnected even if it seems otherwise. */ | |
1265 | ri->pc_last_activity = mstime(); | |
1266 | ||
1267 | /* Sanity check in the reply we expect, so that the code that follows | |
1268 | * can avoid to check for details. */ | |
1269 | if (r->type != REDIS_REPLY_ARRAY || | |
1270 | r->elements != 3 || | |
1271 | r->element[0]->type != REDIS_REPLY_STRING || | |
1272 | r->element[1]->type != REDIS_REPLY_STRING || | |
1273 | r->element[2]->type != REDIS_REPLY_STRING || | |
1274 | strcmp(r->element[0]->str,"message") != 0) return; | |
1275 | ||
1276 | /* We are not interested in meeting ourselves */ | |
1277 | if (strstr(r->element[2]->str,server.runid) != NULL) return; | |
1278 | ||
1279 | { | |
1280 | int numtokens, port, removed, canfailover; | |
1281 | char **token = sdssplitlen(r->element[2]->str, | |
1282 | r->element[2]->len, | |
1283 | ":",1,&numtokens); | |
1284 | sentinelRedisInstance *sentinel; | |
1285 | ||
1286 | if (numtokens == 4) { | |
1287 | /* First, try to see if we already have this sentinel. */ | |
1288 | port = atoi(token[1]); | |
1289 | canfailover = atoi(token[3]); | |
1290 | sentinel = getSentinelRedisInstanceByAddrAndRunID( | |
1291 | ri->sentinels,token[0],port,token[2]); | |
1292 | ||
1293 | if (!sentinel) { | |
1294 | /* If not, remove all the sentinels that have the same runid | |
1295 | * OR the same ip/port, because it's either a restart or a | |
1296 | * network topology change. */ | |
1297 | removed = removeMatchingSentinelsFromMaster(ri,token[0],port, | |
1298 | token[2]); | |
1299 | if (removed) { | |
1300 | sentinelEvent(REDIS_NOTICE,"-dup-sentinel",ri, | |
1301 | "%@ #duplicate of %s:%d or %s", | |
1302 | token[0],port,token[2]); | |
1303 | } | |
1304 | ||
1305 | /* Add the new sentinel. */ | |
1306 | sentinel = createSentinelRedisInstance(NULL,SRI_SENTINEL, | |
1307 | token[0],port,ri->quorum,ri); | |
1308 | if (sentinel) { | |
1309 | sentinelEvent(REDIS_NOTICE,"+sentinel",sentinel,"%@"); | |
1310 | /* The runid is NULL after a new instance creation and | |
1311 | * for Sentinels we don't have a later chance to fill it, | |
1312 | * so do it now. */ | |
1313 | sentinel->runid = sdsnew(token[2]); | |
1314 | } | |
1315 | } | |
1316 | ||
1317 | /* Update the state of the Sentinel. */ | |
1318 | if (sentinel) { | |
1319 | sentinel->last_hello_time = mstime(); | |
1320 | if (canfailover) | |
1321 | sentinel->flags |= SRI_CAN_FAILOVER; | |
1322 | else | |
1323 | sentinel->flags &= ~SRI_CAN_FAILOVER; | |
1324 | } | |
1325 | } | |
1326 | sdsfreesplitres(token,numtokens); | |
1327 | } | |
1328 | } | |
1329 | ||
1330 | void sentinelPingInstance(sentinelRedisInstance *ri) { | |
1331 | mstime_t now = mstime(); | |
1332 | mstime_t info_period; | |
1333 | int retval; | |
1334 | ||
1335 | /* Return ASAP if we have already a PING or INFO already pending, or | |
1336 | * in the case the instance is not properly connected. */ | |
1337 | if (ri->flags & SRI_DISCONNECTED) return; | |
1338 | ||
1339 | /* For INFO, PING, PUBLISH that are not critical commands to send we | |
1340 | * also have a limit of SENTINEL_MAX_PENDING_COMMANDS. We don't | |
1341 | * want to use a lot of memory just because a link is not working | |
1342 | * properly (note that anyway there is a redundant protection about this, | |
1343 | * that is, the link will be disconnected and reconnected if a long | |
1344 | * timeout condition is detected. */ | |
1345 | if (ri->pending_commands >= SENTINEL_MAX_PENDING_COMMANDS) return; | |
1346 | ||
1347 | /* If this is a slave of a master in O_DOWN condition we start sending | |
1348 | * it INFO every second, instead of the usual SENTINEL_INFO_PERIOD | |
1349 | * period. In this state we want to closely monitor slaves in case they | |
1350 | * are turned into masters by another Sentinel, or by the sysadmin. */ | |
1351 | if ((ri->flags & SRI_SLAVE) && | |
1352 | (ri->master->flags & (SRI_O_DOWN|SRI_FAILOVER_IN_PROGRESS))) { | |
1353 | info_period = 1000; | |
1354 | } else { | |
1355 | info_period = SENTINEL_INFO_PERIOD; | |
1356 | } | |
1357 | ||
1358 | if ((ri->flags & SRI_SENTINEL) == 0 && | |
1359 | (ri->info_refresh == 0 || | |
1360 | (now - ri->info_refresh) > info_period)) | |
1361 | { | |
1362 | /* Send INFO to masters and slaves, not sentinels. */ | |
1363 | retval = redisAsyncCommand(ri->cc, | |
1364 | sentinelInfoReplyCallback, NULL, "INFO"); | |
1365 | if (retval != REDIS_OK) return; | |
1366 | ri->pending_commands++; | |
1367 | } else if ((now - ri->last_pong_time) > SENTINEL_PING_PERIOD) { | |
1368 | /* Send PING to all the three kinds of instances. */ | |
1369 | retval = redisAsyncCommand(ri->cc, | |
1370 | sentinelPingReplyCallback, NULL, "PING"); | |
1371 | if (retval != REDIS_OK) return; | |
1372 | ri->pending_commands++; | |
1373 | } else if ((ri->flags & SRI_MASTER) && | |
1374 | (now - ri->last_pub_time) > SENTINEL_PUBLISH_PERIOD) | |
1375 | { | |
1376 | /* PUBLISH hello messages only to masters. */ | |
1377 | struct sockaddr_in sa; | |
1378 | socklen_t salen = sizeof(sa); | |
1379 | ||
1380 | if (getsockname(ri->cc->c.fd,(struct sockaddr*)&sa,&salen) != -1) { | |
1381 | char myaddr[128]; | |
1382 | ||
1383 | snprintf(myaddr,sizeof(myaddr),"%s:%d:%s:%d", | |
1384 | inet_ntoa(sa.sin_addr), server.port, server.runid, | |
1385 | (ri->flags & SRI_CAN_FAILOVER) != 0); | |
1386 | retval = redisAsyncCommand(ri->cc, | |
1387 | sentinelPublishReplyCallback, NULL, "PUBLISH %s %s", | |
1388 | SENTINEL_HELLO_CHANNEL,myaddr); | |
1389 | if (retval != REDIS_OK) return; | |
1390 | ri->pending_commands++; | |
1391 | } | |
1392 | } | |
1393 | } | |
1394 | ||
1395 | /* =========================== SENTINEL command ============================= */ | |
1396 | ||
1397 | const char *sentinelFailoverStateStr(int state) { | |
1398 | switch(state) { | |
1399 | case SENTINEL_FAILOVER_STATE_NONE: return "none"; | |
1400 | case SENTINEL_FAILOVER_STATE_WAIT_START: return "wait_start"; | |
1401 | case SENTINEL_FAILOVER_STATE_SELECT_SLAVE: return "select_slave"; | |
1402 | case SENTINEL_FAILOVER_STATE_SEND_SLAVEOF_NOONE: return "send_slaveof_noone"; | |
1403 | case SENTINEL_FAILOVER_STATE_WAIT_PROMOTION: return "wait_promotion"; | |
1404 | case SENTINEL_FAILOVER_STATE_RECONF_SLAVES: return "reconf_slaves"; | |
1405 | case SENTINEL_FAILOVER_STATE_ALERT_CLIENTS: return "alert_clients"; | |
1406 | case SENTINEL_FAILOVER_STATE_DETECT_END: return "detect_end"; | |
1407 | case SENTINEL_FAILOVER_STATE_UPDATE_CONFIG: return "update_config"; | |
1408 | default: return "unknown"; | |
1409 | } | |
1410 | } | |
1411 | ||
1412 | /* Redis instance to Redis protocol representation. */ | |
1413 | void addReplySentinelRedisInstance(redisClient *c, sentinelRedisInstance *ri) { | |
1414 | char *flags = sdsempty(); | |
1415 | void *mbl; | |
1416 | int fields = 0; | |
1417 | ||
1418 | mbl = addDeferredMultiBulkLength(c); | |
1419 | ||
1420 | addReplyBulkCString(c,"name"); | |
1421 | addReplyBulkCString(c,ri->name); | |
1422 | fields++; | |
1423 | ||
1424 | addReplyBulkCString(c,"ip"); | |
1425 | addReplyBulkCString(c,ri->addr->ip); | |
1426 | fields++; | |
1427 | ||
1428 | addReplyBulkCString(c,"port"); | |
1429 | addReplyBulkLongLong(c,ri->addr->port); | |
1430 | fields++; | |
1431 | ||
1432 | addReplyBulkCString(c,"runid"); | |
1433 | addReplyBulkCString(c,ri->runid ? ri->runid : ""); | |
1434 | fields++; | |
1435 | ||
1436 | addReplyBulkCString(c,"flags"); | |
1437 | if (ri->flags & SRI_S_DOWN) flags = sdscat(flags,"s_down,"); | |
1438 | if (ri->flags & SRI_O_DOWN) flags = sdscat(flags,"o_down,"); | |
1439 | if (ri->flags & SRI_MASTER) flags = sdscat(flags,"master,"); | |
1440 | if (ri->flags & SRI_SLAVE) flags = sdscat(flags,"slave,"); | |
1441 | if (ri->flags & SRI_SENTINEL) flags = sdscat(flags,"sentinel,"); | |
1442 | if (ri->flags & SRI_DISCONNECTED) flags = sdscat(flags,"disconnected,"); | |
1443 | if (ri->flags & SRI_MASTER_DOWN) flags = sdscat(flags,"master_down,"); | |
1444 | if (ri->flags & SRI_FAILOVER_IN_PROGRESS) | |
1445 | flags = sdscat(flags,"failover_in_progress,"); | |
1446 | if (ri->flags & SRI_I_AM_THE_LEADER) | |
1447 | flags = sdscat(flags,"i_am_the_leader,"); | |
1448 | if (ri->flags & SRI_PROMOTED) flags = sdscat(flags,"promoted,"); | |
1449 | if (ri->flags & SRI_RECONF_SENT) flags = sdscat(flags,"reconf_sent,"); | |
1450 | if (ri->flags & SRI_RECONF_INPROG) flags = sdscat(flags,"reconf_inprog,"); | |
1451 | if (ri->flags & SRI_RECONF_DONE) flags = sdscat(flags,"reconf_done,"); | |
1452 | ||
1453 | if (sdslen(flags) != 0) flags = sdsrange(flags,0,-2); /* remove last "," */ | |
1454 | addReplyBulkCString(c,flags); | |
1455 | sdsfree(flags); | |
1456 | fields++; | |
1457 | ||
1458 | addReplyBulkCString(c,"pending-commands"); | |
1459 | addReplyBulkLongLong(c,ri->pending_commands); | |
1460 | fields++; | |
1461 | ||
1462 | if (ri->flags & SRI_FAILOVER_IN_PROGRESS) { | |
1463 | addReplyBulkCString(c,"failover-state"); | |
1464 | addReplyBulkCString(c,(char*)sentinelFailoverStateStr(ri->failover_state)); | |
1465 | fields++; | |
1466 | } | |
1467 | ||
1468 | addReplyBulkCString(c,"last-ok-ping-reply"); | |
1469 | addReplyBulkLongLong(c,mstime() - ri->last_avail_time); | |
1470 | fields++; | |
1471 | ||
1472 | addReplyBulkCString(c,"last-ping-reply"); | |
1473 | addReplyBulkLongLong(c,mstime() - ri->last_pong_time); | |
1474 | fields++; | |
1475 | ||
1476 | if (ri->flags & SRI_S_DOWN) { | |
1477 | addReplyBulkCString(c,"s-down-time"); | |
1478 | addReplyBulkLongLong(c,mstime()-ri->s_down_since_time); | |
1479 | fields++; | |
1480 | } | |
1481 | ||
1482 | if (ri->flags & SRI_O_DOWN) { | |
1483 | addReplyBulkCString(c,"o-down-time"); | |
1484 | addReplyBulkLongLong(c,mstime()-ri->o_down_since_time); | |
1485 | fields++; | |
1486 | } | |
1487 | ||
1488 | /* Masters and Slaves */ | |
1489 | if (ri->flags & (SRI_MASTER|SRI_SLAVE)) { | |
1490 | addReplyBulkCString(c,"info-refresh"); | |
1491 | addReplyBulkLongLong(c,mstime() - ri->info_refresh); | |
1492 | fields++; | |
1493 | } | |
1494 | ||
1495 | /* Only masters */ | |
1496 | if (ri->flags & SRI_MASTER) { | |
1497 | addReplyBulkCString(c,"num-slaves"); | |
1498 | addReplyBulkLongLong(c,dictSize(ri->slaves)); | |
1499 | fields++; | |
1500 | ||
1501 | addReplyBulkCString(c,"num-other-sentinels"); | |
1502 | addReplyBulkLongLong(c,dictSize(ri->sentinels)); | |
1503 | fields++; | |
1504 | ||
1505 | addReplyBulkCString(c,"quorum"); | |
1506 | addReplyBulkLongLong(c,ri->quorum); | |
1507 | fields++; | |
1508 | } | |
1509 | ||
1510 | /* Only slaves */ | |
1511 | if (ri->flags & SRI_SLAVE) { | |
1512 | addReplyBulkCString(c,"master-link-down-time"); | |
1513 | addReplyBulkLongLong(c,ri->master_link_down_time); | |
1514 | fields++; | |
1515 | ||
1516 | addReplyBulkCString(c,"master-link-status"); | |
1517 | addReplyBulkCString(c, | |
1518 | (ri->slave_master_link_status == SENTINEL_MASTER_LINK_STATUS_UP) ? | |
1519 | "ok" : "err"); | |
1520 | fields++; | |
1521 | ||
1522 | addReplyBulkCString(c,"master-host"); | |
1523 | addReplyBulkCString(c, | |
1524 | ri->slave_master_host ? ri->slave_master_host : "?"); | |
1525 | fields++; | |
1526 | ||
1527 | addReplyBulkCString(c,"master-port"); | |
1528 | addReplyBulkLongLong(c,ri->slave_master_port); | |
1529 | fields++; | |
1530 | } | |
1531 | ||
1532 | /* Only sentinels */ | |
1533 | if (ri->flags & SRI_SENTINEL) { | |
1534 | addReplyBulkCString(c,"last-hello-message"); | |
1535 | addReplyBulkLongLong(c,mstime() - ri->last_hello_time); | |
1536 | fields++; | |
1537 | ||
1538 | addReplyBulkCString(c,"can-failover-its-master"); | |
1539 | addReplyBulkLongLong(c,(ri->flags & SRI_CAN_FAILOVER) != 0); | |
1540 | fields++; | |
1541 | ||
1542 | if (ri->flags & SRI_MASTER_DOWN) { | |
1543 | addReplyBulkCString(c,"subjective-leader"); | |
1544 | addReplyBulkCString(c,ri->leader ? ri->leader : "?"); | |
1545 | fields++; | |
1546 | } | |
1547 | } | |
1548 | ||
1549 | setDeferredMultiBulkLength(c,mbl,fields*2); | |
1550 | } | |
1551 | ||
1552 | /* Output a number of instances contanined inside a dictionary as | |
1553 | * Redis protocol. */ | |
1554 | void addReplyDictOfRedisInstances(redisClient *c, dict *instances) { | |
1555 | dictIterator *di; | |
1556 | dictEntry *de; | |
1557 | ||
1558 | di = dictGetIterator(instances); | |
1559 | addReplyMultiBulkLen(c,dictSize(instances)); | |
1560 | while((de = dictNext(di)) != NULL) { | |
1561 | sentinelRedisInstance *ri = dictGetVal(de); | |
1562 | ||
1563 | addReplySentinelRedisInstance(c,ri); | |
1564 | } | |
1565 | dictReleaseIterator(di); | |
1566 | } | |
1567 | ||
1568 | /* Lookup the named master into sentinel.masters. | |
1569 | * If the master is not found reply to the client with an error and returns | |
1570 | * NULL. */ | |
1571 | sentinelRedisInstance *sentinelGetMasterByNameOrReplyError(redisClient *c, | |
1572 | robj *name) | |
1573 | { | |
1574 | sentinelRedisInstance *ri; | |
1575 | ||
1576 | ri = dictFetchValue(sentinel.masters,c->argv[2]->ptr); | |
1577 | if (!ri) { | |
1578 | addReplyError(c,"No such master with that name"); | |
1579 | return NULL; | |
1580 | } | |
1581 | return ri; | |
1582 | } | |
1583 | ||
1584 | void sentinelCommand(redisClient *c) { | |
1585 | if (!strcasecmp(c->argv[1]->ptr,"masters")) { | |
1586 | /* SENTINEL MASTERS */ | |
1587 | if (c->argc != 2) goto numargserr; | |
1588 | ||
1589 | addReplyDictOfRedisInstances(c,sentinel.masters); | |
1590 | } else if (!strcasecmp(c->argv[1]->ptr,"slaves")) { | |
1591 | /* SENTINEL SLAVES <master-name> */ | |
1592 | sentinelRedisInstance *ri; | |
1593 | ||
1594 | if (c->argc != 3) goto numargserr; | |
1595 | if ((ri = sentinelGetMasterByNameOrReplyError(c,c->argv[2])) == NULL) | |
1596 | return; | |
1597 | addReplyDictOfRedisInstances(c,ri->slaves); | |
1598 | } else if (!strcasecmp(c->argv[1]->ptr,"sentinels")) { | |
1599 | /* SENTINEL SENTINELS <master-name> */ | |
1600 | sentinelRedisInstance *ri; | |
1601 | ||
1602 | if (c->argc != 3) goto numargserr; | |
1603 | if ((ri = sentinelGetMasterByNameOrReplyError(c,c->argv[2])) == NULL) | |
1604 | return; | |
1605 | addReplyDictOfRedisInstances(c,ri->sentinels); | |
1606 | } else if (!strcasecmp(c->argv[1]->ptr,"is-master-down-by-addr")) { | |
1607 | /* SENTINEL IS-MASTER-DOWN-BY-ADDR <ip> <port> */ | |
1608 | sentinelRedisInstance *ri; | |
1609 | char *leader = NULL; | |
1610 | long port; | |
1611 | int isdown = 0; | |
1612 | ||
1613 | if (c->argc != 4) goto numargserr; | |
1614 | if (getLongFromObjectOrReply(c,c->argv[3],&port,NULL) != REDIS_OK) | |
1615 | return; | |
1616 | ri = getSentinelRedisInstanceByAddrAndRunID(sentinel.masters, | |
1617 | c->argv[2]->ptr,port,NULL); | |
1618 | ||
1619 | /* It exists? Is actually a master? Is subjectively down? It's down. | |
1620 | * Note: if we are in tilt mode we always reply with "0". */ | |
1621 | if (!sentinel.tilt && ri && (ri->flags & SRI_S_DOWN) && | |
1622 | (ri->flags & SRI_MASTER)) | |
1623 | isdown = 1; | |
1624 | if (ri) leader = sentinelGetSubjectiveLeader(ri); | |
1625 | ||
1626 | /* Reply with a two-elements multi-bulk reply: down state, leader. */ | |
1627 | addReplyMultiBulkLen(c,2); | |
1628 | addReply(c, isdown ? shared.cone : shared.czero); | |
1629 | addReplyBulkCString(c, leader ? leader : "?"); | |
1630 | if (leader) sdsfree(leader); | |
1631 | } else if (!strcasecmp(c->argv[1]->ptr,"reset")) { | |
1632 | /* SENTINEL RESET <pattern> */ | |
1633 | if (c->argc != 3) goto numargserr; | |
e47236d8 | 1634 | addReplyLongLong(c,sentinelResetMastersByPattern(c->argv[2]->ptr,SENTINEL_GENERATE_EVENT)); |
120ba392 | 1635 | } else if (!strcasecmp(c->argv[1]->ptr,"get-master-addr-by-name")) { |
1636 | /* SENTINEL GET-MASTER-ADDR-BY-NAME <master-name> */ | |
1637 | sentinelRedisInstance *ri; | |
1638 | ||
1639 | if (c->argc != 3) goto numargserr; | |
1640 | ri = sentinelGetMasterByName(c->argv[2]->ptr); | |
1641 | if (ri == NULL) { | |
1642 | addReply(c,shared.nullmultibulk); | |
1643 | } else { | |
1644 | sentinelAddr *addr = ri->addr; | |
1645 | ||
1646 | if ((ri->flags & SRI_FAILOVER_IN_PROGRESS) && ri->promoted_slave) | |
1647 | addr = ri->promoted_slave->addr; | |
1648 | addReplyMultiBulkLen(c,2); | |
1649 | addReplyBulkCString(c,addr->ip); | |
1650 | addReplyBulkLongLong(c,addr->port); | |
1651 | } | |
1652 | } else { | |
1653 | addReplyErrorFormat(c,"Unknown sentinel subcommand '%s'", | |
1654 | (char*)c->argv[1]->ptr); | |
1655 | } | |
1656 | return; | |
1657 | ||
1658 | numargserr: | |
1659 | addReplyErrorFormat(c,"Wrong number of commands for 'sentinel %s'", | |
1660 | (char*)c->argv[1]->ptr); | |
1661 | } | |
1662 | ||
1663 | /* ===================== SENTINEL availability checks ======================= */ | |
1664 | ||
1665 | /* Is this instance down from our point of view? */ | |
1666 | void sentinelCheckSubjectivelyDown(sentinelRedisInstance *ri) { | |
1667 | mstime_t elapsed = mstime() - ri->last_avail_time; | |
1668 | ||
1669 | /* Check if we are in need for a reconnection of one of the | |
1670 | * links, because we are detecting low activity. | |
1671 | * | |
1672 | * 1) Check if the command link seems connected, was connected not less | |
1673 | * than SENTINEL_MIN_LINK_RECONNECT_PERIOD, but still we have an | |
1674 | * idle time that is greater than down_after_period / 2 seconds. */ | |
1675 | if (ri->cc && | |
1676 | (mstime() - ri->cc_conn_time) > SENTINEL_MIN_LINK_RECONNECT_PERIOD && | |
1677 | (mstime() - ri->last_pong_time) > (ri->down_after_period/2)) | |
1678 | { | |
e47236d8 | 1679 | sentinelKillLink(ri,ri->cc); |
120ba392 | 1680 | } |
1681 | ||
1682 | /* 2) Check if the pubsub link seems connected, was connected not less | |
1683 | * than SENTINEL_MIN_LINK_RECONNECT_PERIOD, but still we have no | |
1684 | * activity in the Pub/Sub channel for more than | |
1685 | * SENTINEL_PUBLISH_PERIOD * 3. | |
1686 | */ | |
1687 | if (ri->pc && | |
1688 | (mstime() - ri->pc_conn_time) > SENTINEL_MIN_LINK_RECONNECT_PERIOD && | |
1689 | (mstime() - ri->pc_last_activity) > (SENTINEL_PUBLISH_PERIOD*3)) | |
1690 | { | |
e47236d8 | 1691 | sentinelKillLink(ri,ri->pc); |
120ba392 | 1692 | } |
1693 | ||
1694 | /* Update the subjectively down flag. */ | |
1695 | if (elapsed > ri->down_after_period) { | |
1696 | /* Is subjectively down */ | |
1697 | if ((ri->flags & SRI_S_DOWN) == 0) { | |
1698 | sentinelEvent(REDIS_WARNING,"+sdown",ri,"%@"); | |
1699 | ri->s_down_since_time = mstime(); | |
1700 | ri->flags |= SRI_S_DOWN; | |
1701 | } | |
1702 | } else { | |
1703 | /* Is subjectively up */ | |
1704 | if (ri->flags & SRI_S_DOWN) { | |
1705 | sentinelEvent(REDIS_WARNING,"-sdown",ri,"%@"); | |
1706 | ri->flags &= ~SRI_S_DOWN; | |
1707 | } | |
1708 | } | |
1709 | } | |
1710 | ||
1711 | /* Is this instance down accordingly to the configured quorum? */ | |
1712 | void sentinelCheckObjectivelyDown(sentinelRedisInstance *master) { | |
1713 | dictIterator *di; | |
1714 | dictEntry *de; | |
1715 | int quorum = 0, odown = 0; | |
1716 | ||
1717 | if (master->flags & SRI_S_DOWN) { | |
1718 | /* Is down for enough sentinels? */ | |
1719 | quorum = 1; /* the current sentinel. */ | |
1720 | /* Count all the other sentinels. */ | |
1721 | di = dictGetIterator(master->sentinels); | |
1722 | while((de = dictNext(di)) != NULL) { | |
1723 | sentinelRedisInstance *ri = dictGetVal(de); | |
1724 | ||
1725 | if (ri->flags & SRI_MASTER_DOWN) quorum++; | |
1726 | } | |
1727 | dictReleaseIterator(di); | |
1728 | if (quorum >= master->quorum) odown = 1; | |
1729 | } | |
1730 | ||
1731 | /* Set the flag accordingly to the outcome. */ | |
1732 | if (odown) { | |
1733 | if ((master->flags & SRI_O_DOWN) == 0) { | |
1734 | sentinelEvent(REDIS_WARNING,"+odown",master,"%@ #quorum %d/%d", | |
1735 | quorum, master->quorum); | |
1736 | master->flags |= SRI_O_DOWN; | |
1737 | master->o_down_since_time = mstime(); | |
1738 | } | |
1739 | } else { | |
1740 | if (master->flags & SRI_O_DOWN) { | |
1741 | sentinelEvent(REDIS_WARNING,"-odown",master,"%@"); | |
1742 | master->flags &= ~SRI_O_DOWN; | |
1743 | } | |
1744 | } | |
1745 | } | |
1746 | ||
1747 | /* Receive the SENTINEL is-master-down-by-addr reply, see the | |
1748 | * sentinelAskMasterStateToOtherSentinels() function for more information. */ | |
1749 | void sentinelReceiveIsMasterDownReply(redisAsyncContext *c, void *reply, void *privdata) { | |
1750 | sentinelRedisInstance *ri = c->data; | |
1751 | redisReply *r; | |
1752 | ||
8ab7e998 | 1753 | if (ri) ri->pending_commands--; |
1754 | if (!reply || !ri) return; | |
120ba392 | 1755 | r = reply; |
1756 | ||
1757 | /* Ignore every error or unexpected reply. | |
1758 | * Note that if the command returns an error for any reason we'll | |
1759 | * end clearing the SRI_MASTER_DOWN flag for timeout anyway. */ | |
1760 | if (r->type == REDIS_REPLY_ARRAY && r->elements == 2 && | |
1761 | r->element[0]->type == REDIS_REPLY_INTEGER && | |
1762 | r->element[1]->type == REDIS_REPLY_STRING) | |
1763 | { | |
1764 | ri->last_master_down_reply_time = mstime(); | |
1765 | if (r->element[0]->integer == 1) { | |
1766 | ri->flags |= SRI_MASTER_DOWN; | |
1767 | } else { | |
1768 | ri->flags &= ~SRI_MASTER_DOWN; | |
1769 | } | |
1770 | sdsfree(ri->leader); | |
1771 | ri->leader = sdsnew(r->element[1]->str); | |
1772 | } | |
1773 | } | |
1774 | ||
1775 | /* If we think (subjectively) the master is down, we start sending | |
1776 | * SENTINEL IS-MASTER-DOWN-BY-ADDR requests to other sentinels | |
1777 | * in order to get the replies that allow to reach the quorum and | |
1778 | * possibly also mark the master as objectively down. */ | |
1779 | void sentinelAskMasterStateToOtherSentinels(sentinelRedisInstance *master) { | |
1780 | dictIterator *di; | |
1781 | dictEntry *de; | |
1782 | ||
1783 | di = dictGetIterator(master->sentinels); | |
1784 | while((de = dictNext(di)) != NULL) { | |
1785 | sentinelRedisInstance *ri = dictGetVal(de); | |
1786 | mstime_t elapsed = mstime() - ri->last_master_down_reply_time; | |
1787 | char port[32]; | |
1788 | int retval; | |
1789 | ||
1790 | /* If the master state from other sentinel is too old, we clear it. */ | |
1791 | if (elapsed > SENTINEL_INFO_VALIDITY_TIME) { | |
1792 | ri->flags &= ~SRI_MASTER_DOWN; | |
1793 | sdsfree(ri->leader); | |
1794 | ri->leader = NULL; | |
1795 | } | |
1796 | ||
1797 | /* Only ask if master is down to other sentinels if: | |
1798 | * | |
1799 | * 1) We believe it is down, or there is a failover in progress. | |
1800 | * 2) Sentinel is connected. | |
1801 | * 3) We did not received the info within SENTINEL_ASK_PERIOD ms. */ | |
1802 | if ((master->flags & (SRI_S_DOWN|SRI_FAILOVER_IN_PROGRESS)) == 0) | |
1803 | continue; | |
1804 | if (ri->flags & SRI_DISCONNECTED) continue; | |
1805 | if (mstime() - ri->last_master_down_reply_time < SENTINEL_ASK_PERIOD) | |
1806 | continue; | |
1807 | ||
1808 | /* Ask */ | |
1809 | ll2string(port,sizeof(port),master->addr->port); | |
1810 | retval = redisAsyncCommand(ri->cc, | |
1811 | sentinelReceiveIsMasterDownReply, NULL, | |
1812 | "SENTINEL is-master-down-by-addr %s %s", | |
1813 | master->addr->ip, port); | |
1814 | if (retval == REDIS_OK) ri->pending_commands++; | |
1815 | } | |
1816 | dictReleaseIterator(di); | |
1817 | } | |
1818 | ||
1819 | /* =============================== FAILOVER ================================= */ | |
1820 | ||
1821 | /* Given a master get the "subjective leader", that is, among all the sentinels | |
1822 | * with given characteristics, the one with the lexicographically smaller | |
1823 | * runid. The characteristics required are: | |
1824 | * | |
1825 | * 1) Has SRI_CAN_FAILOVER flag. | |
1826 | * 2) Is not disconnected. | |
1827 | * 3) Recently answered to our ping (no longer than | |
1828 | * SENTINEL_INFO_VALIDITY_TIME milliseconds ago). | |
1829 | * | |
1830 | * The function returns a pointer to an sds string representing the runid of the | |
1831 | * leader sentinel instance (from our point of view). Otherwise NULL is | |
1832 | * returned if there are no suitable sentinels. | |
1833 | */ | |
1834 | ||
1835 | int compareRunID(const void *a, const void *b) { | |
1836 | char **aptrptr = (char**)a, **bptrptr = (char**)b; | |
1837 | return strcasecmp(*aptrptr, *bptrptr); | |
1838 | } | |
1839 | ||
1840 | char *sentinelGetSubjectiveLeader(sentinelRedisInstance *master) { | |
1841 | dictIterator *di; | |
1842 | dictEntry *de; | |
1843 | char **instance = | |
1844 | zmalloc(sizeof(char*)*(dictSize(master->sentinels)+1)); | |
1845 | int instances = 0; | |
1846 | char *leader = NULL; | |
1847 | ||
1848 | if (master->flags & SRI_CAN_FAILOVER) { | |
1849 | /* Add myself if I'm a Sentinel that can failover this master. */ | |
1850 | instance[instances++] = server.runid; | |
1851 | } | |
1852 | ||
1853 | di = dictGetIterator(master->sentinels); | |
1854 | while((de = dictNext(di)) != NULL) { | |
1855 | sentinelRedisInstance *ri = dictGetVal(de); | |
1856 | mstime_t lag = mstime() - ri->last_avail_time; | |
1857 | ||
1858 | if (lag > SENTINEL_INFO_VALIDITY_TIME || | |
1859 | !(ri->flags & SRI_CAN_FAILOVER) || | |
1860 | (ri->flags & SRI_DISCONNECTED) || | |
1861 | ri->runid == NULL) | |
1862 | continue; | |
1863 | instance[instances++] = ri->runid; | |
1864 | } | |
1865 | dictReleaseIterator(di); | |
1866 | ||
1867 | /* If we have at least one instance passing our checks, order the array | |
1868 | * by runid. */ | |
1869 | if (instances) { | |
1870 | qsort(instance,instances,sizeof(char*),compareRunID); | |
1871 | leader = sdsnew(instance[0]); | |
1872 | } | |
1873 | zfree(instance); | |
1874 | return leader; | |
1875 | } | |
1876 | ||
1877 | struct sentinelLeader { | |
1878 | char *runid; | |
1879 | unsigned long votes; | |
1880 | }; | |
1881 | ||
1882 | /* Helper function for sentinelGetObjectiveLeader, increment the counter | |
1883 | * relative to the specified runid. */ | |
1884 | void sentinelObjectiveLeaderIncr(dict *counters, char *runid) { | |
1885 | dictEntry *de = dictFind(counters,runid); | |
1886 | uint64_t oldval; | |
1887 | ||
1888 | if (de) { | |
1889 | oldval = dictGetUnsignedIntegerVal(de); | |
1890 | dictSetUnsignedIntegerVal(de,oldval+1); | |
1891 | } else { | |
1892 | de = dictAddRaw(counters,runid); | |
1893 | redisAssert(de != NULL); | |
1894 | dictSetUnsignedIntegerVal(de,1); | |
1895 | } | |
1896 | } | |
1897 | ||
1898 | /* Scan all the Sentinels attached to this master to check what is the | |
1899 | * most voted leader among Sentinels. */ | |
1900 | char *sentinelGetObjectiveLeader(sentinelRedisInstance *master) { | |
1901 | dict *counters; | |
1902 | dictIterator *di; | |
1903 | dictEntry *de; | |
1904 | unsigned int voters = 0, voters_quorum; | |
1905 | char *myvote; | |
1906 | char *winner = NULL; | |
1907 | ||
1908 | redisAssert(master->flags & (SRI_O_DOWN|SRI_FAILOVER_IN_PROGRESS)); | |
1909 | counters = dictCreate(&leaderVotesDictType,NULL); | |
1910 | ||
1911 | /* Count my vote. */ | |
1912 | myvote = sentinelGetSubjectiveLeader(master); | |
1913 | if (myvote) { | |
1914 | sentinelObjectiveLeaderIncr(counters,myvote); | |
1915 | voters++; | |
1916 | } | |
1917 | ||
1918 | /* Count other sentinels votes */ | |
1919 | di = dictGetIterator(master->sentinels); | |
1920 | while((de = dictNext(di)) != NULL) { | |
1921 | sentinelRedisInstance *ri = dictGetVal(de); | |
1922 | if (ri->leader == NULL) continue; | |
1923 | /* If the failover is not already in progress we are only interested | |
1924 | * in Sentinels that believe the master is down. Otherwise the leader | |
1925 | * selection is useful for the "failover-takedown" when the original | |
1926 | * leader fails. In that case we consider all the voters. */ | |
1927 | if (!(master->flags & SRI_FAILOVER_IN_PROGRESS) && | |
1928 | !(ri->flags & SRI_MASTER_DOWN)) continue; | |
1929 | sentinelObjectiveLeaderIncr(counters,ri->leader); | |
1930 | voters++; | |
1931 | } | |
1932 | dictReleaseIterator(di); | |
1933 | voters_quorum = voters/2+1; | |
1934 | ||
1935 | /* Check what's the winner. For the winner to win, it needs two conditions: | |
1936 | * 1) Absolute majority between voters (50% + 1). | |
1937 | * 2) And anyway at least master->quorum votes. */ | |
1938 | { | |
1939 | uint64_t max_votes = 0; /* Max votes so far. */ | |
1940 | ||
1941 | di = dictGetIterator(counters); | |
1942 | while((de = dictNext(di)) != NULL) { | |
1943 | uint64_t votes = dictGetUnsignedIntegerVal(de); | |
1944 | ||
1945 | if (max_votes < votes) { | |
1946 | max_votes = votes; | |
1947 | winner = dictGetKey(de); | |
1948 | } | |
1949 | } | |
1950 | dictReleaseIterator(di); | |
1951 | if (winner && (max_votes < voters_quorum || max_votes < master->quorum)) | |
1952 | winner = NULL; | |
1953 | } | |
1954 | winner = winner ? sdsnew(winner) : NULL; | |
1955 | sdsfree(myvote); | |
1956 | dictRelease(counters); | |
1957 | return winner; | |
1958 | } | |
1959 | ||
1960 | /* This function checks if there are the conditions to start the failover, | |
1961 | * that is: | |
1962 | * | |
1963 | * 1) Enough time has passed since O_DOWN. | |
1964 | * 2) The master is marked as SRI_CAN_FAILOVER, so we can failover it. | |
1965 | * 3) We are the objectively leader for this master. | |
1966 | * | |
1967 | * If the conditions are met we flag the master as SRI_FAILOVER_IN_PROGRESS | |
1968 | * and SRI_I_AM_THE_LEADER. | |
1969 | */ | |
1970 | void sentinelStartFailover(sentinelRedisInstance *master) { | |
1971 | char *leader; | |
1972 | int isleader; | |
1973 | ||
1974 | /* We can't failover if the master is not in O_DOWN state or if | |
1975 | * there is not already a failover in progress (to perform the | |
1976 | * takedown if the leader died) or if this Sentinel is not allowed | |
1977 | * to start a failover. */ | |
1978 | if (!(master->flags & SRI_CAN_FAILOVER) || | |
1979 | !(master->flags & (SRI_O_DOWN|SRI_FAILOVER_IN_PROGRESS))) return; | |
1980 | ||
1981 | leader = sentinelGetObjectiveLeader(master); | |
1982 | isleader = leader && strcasecmp(leader,server.runid) == 0; | |
1983 | sdsfree(leader); | |
1984 | ||
1985 | /* If I'm not the leader, I can't failover for sure. */ | |
1986 | if (!isleader) return; | |
1987 | ||
1988 | /* If the failover is already in progress there are two options... */ | |
1989 | if (master->flags & SRI_FAILOVER_IN_PROGRESS) { | |
1990 | if (master->flags & SRI_I_AM_THE_LEADER) { | |
1991 | /* 1) I'm flagged as leader so I already started the failover. | |
1992 | * Just return. */ | |
1993 | return; | |
1994 | } else { | |
1995 | mstime_t elapsed = mstime() - master->failover_state_change_time; | |
1996 | ||
1997 | /* 2) I'm the new leader, but I'm not flagged as leader in the | |
1998 | * master: I did not started the failover, but the original | |
1999 | * leader has no longer the leadership. | |
2000 | * | |
2001 | * In this case if the failover appears to be lagging | |
2002 | * for at least 25% of the configured failover timeout, | |
2003 | * I can assume I can take control. Otherwise | |
2004 | * it's better to return and wait more. */ | |
2005 | if (elapsed < (master->failover_timeout/4)) return; | |
2006 | sentinelEvent(REDIS_WARNING,"+failover-takedown",master,"%@"); | |
2007 | /* We have already an elected slave if we are in | |
2008 | * FAILOVER_IN_PROGRESS state, that is, the slave that we | |
2009 | * observed turning into a master. */ | |
2010 | master->failover_state = SENTINEL_FAILOVER_STATE_RECONF_SLAVES; | |
2011 | /* As an observer we flagged all the slaves as RECONF_SENT but | |
2012 | * now we are in charge of actually sending the reconfiguration | |
2013 | * command so let's clear this flag for all the instances. */ | |
2014 | sentinelDelFlagsToDictOfRedisInstances(master->slaves, | |
2015 | SRI_RECONF_SENT); | |
2016 | } | |
2017 | } else { | |
2018 | /* Brand new failover as SRI_FAILOVER_IN_PROGRESS was not set. */ | |
2019 | master->failover_state = SENTINEL_FAILOVER_STATE_WAIT_START; | |
2020 | } | |
2021 | ||
2022 | master->flags |= SRI_FAILOVER_IN_PROGRESS|SRI_I_AM_THE_LEADER; | |
2023 | sentinelEvent(REDIS_WARNING,"+failover-triggered",master,"%@"); | |
2024 | ||
2025 | /* Pick a random delay if it's a fresh failover (WAIT_START), and not | |
2026 | * a recovery of a failover started by another sentinel. */ | |
2027 | if (master->failover_state == SENTINEL_FAILOVER_STATE_WAIT_START) { | |
2028 | master->failover_start_time = mstime() + | |
2029 | SENTINEL_FAILOVER_FIXED_DELAY + | |
2030 | (rand() % SENTINEL_FAILOVER_MAX_RANDOM_DELAY); | |
2031 | sentinelEvent(REDIS_WARNING,"+failover-state-wait-start",master, | |
2032 | "%@ #starting in %lld milliseconds", | |
2033 | master->failover_start_time-mstime()); | |
2034 | } | |
2035 | master->failover_state_change_time = mstime(); | |
2036 | } | |
2037 | ||
2038 | /* Select a suitable slave to promote. The current algorithm only uses | |
2039 | * the following parameters: | |
2040 | * | |
2041 | * 1) None of the following conditions: S_DOWN, O_DOWN, DISCONNECTED. | |
2042 | * 2) last_avail_time more recent than SENTINEL_INFO_VALIDITY_TIME. | |
2043 | * 3) info_refresh more recent than SENTINEL_INFO_VALIDITY_TIME. | |
2044 | * 4) master_link_down_time no more than: | |
2045 | * (now - master->s_down_since_time) + (master->down_after_period * 10). | |
2046 | * | |
2047 | * Among all the slaves matching the above conditions we select the slave | |
2048 | * with lower slave_priority. If priority is the same we select the slave | |
2049 | * with lexicographically smaller runid. | |
2050 | * | |
2051 | * The function returns the pointer to the selected slave, otherwise | |
2052 | * NULL if no suitable slave was found. | |
2053 | */ | |
2054 | ||
2055 | int compareSlavesForPromotion(const void *a, const void *b) { | |
2056 | sentinelRedisInstance **sa = (sentinelRedisInstance **)a, | |
2057 | **sb = (sentinelRedisInstance **)b; | |
2058 | if ((*sa)->slave_priority != (*sb)->slave_priority) | |
2059 | return (*sa)->slave_priority - (*sb)->slave_priority; | |
2060 | return strcasecmp((*sa)->runid,(*sb)->runid); | |
2061 | } | |
2062 | ||
2063 | sentinelRedisInstance *sentinelSelectSlave(sentinelRedisInstance *master) { | |
2064 | sentinelRedisInstance **instance = | |
2065 | zmalloc(sizeof(instance[0])*dictSize(master->slaves)); | |
2066 | sentinelRedisInstance *selected = NULL; | |
2067 | int instances = 0; | |
2068 | dictIterator *di; | |
2069 | dictEntry *de; | |
2070 | mstime_t max_master_down_time; | |
2071 | ||
2072 | max_master_down_time = (mstime() - master->s_down_since_time) + | |
2073 | (master->down_after_period * 10); | |
2074 | ||
2075 | di = dictGetIterator(master->slaves); | |
2076 | while((de = dictNext(di)) != NULL) { | |
2077 | sentinelRedisInstance *slave = dictGetVal(de); | |
2078 | mstime_t info_validity_time = mstime()-SENTINEL_INFO_VALIDITY_TIME; | |
2079 | ||
2080 | if (slave->flags & (SRI_S_DOWN|SRI_O_DOWN|SRI_DISCONNECTED)) continue; | |
2081 | if (slave->last_avail_time < info_validity_time) continue; | |
2082 | if (slave->info_refresh < info_validity_time) continue; | |
2083 | if (slave->master_link_down_time > max_master_down_time) continue; | |
2084 | instance[instances++] = slave; | |
2085 | } | |
2086 | dictReleaseIterator(di); | |
2087 | if (instances) { | |
2088 | qsort(instance,instances,sizeof(sentinelRedisInstance*), | |
2089 | compareSlavesForPromotion); | |
2090 | selected = instance[0]; | |
2091 | } | |
2092 | zfree(instance); | |
2093 | return selected; | |
2094 | } | |
2095 | ||
2096 | /* ---------------- Failover state machine implementation ------------------- */ | |
2097 | void sentinelFailoverWaitStart(sentinelRedisInstance *ri) { | |
2098 | if (mstime() >= ri->failover_start_time) { | |
2099 | ri->failover_state = SENTINEL_FAILOVER_STATE_SELECT_SLAVE; | |
2100 | ri->failover_state_change_time = mstime(); | |
2101 | sentinelEvent(REDIS_WARNING,"+failover-state-select-slave",ri,"%@"); | |
2102 | } | |
2103 | } | |
2104 | ||
2105 | void sentinelFailoverSelectSlave(sentinelRedisInstance *ri) { | |
2106 | sentinelRedisInstance *slave = sentinelSelectSlave(ri); | |
2107 | ||
2108 | if (slave == NULL) { | |
2109 | sentinelEvent(REDIS_WARNING,"-no-good-slave",ri, | |
2110 | "%@ #retrying in %d seconds", | |
2111 | (SENTINEL_FAILOVER_FIXED_DELAY+ | |
2112 | SENTINEL_FAILOVER_MAX_RANDOM_DELAY)/1000); | |
2113 | ri->failover_state = SENTINEL_FAILOVER_STATE_WAIT_START; | |
2114 | ri->failover_start_time = mstime() + SENTINEL_FAILOVER_FIXED_DELAY + | |
2115 | SENTINEL_FAILOVER_MAX_RANDOM_DELAY; | |
2116 | } else { | |
2117 | sentinelEvent(REDIS_WARNING,"+selected-slave",slave,"%@"); | |
2118 | slave->flags |= SRI_PROMOTED; | |
2119 | ri->promoted_slave = slave; | |
2120 | ri->failover_state = SENTINEL_FAILOVER_STATE_SEND_SLAVEOF_NOONE; | |
2121 | ri->failover_state_change_time = mstime(); | |
2122 | sentinelEvent(REDIS_NOTICE,"+failover-state-send-slaveof-noone", | |
2123 | slave, "%@"); | |
2124 | } | |
2125 | } | |
2126 | ||
2127 | void sentinelFailoverSendSlaveOfNoOne(sentinelRedisInstance *ri) { | |
2128 | int retval; | |
2129 | ||
2130 | if (ri->promoted_slave->flags & SRI_DISCONNECTED) return; | |
2131 | ||
2132 | /* Send SLAVEOF NO ONE command to turn the slave into a master. | |
2133 | * We actually register a generic callback for this command as we don't | |
2134 | * really care about the reply. We check if it worked indirectly observing | |
2135 | * if INFO returns a different role (master instead of slave). */ | |
2136 | retval = redisAsyncCommand(ri->promoted_slave->cc, | |
2137 | sentinelDiscardReplyCallback, NULL, "SLAVEOF NO ONE"); | |
2138 | if (retval != REDIS_OK) return; | |
2139 | ri->promoted_slave->pending_commands++; | |
2140 | sentinelEvent(REDIS_NOTICE, "+failover-state-wait-promotion", | |
2141 | ri->promoted_slave,"%@"); | |
2142 | ri->failover_state = SENTINEL_FAILOVER_STATE_WAIT_PROMOTION; | |
2143 | ri->failover_state_change_time = mstime(); | |
2144 | } | |
2145 | ||
2146 | /* We actually wait for promotion indirectly checking with INFO when the | |
2147 | * slave turns into a master. */ | |
2148 | void sentinelFailoverWaitPromotion(sentinelRedisInstance *ri) { | |
2149 | mstime_t elapsed = mstime() - ri->failover_state_change_time; | |
2150 | ||
2151 | if (elapsed >= SENTINEL_PROMOTION_RETRY_PERIOD) { | |
2152 | sentinelEvent(REDIS_WARNING,"-promotion-timeout",ri->promoted_slave, | |
2153 | "%@"); | |
2154 | sentinelEvent(REDIS_WARNING,"+failover-state-select-slave",ri,"%@"); | |
2155 | ri->failover_state = SENTINEL_FAILOVER_STATE_SELECT_SLAVE; | |
2156 | ri->failover_state_change_time = mstime(); | |
2157 | ri->promoted_slave->flags &= ~SRI_PROMOTED; | |
2158 | ri->promoted_slave = NULL; | |
2159 | } | |
2160 | } | |
2161 | ||
2162 | void sentinelFailoverDetectEnd(sentinelRedisInstance *master) { | |
2163 | int not_reconfigured = 0, timeout = 0; | |
2164 | dictIterator *di; | |
2165 | dictEntry *de; | |
2166 | mstime_t elapsed = mstime() - master->failover_state_change_time; | |
2167 | ||
2168 | /* We can't consider failover finished if the promoted slave is | |
2169 | * not reachable. */ | |
2170 | if (master->promoted_slave == NULL || | |
2171 | master->promoted_slave->flags & SRI_S_DOWN) return; | |
2172 | ||
2173 | /* The failover terminates once all the reachable slaves are properly | |
2174 | * configured. */ | |
2175 | di = dictGetIterator(master->slaves); | |
2176 | while((de = dictNext(di)) != NULL) { | |
2177 | sentinelRedisInstance *slave = dictGetVal(de); | |
2178 | ||
2179 | if (slave->flags & (SRI_PROMOTED|SRI_RECONF_DONE)) continue; | |
2180 | if (slave->flags & SRI_S_DOWN) continue; | |
2181 | not_reconfigured++; | |
2182 | } | |
2183 | dictReleaseIterator(di); | |
2184 | ||
2185 | /* Force end of failover on timeout. */ | |
2186 | if (elapsed > master->failover_timeout) { | |
2187 | not_reconfigured = 0; | |
2188 | timeout = 1; | |
2189 | sentinelEvent(REDIS_WARNING,"+failover-end-for-timeout",master,"%@"); | |
2190 | } | |
2191 | ||
2192 | if (not_reconfigured == 0) { | |
2193 | sentinelEvent(REDIS_WARNING,"+failover-end",master,"%@"); | |
2194 | master->failover_state = SENTINEL_FAILOVER_STATE_UPDATE_CONFIG; | |
2195 | master->failover_state_change_time = mstime(); | |
2196 | } | |
2197 | ||
2198 | /* If I'm the leader it is a good idea to send a best effort SLAVEOF | |
2199 | * command to all the slaves still not reconfigured to replicate with | |
2200 | * the new master. */ | |
2201 | if (timeout && (master->flags & SRI_I_AM_THE_LEADER)) { | |
2202 | dictIterator *di; | |
2203 | dictEntry *de; | |
2204 | char master_port[32]; | |
2205 | ||
2206 | ll2string(master_port,sizeof(master_port), | |
2207 | master->promoted_slave->addr->port); | |
2208 | ||
2209 | di = dictGetIterator(master->slaves); | |
2210 | while((de = dictNext(di)) != NULL) { | |
2211 | sentinelRedisInstance *slave = dictGetVal(de); | |
2212 | int retval; | |
2213 | ||
2214 | if (slave->flags & | |
2215 | (SRI_RECONF_DONE|SRI_RECONF_SENT|SRI_DISCONNECTED)) continue; | |
2216 | ||
2217 | retval = redisAsyncCommand(slave->cc, | |
2218 | sentinelDiscardReplyCallback, NULL, "SLAVEOF %s %s", | |
2219 | master->promoted_slave->addr->ip, | |
2220 | master_port); | |
2221 | if (retval == REDIS_OK) { | |
2222 | sentinelEvent(REDIS_NOTICE,"+slave-reconf-sent-be",slave,"%@"); | |
2223 | slave->flags |= SRI_RECONF_SENT; | |
2224 | } | |
2225 | } | |
2226 | dictReleaseIterator(di); | |
2227 | } | |
2228 | } | |
2229 | ||
2230 | /* Send SLAVE OF <new master address> to all the remaining slaves that | |
2231 | * still don't appear to have the configuration updated. */ | |
2232 | void sentinelFailoverReconfNextSlave(sentinelRedisInstance *master) { | |
2233 | dictIterator *di; | |
2234 | dictEntry *de; | |
2235 | int in_progress = 0; | |
2236 | ||
2237 | di = dictGetIterator(master->slaves); | |
2238 | while((de = dictNext(di)) != NULL) { | |
2239 | sentinelRedisInstance *slave = dictGetVal(de); | |
2240 | ||
2241 | if (slave->flags & (SRI_RECONF_SENT|SRI_RECONF_INPROG)) | |
2242 | in_progress++; | |
2243 | } | |
2244 | dictReleaseIterator(di); | |
2245 | ||
2246 | di = dictGetIterator(master->slaves); | |
2247 | while(in_progress < master->parallel_syncs && | |
2248 | (de = dictNext(di)) != NULL) | |
2249 | { | |
2250 | sentinelRedisInstance *slave = dictGetVal(de); | |
2251 | int retval; | |
2252 | char master_port[32]; | |
2253 | ||
2254 | /* Skip the promoted slave, and already configured slaves. */ | |
2255 | if (slave->flags & (SRI_PROMOTED|SRI_RECONF_DONE)) continue; | |
2256 | ||
2257 | /* Clear the SRI_RECONF_SENT flag if too much time elapsed without | |
2258 | * the slave moving forward to the next state. */ | |
2259 | if ((slave->flags & SRI_RECONF_SENT) && | |
2260 | (mstime() - slave->slave_reconf_sent_time) > | |
2261 | SENTINEL_SLAVE_RECONF_RETRY_PERIOD) | |
2262 | { | |
2263 | sentinelEvent(REDIS_NOTICE,"-slave-reconf-sent-timeout",slave,"%@"); | |
2264 | slave->flags &= ~SRI_RECONF_SENT; | |
2265 | } | |
2266 | ||
2267 | /* Nothing to do for instances that are disconnected or already | |
2268 | * in RECONF_SENT state. */ | |
2269 | if (slave->flags & (SRI_DISCONNECTED|SRI_RECONF_SENT|SRI_RECONF_INPROG)) | |
2270 | continue; | |
2271 | ||
2272 | /* Send SLAVEOF <new master>. */ | |
2273 | ll2string(master_port,sizeof(master_port), | |
2274 | master->promoted_slave->addr->port); | |
2275 | retval = redisAsyncCommand(slave->cc, | |
2276 | sentinelDiscardReplyCallback, NULL, "SLAVEOF %s %s", | |
2277 | master->promoted_slave->addr->ip, | |
2278 | master_port); | |
2279 | if (retval == REDIS_OK) { | |
2280 | slave->flags |= SRI_RECONF_SENT; | |
2281 | slave->pending_commands++; | |
2282 | slave->slave_reconf_sent_time = mstime(); | |
2283 | sentinelEvent(REDIS_NOTICE,"+slave-reconf-sent",slave,"%@"); | |
2284 | in_progress++; | |
2285 | } | |
2286 | } | |
2287 | dictReleaseIterator(di); | |
2288 | sentinelFailoverDetectEnd(master); | |
2289 | } | |
2290 | ||
2291 | /* This function is called when the slave is in | |
2292 | * SENTINEL_FAILOVER_STATE_UPDATE_CONFIG state. In this state we need | |
2293 | * to remove it from the master table and add the promoted slave instead. | |
2294 | * | |
2295 | * If there are no promoted slaves as this instance is unique, we remove | |
2296 | * and re-add it with the same address to trigger a complete state | |
2297 | * refresh. */ | |
2298 | void sentinelFailoverSwitchToPromotedSlave(sentinelRedisInstance *master) { | |
e47236d8 | 2299 | sentinelRedisInstance *ref = master->promoted_slave ? |
2300 | master->promoted_slave : master; | |
2301 | ||
2302 | sentinelEvent(REDIS_WARNING,"+switch-master",master,"%s %s %d %s %d", | |
2303 | master->name, master->addr->ip, master->addr->port, | |
2304 | ref->addr->ip, ref->addr->port); | |
2305 | ||
2306 | sentinelResetMasterAndChangeAddress(master,ref->addr->ip,ref->addr->port); | |
120ba392 | 2307 | } |
2308 | ||
2309 | void sentinelFailoverStateMachine(sentinelRedisInstance *ri) { | |
2310 | redisAssert(ri->flags & SRI_MASTER); | |
2311 | ||
2312 | if (!(ri->flags & SRI_FAILOVER_IN_PROGRESS)) return; | |
2313 | ||
2314 | switch(ri->failover_state) { | |
2315 | case SENTINEL_FAILOVER_STATE_WAIT_START: | |
2316 | sentinelFailoverWaitStart(ri); | |
2317 | break; | |
2318 | case SENTINEL_FAILOVER_STATE_SELECT_SLAVE: | |
2319 | sentinelFailoverSelectSlave(ri); | |
2320 | break; | |
2321 | case SENTINEL_FAILOVER_STATE_SEND_SLAVEOF_NOONE: | |
2322 | sentinelFailoverSendSlaveOfNoOne(ri); | |
2323 | break; | |
2324 | case SENTINEL_FAILOVER_STATE_WAIT_PROMOTION: | |
2325 | sentinelFailoverWaitPromotion(ri); | |
2326 | break; | |
2327 | case SENTINEL_FAILOVER_STATE_RECONF_SLAVES: | |
2328 | sentinelFailoverReconfNextSlave(ri); | |
2329 | break; | |
2330 | case SENTINEL_FAILOVER_STATE_DETECT_END: | |
2331 | sentinelFailoverDetectEnd(ri); | |
2332 | break; | |
2333 | } | |
2334 | } | |
2335 | ||
2336 | /* The following is called only for master instances and will abort the | |
2337 | * failover process if: | |
2338 | * | |
2339 | * 1) The failover is in progress. | |
2340 | * 2) We already promoted a slave. | |
2341 | * 3) The promoted slave is in extended SDOWN condition. | |
2342 | */ | |
2343 | void sentinelAbortFailoverIfNeeded(sentinelRedisInstance *ri) { | |
2344 | dictIterator *di; | |
2345 | dictEntry *de; | |
2346 | ||
2347 | /* Failover is in progress? Do we have a promoted slave? */ | |
2348 | if (!(ri->flags & SRI_FAILOVER_IN_PROGRESS) || !ri->promoted_slave) return; | |
2349 | ||
2350 | /* Is the promoted slave into an extended SDOWN state? */ | |
2351 | if (!(ri->promoted_slave->flags & SRI_S_DOWN) || | |
2352 | (mstime() - ri->promoted_slave->s_down_since_time) < | |
2353 | (ri->down_after_period * SENTINEL_EXTENDED_SDOWN_MULTIPLIER)) return; | |
2354 | ||
2355 | sentinelEvent(REDIS_WARNING,"-failover-abort-x-sdown",ri->promoted_slave,"%@"); | |
2356 | ||
2357 | /* Clear failover related flags from slaves. | |
2358 | * Also if we are the leader make sure to send SLAVEOF commands to all the | |
2359 | * already reconfigured slaves in order to turn them back into slaves of | |
2360 | * the original master. */ | |
2361 | ||
2362 | di = dictGetIterator(ri->slaves); | |
2363 | while((de = dictNext(di)) != NULL) { | |
2364 | sentinelRedisInstance *slave = dictGetVal(de); | |
2365 | if (ri->flags & SRI_I_AM_THE_LEADER) { | |
2366 | char master_port[32]; | |
2367 | int retval; | |
2368 | ||
2369 | ll2string(master_port,sizeof(master_port),ri->addr->port); | |
2370 | retval = redisAsyncCommand(slave->cc, | |
2371 | sentinelDiscardReplyCallback, NULL, "SLAVEOF %s %s", | |
2372 | ri->addr->ip, | |
2373 | master_port); | |
2374 | if (retval == REDIS_OK) | |
2375 | sentinelEvent(REDIS_NOTICE,"-slave-reconf-undo",slave,"%@"); | |
2376 | } | |
2377 | slave->flags &= ~(SRI_RECONF_SENT|SRI_RECONF_INPROG|SRI_RECONF_DONE); | |
2378 | } | |
2379 | dictReleaseIterator(di); | |
2380 | ||
2381 | ri->flags &= ~(SRI_FAILOVER_IN_PROGRESS|SRI_I_AM_THE_LEADER); | |
2382 | ri->failover_state = SENTINEL_FAILOVER_STATE_NONE; | |
2383 | ri->failover_state_change_time = mstime(); | |
2384 | ri->promoted_slave->flags &= ~SRI_PROMOTED; | |
2385 | ri->promoted_slave = NULL; | |
2386 | } | |
2387 | ||
2388 | /* ======================== SENTINEL timer handler ========================== | |
2389 | * This is the "main" our Sentinel, being sentinel completely non blocking | |
2390 | * in design. The function is called every second. | |
2391 | * -------------------------------------------------------------------------- */ | |
2392 | ||
2393 | /* Perform scheduled operations for the specified Redis instance. */ | |
2394 | void sentinelHandleRedisInstance(sentinelRedisInstance *ri) { | |
2395 | /* ========== MONITORING HALF ============ */ | |
2396 | /* Every kind of instance */ | |
2397 | sentinelReconnectInstance(ri); | |
2398 | sentinelPingInstance(ri); | |
2399 | ||
2400 | /* Masters and slaves */ | |
2401 | if (ri->flags & (SRI_MASTER|SRI_SLAVE)) { | |
2402 | /* Nothing so far. */ | |
2403 | } | |
2404 | ||
2405 | /* Only masters */ | |
2406 | if (ri->flags & SRI_MASTER) { | |
2407 | sentinelAskMasterStateToOtherSentinels(ri); | |
2408 | } | |
2409 | ||
2410 | /* ============== ACTING HALF ============= */ | |
2411 | /* We don't proceed with the acting half if we are in TILT mode. | |
2412 | * TILT happens when we find something odd with the time, like a | |
2413 | * sudden change in the clock. */ | |
2414 | if (sentinel.tilt) { | |
2415 | if (mstime()-sentinel.tilt_start_time < SENTINEL_TILT_PERIOD) return; | |
2416 | sentinel.tilt = 0; | |
2417 | sentinelEvent(REDIS_WARNING,"-tilt",NULL,"#tilt mode exited"); | |
2418 | } | |
2419 | ||
2420 | /* Every kind of instance */ | |
2421 | sentinelCheckSubjectivelyDown(ri); | |
2422 | ||
2423 | /* Masters and slaves */ | |
2424 | if (ri->flags & (SRI_MASTER|SRI_SLAVE)) { | |
2425 | /* Nothing so far. */ | |
2426 | } | |
2427 | ||
2428 | /* Only masters */ | |
2429 | if (ri->flags & SRI_MASTER) { | |
2430 | sentinelCheckObjectivelyDown(ri); | |
2431 | sentinelStartFailover(ri); | |
2432 | sentinelFailoverStateMachine(ri); | |
2433 | sentinelAbortFailoverIfNeeded(ri); | |
2434 | } | |
2435 | } | |
2436 | ||
2437 | /* Perform scheduled operations for all the instances in the dictionary. | |
2438 | * Recursively call the function against dictionaries of slaves. */ | |
2439 | void sentinelHandleDictOfRedisInstances(dict *instances) { | |
2440 | dictIterator *di; | |
2441 | dictEntry *de; | |
2442 | sentinelRedisInstance *switch_to_promoted = NULL; | |
2443 | ||
2444 | /* There are a number of things we need to perform against every master. */ | |
2445 | di = dictGetIterator(instances); | |
2446 | while((de = dictNext(di)) != NULL) { | |
2447 | sentinelRedisInstance *ri = dictGetVal(de); | |
2448 | ||
2449 | sentinelHandleRedisInstance(ri); | |
2450 | if (ri->flags & SRI_MASTER) { | |
2451 | sentinelHandleDictOfRedisInstances(ri->slaves); | |
2452 | sentinelHandleDictOfRedisInstances(ri->sentinels); | |
2453 | if (ri->failover_state == SENTINEL_FAILOVER_STATE_UPDATE_CONFIG) { | |
2454 | switch_to_promoted = ri; | |
2455 | } | |
2456 | } | |
2457 | } | |
2458 | if (switch_to_promoted) | |
2459 | sentinelFailoverSwitchToPromotedSlave(switch_to_promoted); | |
2460 | dictReleaseIterator(di); | |
2461 | } | |
2462 | ||
2463 | /* This function checks if we need to enter the TITL mode. | |
2464 | * | |
2465 | * The TILT mode is entered if we detect that between two invocations of the | |
2466 | * timer interrupt, a negative amount of time, or too much time has passed. | |
2467 | * Note that we expect that more or less just 100 milliseconds will pass | |
2468 | * if everything is fine. However we'll see a negative number or a | |
2469 | * difference bigger than SENTINEL_TILT_TRIGGER milliseconds if one of the | |
2470 | * following conditions happen: | |
2471 | * | |
2472 | * 1) The Sentiel process for some time is blocked, for every kind of | |
2473 | * random reason: the load is huge, the computer was freezed for some time | |
2474 | * in I/O or alike, the process was stopped by a signal. Everything. | |
2475 | * 2) The system clock was altered significantly. | |
2476 | * | |
2477 | * Under both this conditions we'll see everything as timed out and failing | |
2478 | * without good reasons. Instead we enter the TILT mode and wait | |
2479 | * for SENTIENL_TILT_PERIOD to elapse before starting to act again. | |
2480 | * | |
2481 | * During TILT time we still collect information, we just do not act. */ | |
2482 | void sentinelCheckTiltCondition(void) { | |
2483 | mstime_t now = mstime(); | |
2484 | mstime_t delta = now - sentinel.previous_time; | |
2485 | ||
2486 | if (delta < 0 || delta > SENTINEL_TILT_TRIGGER) { | |
2487 | sentinel.tilt = 1; | |
2488 | sentinel.tilt_start_time = mstime(); | |
2489 | sentinelEvent(REDIS_WARNING,"+tilt",NULL,"#tilt mode entered"); | |
2490 | } | |
2491 | sentinel.previous_time = mstime(); | |
2492 | } | |
2493 | ||
2494 | void sentinelTimer(void) { | |
2495 | sentinelCheckTiltCondition(); | |
2496 | sentinelHandleDictOfRedisInstances(sentinel.masters); | |
2497 | } | |
2498 |