]> git.saurik.com Git - redis.git/blob - src/sentinel.c
Sentinel: debugging message removed.
[redis.git] / src / sentinel.c
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
113 /* Generic flags that can be used with different functions. */
114 #define SENTINEL_NO_FLAGS 0
115 #define SENTINEL_GENERATE_EVENT 1
116
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);
291 void sentinelKillLink(sentinelRedisInstance *ri, redisAsyncContext *c);
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
603 /* Release hiredis connections. */
604 if (ri->cc) sentinelKillLink(ri,ri->cc);
605 if (ri->pc) sentinelKillLink(ri,ri->pc);
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 */
760 void sentinelResetMaster(sentinelRedisInstance *ri, int flags) {
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);
766 if (ri->cc) sentinelKillLink(ri,ri->cc);
767 if (ri->pc) sentinelKillLink(ri,ri->pc);
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;
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,"%@");
783 }
784
785 /* Call sentinelResetMaster() on every master with a name matching the specified
786 * pattern. */
787 int sentinelResetMastersByPattern(char *pattern, int flags) {
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)) {
798 sentinelResetMaster(ri,flags);
799 reset++;
800 }
801 }
802 }
803 dictReleaseIterator(di);
804 return reset;
805 }
806
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
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
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
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;
906 int pubsub;
907
908 if (ri == NULL) return; /* The instance no longer exists. */
909
910 pubsub = (ri->pc == c);
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) {
933 sentinelDisconnectInstanceFromContext(c);
934 }
935
936 /* Create the async connections for the specified instance if the instance
937 * is disconnected. Note that the SRI_DISCONNECTED flag is set even if just
938 * one of the two links (commands and pub/sub) is missing. */
939 void sentinelReconnectInstance(sentinelRedisInstance *ri) {
940 if (!(ri->flags & SRI_DISCONNECTED)) return;
941
942 /* Commands connection. */
943 if (ri->cc == NULL) {
944 ri->cc = redisAsyncConnect(ri->addr->ip,ri->addr->port);
945 if (ri->cc->err) {
946 sentinelEvent(REDIS_DEBUG,"-cmd-link-reconnection",ri,"%@ #%s",
947 ri->cc->errstr);
948 sentinelKillLink(ri,ri->cc);
949 } else {
950 ri->cc_conn_time = mstime();
951 ri->cc->data = ri;
952 redisAeAttach(server.el,ri->cc);
953 redisAsyncSetConnectCallback(ri->cc,
954 sentinelLinkEstablishedCallback);
955 redisAsyncSetDisconnectCallback(ri->cc,
956 sentinelDisconnectCallback);
957 }
958 }
959 /* Pub / Sub */
960 if ((ri->flags & SRI_MASTER) && ri->pc == NULL) {
961 ri->pc = redisAsyncConnect(ri->addr->ip,ri->addr->port);
962 if (ri->pc->err) {
963 sentinelEvent(REDIS_DEBUG,"-pubsub-link-reconnection",ri,"%@ #%s",
964 ri->pc->errstr);
965 sentinelKillLink(ri,ri->pc);
966 } else {
967 int retval;
968
969 ri->pc_conn_time = mstime();
970 ri->pc->data = ri;
971 redisAeAttach(server.el,ri->pc);
972 redisAsyncSetConnectCallback(ri->pc,
973 sentinelLinkEstablishedCallback);
974 redisAsyncSetDisconnectCallback(ri->pc,
975 sentinelDisconnectCallback);
976 /* Now we subscribe to the Sentinels "Hello" channel. */
977 retval = redisAsyncCommand(ri->pc,
978 sentinelReceiveHelloMessages, NULL, "SUBSCRIBE %s",
979 SENTINEL_HELLO_CHANNEL);
980 if (retval != REDIS_OK) {
981 /* If we can't subscribe, the Pub/Sub connection is useless
982 * and we can simply disconnect it and try again. */
983 sentinelKillLink(ri,ri->pc);
984 return;
985 }
986 }
987 }
988 /* Clear the DISCONNECTED flags only if we have both the connections
989 * (or just the commands connection if this is a slave or a
990 * sentinel instance). */
991 if (ri->cc && (ri->flags & (SRI_SLAVE|SRI_SENTINEL) || ri->pc))
992 ri->flags &= ~SRI_DISCONNECTED;
993 }
994
995 /* ======================== Redis instances pinging ======================== */
996
997 /* Process the INFO output from masters. */
998 void sentinelRefreshInstanceInfo(sentinelRedisInstance *ri, const char *info) {
999 sds *lines;
1000 int numlines, j;
1001 int role = 0;
1002 int runid_changed = 0; /* true if runid changed. */
1003 int first_runid = 0; /* true if this is the first runid we receive. */
1004
1005 /* The following fields must be reset to a given value in the case they
1006 * are not found at all in the INFO output. */
1007 ri->master_link_down_time = 0;
1008
1009 /* Process line by line. */
1010 lines = sdssplitlen(info,strlen(info),"\r\n",2,&numlines);
1011 for (j = 0; j < numlines; j++) {
1012 sentinelRedisInstance *slave;
1013 sds l = lines[j];
1014
1015 /* run_id:<40 hex chars>*/
1016 if (sdslen(l) >= 47 && !memcmp(l,"run_id:",7)) {
1017 if (ri->runid == NULL) {
1018 ri->runid = sdsnewlen(l+7,40);
1019 first_runid = 1;
1020 } else {
1021 if (strncmp(ri->runid,l+7,40) != 0) {
1022 runid_changed = 1;
1023 sentinelEvent(REDIS_NOTICE,"+reboot",ri,"%@");
1024 sdsfree(ri->runid);
1025 ri->runid = sdsnewlen(l+7,40);
1026 }
1027 }
1028 }
1029
1030 /* slave0:<ip>,<port>,<state> */
1031 if ((ri->flags & SRI_MASTER) &&
1032 sdslen(l) >= 7 &&
1033 !memcmp(l,"slave",5) && isdigit(l[5]))
1034 {
1035 char *ip, *port, *end;
1036
1037 ip = strchr(l,':'); if (!ip) continue;
1038 ip++; /* Now ip points to start of ip address. */
1039 port = strchr(ip,','); if (!port) continue;
1040 *port = '\0'; /* nul term for easy access. */
1041 port++; /* Now port points to start of port number. */
1042 end = strchr(port,','); if (!end) continue;
1043 *end = '\0'; /* nul term for easy access. */
1044
1045 /* Check if we already have this slave into our table,
1046 * otherwise add it. */
1047 if (sentinelRedisInstanceLookupSlave(ri,ip,atoi(port)) == NULL) {
1048 if ((slave = createSentinelRedisInstance(NULL,SRI_SLAVE,ip,
1049 atoi(port), ri->quorum,ri)) != NULL)
1050 {
1051 sentinelEvent(REDIS_NOTICE,"+slave",slave,"%@");
1052 }
1053 }
1054 }
1055
1056 /* master_link_down_since_seconds:<seconds> */
1057 if (sdslen(l) >= 32 &&
1058 !memcmp(l,"master_link_down_since_seconds",30))
1059 {
1060 ri->master_link_down_time = strtoll(l+31,NULL,10)*1000;
1061 }
1062
1063 /* role:<role> */
1064 if (!memcmp(l,"role:master",11)) role = SRI_MASTER;
1065 else if (!memcmp(l,"role:slave",10)) role = SRI_SLAVE;
1066
1067 if (role == SRI_SLAVE) {
1068 /* master_host:<host> */
1069 if (sdslen(l) >= 12 && !memcmp(l,"master_host:",12)) {
1070 sdsfree(ri->slave_master_host);
1071 ri->slave_master_host = sdsnew(l+12);
1072 }
1073
1074 /* master_port:<port> */
1075 if (sdslen(l) >= 12 && !memcmp(l,"master_port:",12))
1076 ri->slave_master_port = atoi(l+12);
1077
1078 /* master_link_status:<status> */
1079 if (sdslen(l) >= 19 && !memcmp(l,"master_link_status:",19)) {
1080 ri->slave_master_link_status =
1081 (strcasecmp(l+19,"up") == 0) ?
1082 SENTINEL_MASTER_LINK_STATUS_UP :
1083 SENTINEL_MASTER_LINK_STATUS_DOWN;
1084 }
1085 }
1086 }
1087 ri->info_refresh = mstime();
1088 sdsfreesplitres(lines,numlines);
1089
1090 if (sentinel.tilt) return;
1091
1092 /* Act if a master turned into a slave. */
1093 if ((ri->flags & SRI_MASTER) && role == SRI_SLAVE) {
1094 if (first_runid && ri->slave_master_host) {
1095 /* If it is the first time we receive INFO from it, but it's
1096 * a slave while it was configured as a master, we want to monitor
1097 * its master instead. */
1098 sentinelEvent(REDIS_WARNING,"+redirect-to-master",ri,
1099 "%s %s %d %s %d",
1100 ri->name, ri->addr->ip, ri->addr->port,
1101 ri->slave_master_host, ri->slave_master_port);
1102 sentinelResetMasterAndChangeAddress(ri,ri->slave_master_host,
1103 ri->slave_master_port);
1104 return;
1105 }
1106 }
1107
1108 /* Act if a slave turned into a master. */
1109 if ((ri->flags & SRI_SLAVE) && role == SRI_MASTER) {
1110 if (!(ri->master->flags & SRI_FAILOVER_IN_PROGRESS) &&
1111 (runid_changed || first_runid))
1112 {
1113 /* If a slave turned into a master, but at the same time the
1114 * runid has changed, or it is simply the first time we see and
1115 * INFO output from this instance, this is a reboot with a wrong
1116 * configuration.
1117 *
1118 * Log the event and remove the slave. */
1119 int retval;
1120
1121 sentinelEvent(REDIS_WARNING,"-slave-restart-as-master",ri,"%@ #removing it from the attached slaves");
1122 retval = dictDelete(ri->master->slaves,ri->name);
1123 redisAssert(retval == REDIS_OK);
1124 return;
1125 } else if (ri->flags & SRI_PROMOTED) {
1126 /* If this is a promoted slave we can change state to the
1127 * failover state machine. */
1128 if (ri->master &&
1129 (ri->master->flags & SRI_FAILOVER_IN_PROGRESS) &&
1130 (ri->master->flags & SRI_I_AM_THE_LEADER) &&
1131 (ri->master->failover_state ==
1132 SENTINEL_FAILOVER_STATE_WAIT_PROMOTION))
1133 {
1134 ri->master->failover_state = SENTINEL_FAILOVER_STATE_RECONF_SLAVES;
1135 ri->master->failover_state_change_time = mstime();
1136 sentinelEvent(REDIS_WARNING,"+promoted-slave",ri,"%@");
1137 sentinelEvent(REDIS_WARNING,"+failover-state-reconf-slaves",
1138 ri->master,"%@");
1139 }
1140 } else {
1141 /* Otherwise we interpret this as the start of the failover. */
1142 if (ri->master &&
1143 (ri->master->flags & SRI_FAILOVER_IN_PROGRESS) == 0)
1144 {
1145 ri->master->flags |= SRI_FAILOVER_IN_PROGRESS;
1146 sentinelEvent(REDIS_WARNING,"failover-detected",ri->master,"%@");
1147 ri->master->failover_state = SENTINEL_FAILOVER_STATE_DETECT_END;
1148 ri->master->failover_state_change_time = mstime();
1149 ri->master->promoted_slave = ri;
1150 ri->flags |= SRI_PROMOTED;
1151 /* We are an observer, so we can only assume that the leader
1152 * is reconfiguring the slave instances. For this reason we
1153 * set all the instances as RECONF_SENT waiting for progresses
1154 * on this side. */
1155 sentinelAddFlagsToDictOfRedisInstances(ri->master->slaves,
1156 SRI_RECONF_SENT);
1157 }
1158 }
1159 }
1160
1161 /* Detect if the slave that is in the process of being reconfigured
1162 * changed state. */
1163 if ((ri->flags & SRI_SLAVE) && role == SRI_SLAVE &&
1164 (ri->flags & (SRI_RECONF_SENT|SRI_RECONF_INPROG)))
1165 {
1166 /* SRI_RECONF_SENT -> SRI_RECONF_INPROG. */
1167 if ((ri->flags & SRI_RECONF_SENT) &&
1168 ri->slave_master_host &&
1169 strcmp(ri->slave_master_host,
1170 ri->master->promoted_slave->addr->ip) == 0 &&
1171 ri->slave_master_port == ri->master->promoted_slave->addr->port)
1172 {
1173 ri->flags &= ~SRI_RECONF_SENT;
1174 ri->flags |= SRI_RECONF_INPROG;
1175 sentinelEvent(REDIS_NOTICE,"+slave-reconf-inprog",ri,"%@");
1176 }
1177
1178 /* SRI_RECONF_INPROG -> SRI_RECONF_DONE */
1179 if ((ri->flags & SRI_RECONF_INPROG) &&
1180 ri->slave_master_link_status == SENTINEL_MASTER_LINK_STATUS_UP)
1181 {
1182 ri->flags &= ~SRI_RECONF_INPROG;
1183 ri->flags |= SRI_RECONF_DONE;
1184 sentinelEvent(REDIS_NOTICE,"+slave-reconf-done",ri,"%@");
1185 /* If we are moving forward (a new slave is now configured)
1186 * we update the change_time as we are conceptually passing
1187 * to the next slave. */
1188 ri->failover_state_change_time = mstime();
1189 }
1190 }
1191 }
1192
1193 void sentinelInfoReplyCallback(redisAsyncContext *c, void *reply, void *privdata) {
1194 sentinelRedisInstance *ri = c->data;
1195 redisReply *r;
1196
1197 if (ri) ri->pending_commands--;
1198 if (!reply || !ri) return;
1199 r = reply;
1200
1201 if (r->type == REDIS_REPLY_STRING) {
1202 sentinelRefreshInstanceInfo(ri,r->str);
1203 }
1204 }
1205
1206 /* Just discard the reply. We use this when we are not monitoring the return
1207 * value of the command but its effects directly. */
1208 void sentinelDiscardReplyCallback(redisAsyncContext *c, void *reply, void *privdata) {
1209 sentinelRedisInstance *ri = c->data;
1210
1211 if (ri) ri->pending_commands--;
1212 }
1213
1214 void sentinelPingReplyCallback(redisAsyncContext *c, void *reply, void *privdata) {
1215 sentinelRedisInstance *ri = c->data;
1216 redisReply *r;
1217
1218 if (ri) ri->pending_commands--;
1219 if (!reply || !ri) return;
1220 r = reply;
1221
1222 if (r->type == REDIS_REPLY_STATUS ||
1223 r->type == REDIS_REPLY_ERROR) {
1224 /* Update the "instance available" field only if this is an
1225 * acceptable reply. */
1226 if (strncmp(r->str,"PONG",4) == 0 ||
1227 strncmp(r->str,"LOADING",7) == 0 ||
1228 strncmp(r->str,"MASTERDOWN",10) == 0)
1229 {
1230 ri->last_avail_time = mstime();
1231 }
1232 }
1233 ri->last_pong_time = mstime();
1234 }
1235
1236 /* This is called when we get the reply about the PUBLISH command we send
1237 * to the master to advertise this sentinel. */
1238 void sentinelPublishReplyCallback(redisAsyncContext *c, void *reply, void *privdata) {
1239 sentinelRedisInstance *ri = c->data;
1240 redisReply *r;
1241
1242 if (ri) ri->pending_commands--;
1243 if (!reply || !ri) return;
1244 r = reply;
1245
1246 /* Only update pub_time if we actually published our message. Otherwise
1247 * we'll retry against in 100 milliseconds. */
1248 if (r->type != REDIS_REPLY_ERROR)
1249 ri->last_pub_time = mstime();
1250 }
1251
1252 /* This is our Pub/Sub callback for the Hello channel. It's useful in order
1253 * to discover other sentinels attached at the same master. */
1254 void sentinelReceiveHelloMessages(redisAsyncContext *c, void *reply, void *privdata) {
1255 sentinelRedisInstance *ri = c->data;
1256 redisReply *r;
1257
1258 if (!reply || !ri) return;
1259 r = reply;
1260
1261 /* Update the last activity in the pubsub channel. Note that since we
1262 * receive our messages as well this timestamp can be used to detect
1263 * if the link is probably diconnected even if it seems otherwise. */
1264 ri->pc_last_activity = mstime();
1265
1266 /* Sanity check in the reply we expect, so that the code that follows
1267 * can avoid to check for details. */
1268 if (r->type != REDIS_REPLY_ARRAY ||
1269 r->elements != 3 ||
1270 r->element[0]->type != REDIS_REPLY_STRING ||
1271 r->element[1]->type != REDIS_REPLY_STRING ||
1272 r->element[2]->type != REDIS_REPLY_STRING ||
1273 strcmp(r->element[0]->str,"message") != 0) return;
1274
1275 /* We are not interested in meeting ourselves */
1276 if (strstr(r->element[2]->str,server.runid) != NULL) return;
1277
1278 {
1279 int numtokens, port, removed, canfailover;
1280 char **token = sdssplitlen(r->element[2]->str,
1281 r->element[2]->len,
1282 ":",1,&numtokens);
1283 sentinelRedisInstance *sentinel;
1284
1285 if (numtokens == 4) {
1286 /* First, try to see if we already have this sentinel. */
1287 port = atoi(token[1]);
1288 canfailover = atoi(token[3]);
1289 sentinel = getSentinelRedisInstanceByAddrAndRunID(
1290 ri->sentinels,token[0],port,token[2]);
1291
1292 if (!sentinel) {
1293 /* If not, remove all the sentinels that have the same runid
1294 * OR the same ip/port, because it's either a restart or a
1295 * network topology change. */
1296 removed = removeMatchingSentinelsFromMaster(ri,token[0],port,
1297 token[2]);
1298 if (removed) {
1299 sentinelEvent(REDIS_NOTICE,"-dup-sentinel",ri,
1300 "%@ #duplicate of %s:%d or %s",
1301 token[0],port,token[2]);
1302 }
1303
1304 /* Add the new sentinel. */
1305 sentinel = createSentinelRedisInstance(NULL,SRI_SENTINEL,
1306 token[0],port,ri->quorum,ri);
1307 if (sentinel) {
1308 sentinelEvent(REDIS_NOTICE,"+sentinel",sentinel,"%@");
1309 /* The runid is NULL after a new instance creation and
1310 * for Sentinels we don't have a later chance to fill it,
1311 * so do it now. */
1312 sentinel->runid = sdsnew(token[2]);
1313 }
1314 }
1315
1316 /* Update the state of the Sentinel. */
1317 if (sentinel) {
1318 sentinel->last_hello_time = mstime();
1319 if (canfailover)
1320 sentinel->flags |= SRI_CAN_FAILOVER;
1321 else
1322 sentinel->flags &= ~SRI_CAN_FAILOVER;
1323 }
1324 }
1325 sdsfreesplitres(token,numtokens);
1326 }
1327 }
1328
1329 void sentinelPingInstance(sentinelRedisInstance *ri) {
1330 mstime_t now = mstime();
1331 mstime_t info_period;
1332 int retval;
1333
1334 /* Return ASAP if we have already a PING or INFO already pending, or
1335 * in the case the instance is not properly connected. */
1336 if (ri->flags & SRI_DISCONNECTED) return;
1337
1338 /* For INFO, PING, PUBLISH that are not critical commands to send we
1339 * also have a limit of SENTINEL_MAX_PENDING_COMMANDS. We don't
1340 * want to use a lot of memory just because a link is not working
1341 * properly (note that anyway there is a redundant protection about this,
1342 * that is, the link will be disconnected and reconnected if a long
1343 * timeout condition is detected. */
1344 if (ri->pending_commands >= SENTINEL_MAX_PENDING_COMMANDS) return;
1345
1346 /* If this is a slave of a master in O_DOWN condition we start sending
1347 * it INFO every second, instead of the usual SENTINEL_INFO_PERIOD
1348 * period. In this state we want to closely monitor slaves in case they
1349 * are turned into masters by another Sentinel, or by the sysadmin. */
1350 if ((ri->flags & SRI_SLAVE) &&
1351 (ri->master->flags & (SRI_O_DOWN|SRI_FAILOVER_IN_PROGRESS))) {
1352 info_period = 1000;
1353 } else {
1354 info_period = SENTINEL_INFO_PERIOD;
1355 }
1356
1357 if ((ri->flags & SRI_SENTINEL) == 0 &&
1358 (ri->info_refresh == 0 ||
1359 (now - ri->info_refresh) > info_period))
1360 {
1361 /* Send INFO to masters and slaves, not sentinels. */
1362 retval = redisAsyncCommand(ri->cc,
1363 sentinelInfoReplyCallback, NULL, "INFO");
1364 if (retval != REDIS_OK) return;
1365 ri->pending_commands++;
1366 } else if ((now - ri->last_pong_time) > SENTINEL_PING_PERIOD) {
1367 /* Send PING to all the three kinds of instances. */
1368 retval = redisAsyncCommand(ri->cc,
1369 sentinelPingReplyCallback, NULL, "PING");
1370 if (retval != REDIS_OK) return;
1371 ri->pending_commands++;
1372 } else if ((ri->flags & SRI_MASTER) &&
1373 (now - ri->last_pub_time) > SENTINEL_PUBLISH_PERIOD)
1374 {
1375 /* PUBLISH hello messages only to masters. */
1376 struct sockaddr_in sa;
1377 socklen_t salen = sizeof(sa);
1378
1379 if (getsockname(ri->cc->c.fd,(struct sockaddr*)&sa,&salen) != -1) {
1380 char myaddr[128];
1381
1382 snprintf(myaddr,sizeof(myaddr),"%s:%d:%s:%d",
1383 inet_ntoa(sa.sin_addr), server.port, server.runid,
1384 (ri->flags & SRI_CAN_FAILOVER) != 0);
1385 retval = redisAsyncCommand(ri->cc,
1386 sentinelPublishReplyCallback, NULL, "PUBLISH %s %s",
1387 SENTINEL_HELLO_CHANNEL,myaddr);
1388 if (retval != REDIS_OK) return;
1389 ri->pending_commands++;
1390 }
1391 }
1392 }
1393
1394 /* =========================== SENTINEL command ============================= */
1395
1396 const char *sentinelFailoverStateStr(int state) {
1397 switch(state) {
1398 case SENTINEL_FAILOVER_STATE_NONE: return "none";
1399 case SENTINEL_FAILOVER_STATE_WAIT_START: return "wait_start";
1400 case SENTINEL_FAILOVER_STATE_SELECT_SLAVE: return "select_slave";
1401 case SENTINEL_FAILOVER_STATE_SEND_SLAVEOF_NOONE: return "send_slaveof_noone";
1402 case SENTINEL_FAILOVER_STATE_WAIT_PROMOTION: return "wait_promotion";
1403 case SENTINEL_FAILOVER_STATE_RECONF_SLAVES: return "reconf_slaves";
1404 case SENTINEL_FAILOVER_STATE_ALERT_CLIENTS: return "alert_clients";
1405 case SENTINEL_FAILOVER_STATE_DETECT_END: return "detect_end";
1406 case SENTINEL_FAILOVER_STATE_UPDATE_CONFIG: return "update_config";
1407 default: return "unknown";
1408 }
1409 }
1410
1411 /* Redis instance to Redis protocol representation. */
1412 void addReplySentinelRedisInstance(redisClient *c, sentinelRedisInstance *ri) {
1413 char *flags = sdsempty();
1414 void *mbl;
1415 int fields = 0;
1416
1417 mbl = addDeferredMultiBulkLength(c);
1418
1419 addReplyBulkCString(c,"name");
1420 addReplyBulkCString(c,ri->name);
1421 fields++;
1422
1423 addReplyBulkCString(c,"ip");
1424 addReplyBulkCString(c,ri->addr->ip);
1425 fields++;
1426
1427 addReplyBulkCString(c,"port");
1428 addReplyBulkLongLong(c,ri->addr->port);
1429 fields++;
1430
1431 addReplyBulkCString(c,"runid");
1432 addReplyBulkCString(c,ri->runid ? ri->runid : "");
1433 fields++;
1434
1435 addReplyBulkCString(c,"flags");
1436 if (ri->flags & SRI_S_DOWN) flags = sdscat(flags,"s_down,");
1437 if (ri->flags & SRI_O_DOWN) flags = sdscat(flags,"o_down,");
1438 if (ri->flags & SRI_MASTER) flags = sdscat(flags,"master,");
1439 if (ri->flags & SRI_SLAVE) flags = sdscat(flags,"slave,");
1440 if (ri->flags & SRI_SENTINEL) flags = sdscat(flags,"sentinel,");
1441 if (ri->flags & SRI_DISCONNECTED) flags = sdscat(flags,"disconnected,");
1442 if (ri->flags & SRI_MASTER_DOWN) flags = sdscat(flags,"master_down,");
1443 if (ri->flags & SRI_FAILOVER_IN_PROGRESS)
1444 flags = sdscat(flags,"failover_in_progress,");
1445 if (ri->flags & SRI_I_AM_THE_LEADER)
1446 flags = sdscat(flags,"i_am_the_leader,");
1447 if (ri->flags & SRI_PROMOTED) flags = sdscat(flags,"promoted,");
1448 if (ri->flags & SRI_RECONF_SENT) flags = sdscat(flags,"reconf_sent,");
1449 if (ri->flags & SRI_RECONF_INPROG) flags = sdscat(flags,"reconf_inprog,");
1450 if (ri->flags & SRI_RECONF_DONE) flags = sdscat(flags,"reconf_done,");
1451
1452 if (sdslen(flags) != 0) flags = sdsrange(flags,0,-2); /* remove last "," */
1453 addReplyBulkCString(c,flags);
1454 sdsfree(flags);
1455 fields++;
1456
1457 addReplyBulkCString(c,"pending-commands");
1458 addReplyBulkLongLong(c,ri->pending_commands);
1459 fields++;
1460
1461 if (ri->flags & SRI_FAILOVER_IN_PROGRESS) {
1462 addReplyBulkCString(c,"failover-state");
1463 addReplyBulkCString(c,(char*)sentinelFailoverStateStr(ri->failover_state));
1464 fields++;
1465 }
1466
1467 addReplyBulkCString(c,"last-ok-ping-reply");
1468 addReplyBulkLongLong(c,mstime() - ri->last_avail_time);
1469 fields++;
1470
1471 addReplyBulkCString(c,"last-ping-reply");
1472 addReplyBulkLongLong(c,mstime() - ri->last_pong_time);
1473 fields++;
1474
1475 if (ri->flags & SRI_S_DOWN) {
1476 addReplyBulkCString(c,"s-down-time");
1477 addReplyBulkLongLong(c,mstime()-ri->s_down_since_time);
1478 fields++;
1479 }
1480
1481 if (ri->flags & SRI_O_DOWN) {
1482 addReplyBulkCString(c,"o-down-time");
1483 addReplyBulkLongLong(c,mstime()-ri->o_down_since_time);
1484 fields++;
1485 }
1486
1487 /* Masters and Slaves */
1488 if (ri->flags & (SRI_MASTER|SRI_SLAVE)) {
1489 addReplyBulkCString(c,"info-refresh");
1490 addReplyBulkLongLong(c,mstime() - ri->info_refresh);
1491 fields++;
1492 }
1493
1494 /* Only masters */
1495 if (ri->flags & SRI_MASTER) {
1496 addReplyBulkCString(c,"num-slaves");
1497 addReplyBulkLongLong(c,dictSize(ri->slaves));
1498 fields++;
1499
1500 addReplyBulkCString(c,"num-other-sentinels");
1501 addReplyBulkLongLong(c,dictSize(ri->sentinels));
1502 fields++;
1503
1504 addReplyBulkCString(c,"quorum");
1505 addReplyBulkLongLong(c,ri->quorum);
1506 fields++;
1507 }
1508
1509 /* Only slaves */
1510 if (ri->flags & SRI_SLAVE) {
1511 addReplyBulkCString(c,"master-link-down-time");
1512 addReplyBulkLongLong(c,ri->master_link_down_time);
1513 fields++;
1514
1515 addReplyBulkCString(c,"master-link-status");
1516 addReplyBulkCString(c,
1517 (ri->slave_master_link_status == SENTINEL_MASTER_LINK_STATUS_UP) ?
1518 "ok" : "err");
1519 fields++;
1520
1521 addReplyBulkCString(c,"master-host");
1522 addReplyBulkCString(c,
1523 ri->slave_master_host ? ri->slave_master_host : "?");
1524 fields++;
1525
1526 addReplyBulkCString(c,"master-port");
1527 addReplyBulkLongLong(c,ri->slave_master_port);
1528 fields++;
1529 }
1530
1531 /* Only sentinels */
1532 if (ri->flags & SRI_SENTINEL) {
1533 addReplyBulkCString(c,"last-hello-message");
1534 addReplyBulkLongLong(c,mstime() - ri->last_hello_time);
1535 fields++;
1536
1537 addReplyBulkCString(c,"can-failover-its-master");
1538 addReplyBulkLongLong(c,(ri->flags & SRI_CAN_FAILOVER) != 0);
1539 fields++;
1540
1541 if (ri->flags & SRI_MASTER_DOWN) {
1542 addReplyBulkCString(c,"subjective-leader");
1543 addReplyBulkCString(c,ri->leader ? ri->leader : "?");
1544 fields++;
1545 }
1546 }
1547
1548 setDeferredMultiBulkLength(c,mbl,fields*2);
1549 }
1550
1551 /* Output a number of instances contanined inside a dictionary as
1552 * Redis protocol. */
1553 void addReplyDictOfRedisInstances(redisClient *c, dict *instances) {
1554 dictIterator *di;
1555 dictEntry *de;
1556
1557 di = dictGetIterator(instances);
1558 addReplyMultiBulkLen(c,dictSize(instances));
1559 while((de = dictNext(di)) != NULL) {
1560 sentinelRedisInstance *ri = dictGetVal(de);
1561
1562 addReplySentinelRedisInstance(c,ri);
1563 }
1564 dictReleaseIterator(di);
1565 }
1566
1567 /* Lookup the named master into sentinel.masters.
1568 * If the master is not found reply to the client with an error and returns
1569 * NULL. */
1570 sentinelRedisInstance *sentinelGetMasterByNameOrReplyError(redisClient *c,
1571 robj *name)
1572 {
1573 sentinelRedisInstance *ri;
1574
1575 ri = dictFetchValue(sentinel.masters,c->argv[2]->ptr);
1576 if (!ri) {
1577 addReplyError(c,"No such master with that name");
1578 return NULL;
1579 }
1580 return ri;
1581 }
1582
1583 void sentinelCommand(redisClient *c) {
1584 if (!strcasecmp(c->argv[1]->ptr,"masters")) {
1585 /* SENTINEL MASTERS */
1586 if (c->argc != 2) goto numargserr;
1587
1588 addReplyDictOfRedisInstances(c,sentinel.masters);
1589 } else if (!strcasecmp(c->argv[1]->ptr,"slaves")) {
1590 /* SENTINEL SLAVES <master-name> */
1591 sentinelRedisInstance *ri;
1592
1593 if (c->argc != 3) goto numargserr;
1594 if ((ri = sentinelGetMasterByNameOrReplyError(c,c->argv[2])) == NULL)
1595 return;
1596 addReplyDictOfRedisInstances(c,ri->slaves);
1597 } else if (!strcasecmp(c->argv[1]->ptr,"sentinels")) {
1598 /* SENTINEL SENTINELS <master-name> */
1599 sentinelRedisInstance *ri;
1600
1601 if (c->argc != 3) goto numargserr;
1602 if ((ri = sentinelGetMasterByNameOrReplyError(c,c->argv[2])) == NULL)
1603 return;
1604 addReplyDictOfRedisInstances(c,ri->sentinels);
1605 } else if (!strcasecmp(c->argv[1]->ptr,"is-master-down-by-addr")) {
1606 /* SENTINEL IS-MASTER-DOWN-BY-ADDR <ip> <port> */
1607 sentinelRedisInstance *ri;
1608 char *leader = NULL;
1609 long port;
1610 int isdown = 0;
1611
1612 if (c->argc != 4) goto numargserr;
1613 if (getLongFromObjectOrReply(c,c->argv[3],&port,NULL) != REDIS_OK)
1614 return;
1615 ri = getSentinelRedisInstanceByAddrAndRunID(sentinel.masters,
1616 c->argv[2]->ptr,port,NULL);
1617
1618 /* It exists? Is actually a master? Is subjectively down? It's down.
1619 * Note: if we are in tilt mode we always reply with "0". */
1620 if (!sentinel.tilt && ri && (ri->flags & SRI_S_DOWN) &&
1621 (ri->flags & SRI_MASTER))
1622 isdown = 1;
1623 if (ri) leader = sentinelGetSubjectiveLeader(ri);
1624
1625 /* Reply with a two-elements multi-bulk reply: down state, leader. */
1626 addReplyMultiBulkLen(c,2);
1627 addReply(c, isdown ? shared.cone : shared.czero);
1628 addReplyBulkCString(c, leader ? leader : "?");
1629 if (leader) sdsfree(leader);
1630 } else if (!strcasecmp(c->argv[1]->ptr,"reset")) {
1631 /* SENTINEL RESET <pattern> */
1632 if (c->argc != 3) goto numargserr;
1633 addReplyLongLong(c,sentinelResetMastersByPattern(c->argv[2]->ptr,SENTINEL_GENERATE_EVENT));
1634 } else if (!strcasecmp(c->argv[1]->ptr,"get-master-addr-by-name")) {
1635 /* SENTINEL GET-MASTER-ADDR-BY-NAME <master-name> */
1636 sentinelRedisInstance *ri;
1637
1638 if (c->argc != 3) goto numargserr;
1639 ri = sentinelGetMasterByName(c->argv[2]->ptr);
1640 if (ri == NULL) {
1641 addReply(c,shared.nullmultibulk);
1642 } else {
1643 sentinelAddr *addr = ri->addr;
1644
1645 if ((ri->flags & SRI_FAILOVER_IN_PROGRESS) && ri->promoted_slave)
1646 addr = ri->promoted_slave->addr;
1647 addReplyMultiBulkLen(c,2);
1648 addReplyBulkCString(c,addr->ip);
1649 addReplyBulkLongLong(c,addr->port);
1650 }
1651 } else {
1652 addReplyErrorFormat(c,"Unknown sentinel subcommand '%s'",
1653 (char*)c->argv[1]->ptr);
1654 }
1655 return;
1656
1657 numargserr:
1658 addReplyErrorFormat(c,"Wrong number of commands for 'sentinel %s'",
1659 (char*)c->argv[1]->ptr);
1660 }
1661
1662 /* ===================== SENTINEL availability checks ======================= */
1663
1664 /* Is this instance down from our point of view? */
1665 void sentinelCheckSubjectivelyDown(sentinelRedisInstance *ri) {
1666 mstime_t elapsed = mstime() - ri->last_avail_time;
1667
1668 /* Check if we are in need for a reconnection of one of the
1669 * links, because we are detecting low activity.
1670 *
1671 * 1) Check if the command link seems connected, was connected not less
1672 * than SENTINEL_MIN_LINK_RECONNECT_PERIOD, but still we have an
1673 * idle time that is greater than down_after_period / 2 seconds. */
1674 if (ri->cc &&
1675 (mstime() - ri->cc_conn_time) > SENTINEL_MIN_LINK_RECONNECT_PERIOD &&
1676 (mstime() - ri->last_pong_time) > (ri->down_after_period/2))
1677 {
1678 sentinelKillLink(ri,ri->cc);
1679 }
1680
1681 /* 2) Check if the pubsub link seems connected, was connected not less
1682 * than SENTINEL_MIN_LINK_RECONNECT_PERIOD, but still we have no
1683 * activity in the Pub/Sub channel for more than
1684 * SENTINEL_PUBLISH_PERIOD * 3.
1685 */
1686 if (ri->pc &&
1687 (mstime() - ri->pc_conn_time) > SENTINEL_MIN_LINK_RECONNECT_PERIOD &&
1688 (mstime() - ri->pc_last_activity) > (SENTINEL_PUBLISH_PERIOD*3))
1689 {
1690 sentinelKillLink(ri,ri->pc);
1691 }
1692
1693 /* Update the subjectively down flag. */
1694 if (elapsed > ri->down_after_period) {
1695 /* Is subjectively down */
1696 if ((ri->flags & SRI_S_DOWN) == 0) {
1697 sentinelEvent(REDIS_WARNING,"+sdown",ri,"%@");
1698 ri->s_down_since_time = mstime();
1699 ri->flags |= SRI_S_DOWN;
1700 }
1701 } else {
1702 /* Is subjectively up */
1703 if (ri->flags & SRI_S_DOWN) {
1704 sentinelEvent(REDIS_WARNING,"-sdown",ri,"%@");
1705 ri->flags &= ~SRI_S_DOWN;
1706 }
1707 }
1708 }
1709
1710 /* Is this instance down accordingly to the configured quorum? */
1711 void sentinelCheckObjectivelyDown(sentinelRedisInstance *master) {
1712 dictIterator *di;
1713 dictEntry *de;
1714 int quorum = 0, odown = 0;
1715
1716 if (master->flags & SRI_S_DOWN) {
1717 /* Is down for enough sentinels? */
1718 quorum = 1; /* the current sentinel. */
1719 /* Count all the other sentinels. */
1720 di = dictGetIterator(master->sentinels);
1721 while((de = dictNext(di)) != NULL) {
1722 sentinelRedisInstance *ri = dictGetVal(de);
1723
1724 if (ri->flags & SRI_MASTER_DOWN) quorum++;
1725 }
1726 dictReleaseIterator(di);
1727 if (quorum >= master->quorum) odown = 1;
1728 }
1729
1730 /* Set the flag accordingly to the outcome. */
1731 if (odown) {
1732 if ((master->flags & SRI_O_DOWN) == 0) {
1733 sentinelEvent(REDIS_WARNING,"+odown",master,"%@ #quorum %d/%d",
1734 quorum, master->quorum);
1735 master->flags |= SRI_O_DOWN;
1736 master->o_down_since_time = mstime();
1737 }
1738 } else {
1739 if (master->flags & SRI_O_DOWN) {
1740 sentinelEvent(REDIS_WARNING,"-odown",master,"%@");
1741 master->flags &= ~SRI_O_DOWN;
1742 }
1743 }
1744 }
1745
1746 /* Receive the SENTINEL is-master-down-by-addr reply, see the
1747 * sentinelAskMasterStateToOtherSentinels() function for more information. */
1748 void sentinelReceiveIsMasterDownReply(redisAsyncContext *c, void *reply, void *privdata) {
1749 sentinelRedisInstance *ri = c->data;
1750 redisReply *r;
1751
1752 if (ri) ri->pending_commands--;
1753 if (!reply || !ri) return;
1754 r = reply;
1755
1756 /* Ignore every error or unexpected reply.
1757 * Note that if the command returns an error for any reason we'll
1758 * end clearing the SRI_MASTER_DOWN flag for timeout anyway. */
1759 if (r->type == REDIS_REPLY_ARRAY && r->elements == 2 &&
1760 r->element[0]->type == REDIS_REPLY_INTEGER &&
1761 r->element[1]->type == REDIS_REPLY_STRING)
1762 {
1763 ri->last_master_down_reply_time = mstime();
1764 if (r->element[0]->integer == 1) {
1765 ri->flags |= SRI_MASTER_DOWN;
1766 } else {
1767 ri->flags &= ~SRI_MASTER_DOWN;
1768 }
1769 sdsfree(ri->leader);
1770 ri->leader = sdsnew(r->element[1]->str);
1771 }
1772 }
1773
1774 /* If we think (subjectively) the master is down, we start sending
1775 * SENTINEL IS-MASTER-DOWN-BY-ADDR requests to other sentinels
1776 * in order to get the replies that allow to reach the quorum and
1777 * possibly also mark the master as objectively down. */
1778 void sentinelAskMasterStateToOtherSentinels(sentinelRedisInstance *master) {
1779 dictIterator *di;
1780 dictEntry *de;
1781
1782 di = dictGetIterator(master->sentinels);
1783 while((de = dictNext(di)) != NULL) {
1784 sentinelRedisInstance *ri = dictGetVal(de);
1785 mstime_t elapsed = mstime() - ri->last_master_down_reply_time;
1786 char port[32];
1787 int retval;
1788
1789 /* If the master state from other sentinel is too old, we clear it. */
1790 if (elapsed > SENTINEL_INFO_VALIDITY_TIME) {
1791 ri->flags &= ~SRI_MASTER_DOWN;
1792 sdsfree(ri->leader);
1793 ri->leader = NULL;
1794 }
1795
1796 /* Only ask if master is down to other sentinels if:
1797 *
1798 * 1) We believe it is down, or there is a failover in progress.
1799 * 2) Sentinel is connected.
1800 * 3) We did not received the info within SENTINEL_ASK_PERIOD ms. */
1801 if ((master->flags & (SRI_S_DOWN|SRI_FAILOVER_IN_PROGRESS)) == 0)
1802 continue;
1803 if (ri->flags & SRI_DISCONNECTED) continue;
1804 if (mstime() - ri->last_master_down_reply_time < SENTINEL_ASK_PERIOD)
1805 continue;
1806
1807 /* Ask */
1808 ll2string(port,sizeof(port),master->addr->port);
1809 retval = redisAsyncCommand(ri->cc,
1810 sentinelReceiveIsMasterDownReply, NULL,
1811 "SENTINEL is-master-down-by-addr %s %s",
1812 master->addr->ip, port);
1813 if (retval == REDIS_OK) ri->pending_commands++;
1814 }
1815 dictReleaseIterator(di);
1816 }
1817
1818 /* =============================== FAILOVER ================================= */
1819
1820 /* Given a master get the "subjective leader", that is, among all the sentinels
1821 * with given characteristics, the one with the lexicographically smaller
1822 * runid. The characteristics required are:
1823 *
1824 * 1) Has SRI_CAN_FAILOVER flag.
1825 * 2) Is not disconnected.
1826 * 3) Recently answered to our ping (no longer than
1827 * SENTINEL_INFO_VALIDITY_TIME milliseconds ago).
1828 *
1829 * The function returns a pointer to an sds string representing the runid of the
1830 * leader sentinel instance (from our point of view). Otherwise NULL is
1831 * returned if there are no suitable sentinels.
1832 */
1833
1834 int compareRunID(const void *a, const void *b) {
1835 char **aptrptr = (char**)a, **bptrptr = (char**)b;
1836 return strcasecmp(*aptrptr, *bptrptr);
1837 }
1838
1839 char *sentinelGetSubjectiveLeader(sentinelRedisInstance *master) {
1840 dictIterator *di;
1841 dictEntry *de;
1842 char **instance =
1843 zmalloc(sizeof(char*)*(dictSize(master->sentinels)+1));
1844 int instances = 0;
1845 char *leader = NULL;
1846
1847 if (master->flags & SRI_CAN_FAILOVER) {
1848 /* Add myself if I'm a Sentinel that can failover this master. */
1849 instance[instances++] = server.runid;
1850 }
1851
1852 di = dictGetIterator(master->sentinels);
1853 while((de = dictNext(di)) != NULL) {
1854 sentinelRedisInstance *ri = dictGetVal(de);
1855 mstime_t lag = mstime() - ri->last_avail_time;
1856
1857 if (lag > SENTINEL_INFO_VALIDITY_TIME ||
1858 !(ri->flags & SRI_CAN_FAILOVER) ||
1859 (ri->flags & SRI_DISCONNECTED) ||
1860 ri->runid == NULL)
1861 continue;
1862 instance[instances++] = ri->runid;
1863 }
1864 dictReleaseIterator(di);
1865
1866 /* If we have at least one instance passing our checks, order the array
1867 * by runid. */
1868 if (instances) {
1869 qsort(instance,instances,sizeof(char*),compareRunID);
1870 leader = sdsnew(instance[0]);
1871 }
1872 zfree(instance);
1873 return leader;
1874 }
1875
1876 struct sentinelLeader {
1877 char *runid;
1878 unsigned long votes;
1879 };
1880
1881 /* Helper function for sentinelGetObjectiveLeader, increment the counter
1882 * relative to the specified runid. */
1883 void sentinelObjectiveLeaderIncr(dict *counters, char *runid) {
1884 dictEntry *de = dictFind(counters,runid);
1885 uint64_t oldval;
1886
1887 if (de) {
1888 oldval = dictGetUnsignedIntegerVal(de);
1889 dictSetUnsignedIntegerVal(de,oldval+1);
1890 } else {
1891 de = dictAddRaw(counters,runid);
1892 redisAssert(de != NULL);
1893 dictSetUnsignedIntegerVal(de,1);
1894 }
1895 }
1896
1897 /* Scan all the Sentinels attached to this master to check what is the
1898 * most voted leader among Sentinels. */
1899 char *sentinelGetObjectiveLeader(sentinelRedisInstance *master) {
1900 dict *counters;
1901 dictIterator *di;
1902 dictEntry *de;
1903 unsigned int voters = 0, voters_quorum;
1904 char *myvote;
1905 char *winner = NULL;
1906
1907 redisAssert(master->flags & (SRI_O_DOWN|SRI_FAILOVER_IN_PROGRESS));
1908 counters = dictCreate(&leaderVotesDictType,NULL);
1909
1910 /* Count my vote. */
1911 myvote = sentinelGetSubjectiveLeader(master);
1912 if (myvote) {
1913 sentinelObjectiveLeaderIncr(counters,myvote);
1914 voters++;
1915 }
1916
1917 /* Count other sentinels votes */
1918 di = dictGetIterator(master->sentinels);
1919 while((de = dictNext(di)) != NULL) {
1920 sentinelRedisInstance *ri = dictGetVal(de);
1921 if (ri->leader == NULL) continue;
1922 /* If the failover is not already in progress we are only interested
1923 * in Sentinels that believe the master is down. Otherwise the leader
1924 * selection is useful for the "failover-takedown" when the original
1925 * leader fails. In that case we consider all the voters. */
1926 if (!(master->flags & SRI_FAILOVER_IN_PROGRESS) &&
1927 !(ri->flags & SRI_MASTER_DOWN)) continue;
1928 sentinelObjectiveLeaderIncr(counters,ri->leader);
1929 voters++;
1930 }
1931 dictReleaseIterator(di);
1932 voters_quorum = voters/2+1;
1933
1934 /* Check what's the winner. For the winner to win, it needs two conditions:
1935 * 1) Absolute majority between voters (50% + 1).
1936 * 2) And anyway at least master->quorum votes. */
1937 {
1938 uint64_t max_votes = 0; /* Max votes so far. */
1939
1940 di = dictGetIterator(counters);
1941 while((de = dictNext(di)) != NULL) {
1942 uint64_t votes = dictGetUnsignedIntegerVal(de);
1943
1944 if (max_votes < votes) {
1945 max_votes = votes;
1946 winner = dictGetKey(de);
1947 }
1948 }
1949 dictReleaseIterator(di);
1950 if (winner && (max_votes < voters_quorum || max_votes < master->quorum))
1951 winner = NULL;
1952 }
1953 winner = winner ? sdsnew(winner) : NULL;
1954 sdsfree(myvote);
1955 dictRelease(counters);
1956 return winner;
1957 }
1958
1959 /* This function checks if there are the conditions to start the failover,
1960 * that is:
1961 *
1962 * 1) Enough time has passed since O_DOWN.
1963 * 2) The master is marked as SRI_CAN_FAILOVER, so we can failover it.
1964 * 3) We are the objectively leader for this master.
1965 *
1966 * If the conditions are met we flag the master as SRI_FAILOVER_IN_PROGRESS
1967 * and SRI_I_AM_THE_LEADER.
1968 */
1969 void sentinelStartFailover(sentinelRedisInstance *master) {
1970 char *leader;
1971 int isleader;
1972
1973 /* We can't failover if the master is not in O_DOWN state or if
1974 * there is not already a failover in progress (to perform the
1975 * takedown if the leader died) or if this Sentinel is not allowed
1976 * to start a failover. */
1977 if (!(master->flags & SRI_CAN_FAILOVER) ||
1978 !(master->flags & (SRI_O_DOWN|SRI_FAILOVER_IN_PROGRESS))) return;
1979
1980 leader = sentinelGetObjectiveLeader(master);
1981 isleader = leader && strcasecmp(leader,server.runid) == 0;
1982 sdsfree(leader);
1983
1984 /* If I'm not the leader, I can't failover for sure. */
1985 if (!isleader) return;
1986
1987 /* If the failover is already in progress there are two options... */
1988 if (master->flags & SRI_FAILOVER_IN_PROGRESS) {
1989 if (master->flags & SRI_I_AM_THE_LEADER) {
1990 /* 1) I'm flagged as leader so I already started the failover.
1991 * Just return. */
1992 return;
1993 } else {
1994 mstime_t elapsed = mstime() - master->failover_state_change_time;
1995
1996 /* 2) I'm the new leader, but I'm not flagged as leader in the
1997 * master: I did not started the failover, but the original
1998 * leader has no longer the leadership.
1999 *
2000 * In this case if the failover appears to be lagging
2001 * for at least 25% of the configured failover timeout,
2002 * I can assume I can take control. Otherwise
2003 * it's better to return and wait more. */
2004 if (elapsed < (master->failover_timeout/4)) return;
2005 sentinelEvent(REDIS_WARNING,"+failover-takedown",master,"%@");
2006 /* We have already an elected slave if we are in
2007 * FAILOVER_IN_PROGRESS state, that is, the slave that we
2008 * observed turning into a master. */
2009 master->failover_state = SENTINEL_FAILOVER_STATE_RECONF_SLAVES;
2010 /* As an observer we flagged all the slaves as RECONF_SENT but
2011 * now we are in charge of actually sending the reconfiguration
2012 * command so let's clear this flag for all the instances. */
2013 sentinelDelFlagsToDictOfRedisInstances(master->slaves,
2014 SRI_RECONF_SENT);
2015 }
2016 } else {
2017 /* Brand new failover as SRI_FAILOVER_IN_PROGRESS was not set. */
2018 master->failover_state = SENTINEL_FAILOVER_STATE_WAIT_START;
2019 }
2020
2021 master->flags |= SRI_FAILOVER_IN_PROGRESS|SRI_I_AM_THE_LEADER;
2022 sentinelEvent(REDIS_WARNING,"+failover-triggered",master,"%@");
2023
2024 /* Pick a random delay if it's a fresh failover (WAIT_START), and not
2025 * a recovery of a failover started by another sentinel. */
2026 if (master->failover_state == SENTINEL_FAILOVER_STATE_WAIT_START) {
2027 master->failover_start_time = mstime() +
2028 SENTINEL_FAILOVER_FIXED_DELAY +
2029 (rand() % SENTINEL_FAILOVER_MAX_RANDOM_DELAY);
2030 sentinelEvent(REDIS_WARNING,"+failover-state-wait-start",master,
2031 "%@ #starting in %lld milliseconds",
2032 master->failover_start_time-mstime());
2033 }
2034 master->failover_state_change_time = mstime();
2035 }
2036
2037 /* Select a suitable slave to promote. The current algorithm only uses
2038 * the following parameters:
2039 *
2040 * 1) None of the following conditions: S_DOWN, O_DOWN, DISCONNECTED.
2041 * 2) last_avail_time more recent than SENTINEL_INFO_VALIDITY_TIME.
2042 * 3) info_refresh more recent than SENTINEL_INFO_VALIDITY_TIME.
2043 * 4) master_link_down_time no more than:
2044 * (now - master->s_down_since_time) + (master->down_after_period * 10).
2045 *
2046 * Among all the slaves matching the above conditions we select the slave
2047 * with lower slave_priority. If priority is the same we select the slave
2048 * with lexicographically smaller runid.
2049 *
2050 * The function returns the pointer to the selected slave, otherwise
2051 * NULL if no suitable slave was found.
2052 */
2053
2054 int compareSlavesForPromotion(const void *a, const void *b) {
2055 sentinelRedisInstance **sa = (sentinelRedisInstance **)a,
2056 **sb = (sentinelRedisInstance **)b;
2057 if ((*sa)->slave_priority != (*sb)->slave_priority)
2058 return (*sa)->slave_priority - (*sb)->slave_priority;
2059 return strcasecmp((*sa)->runid,(*sb)->runid);
2060 }
2061
2062 sentinelRedisInstance *sentinelSelectSlave(sentinelRedisInstance *master) {
2063 sentinelRedisInstance **instance =
2064 zmalloc(sizeof(instance[0])*dictSize(master->slaves));
2065 sentinelRedisInstance *selected = NULL;
2066 int instances = 0;
2067 dictIterator *di;
2068 dictEntry *de;
2069 mstime_t max_master_down_time;
2070
2071 max_master_down_time = (mstime() - master->s_down_since_time) +
2072 (master->down_after_period * 10);
2073
2074 di = dictGetIterator(master->slaves);
2075 while((de = dictNext(di)) != NULL) {
2076 sentinelRedisInstance *slave = dictGetVal(de);
2077 mstime_t info_validity_time = mstime()-SENTINEL_INFO_VALIDITY_TIME;
2078
2079 if (slave->flags & (SRI_S_DOWN|SRI_O_DOWN|SRI_DISCONNECTED)) continue;
2080 if (slave->last_avail_time < info_validity_time) continue;
2081 if (slave->info_refresh < info_validity_time) continue;
2082 if (slave->master_link_down_time > max_master_down_time) continue;
2083 instance[instances++] = slave;
2084 }
2085 dictReleaseIterator(di);
2086 if (instances) {
2087 qsort(instance,instances,sizeof(sentinelRedisInstance*),
2088 compareSlavesForPromotion);
2089 selected = instance[0];
2090 }
2091 zfree(instance);
2092 return selected;
2093 }
2094
2095 /* ---------------- Failover state machine implementation ------------------- */
2096 void sentinelFailoverWaitStart(sentinelRedisInstance *ri) {
2097 if (mstime() >= ri->failover_start_time) {
2098 ri->failover_state = SENTINEL_FAILOVER_STATE_SELECT_SLAVE;
2099 ri->failover_state_change_time = mstime();
2100 sentinelEvent(REDIS_WARNING,"+failover-state-select-slave",ri,"%@");
2101 }
2102 }
2103
2104 void sentinelFailoverSelectSlave(sentinelRedisInstance *ri) {
2105 sentinelRedisInstance *slave = sentinelSelectSlave(ri);
2106
2107 if (slave == NULL) {
2108 sentinelEvent(REDIS_WARNING,"-no-good-slave",ri,
2109 "%@ #retrying in %d seconds",
2110 (SENTINEL_FAILOVER_FIXED_DELAY+
2111 SENTINEL_FAILOVER_MAX_RANDOM_DELAY)/1000);
2112 ri->failover_state = SENTINEL_FAILOVER_STATE_WAIT_START;
2113 ri->failover_start_time = mstime() + SENTINEL_FAILOVER_FIXED_DELAY +
2114 SENTINEL_FAILOVER_MAX_RANDOM_DELAY;
2115 } else {
2116 sentinelEvent(REDIS_WARNING,"+selected-slave",slave,"%@");
2117 slave->flags |= SRI_PROMOTED;
2118 ri->promoted_slave = slave;
2119 ri->failover_state = SENTINEL_FAILOVER_STATE_SEND_SLAVEOF_NOONE;
2120 ri->failover_state_change_time = mstime();
2121 sentinelEvent(REDIS_NOTICE,"+failover-state-send-slaveof-noone",
2122 slave, "%@");
2123 }
2124 }
2125
2126 void sentinelFailoverSendSlaveOfNoOne(sentinelRedisInstance *ri) {
2127 int retval;
2128
2129 if (ri->promoted_slave->flags & SRI_DISCONNECTED) return;
2130
2131 /* Send SLAVEOF NO ONE command to turn the slave into a master.
2132 * We actually register a generic callback for this command as we don't
2133 * really care about the reply. We check if it worked indirectly observing
2134 * if INFO returns a different role (master instead of slave). */
2135 retval = redisAsyncCommand(ri->promoted_slave->cc,
2136 sentinelDiscardReplyCallback, NULL, "SLAVEOF NO ONE");
2137 if (retval != REDIS_OK) return;
2138 ri->promoted_slave->pending_commands++;
2139 sentinelEvent(REDIS_NOTICE, "+failover-state-wait-promotion",
2140 ri->promoted_slave,"%@");
2141 ri->failover_state = SENTINEL_FAILOVER_STATE_WAIT_PROMOTION;
2142 ri->failover_state_change_time = mstime();
2143 }
2144
2145 /* We actually wait for promotion indirectly checking with INFO when the
2146 * slave turns into a master. */
2147 void sentinelFailoverWaitPromotion(sentinelRedisInstance *ri) {
2148 mstime_t elapsed = mstime() - ri->failover_state_change_time;
2149
2150 if (elapsed >= SENTINEL_PROMOTION_RETRY_PERIOD) {
2151 sentinelEvent(REDIS_WARNING,"-promotion-timeout",ri->promoted_slave,
2152 "%@");
2153 sentinelEvent(REDIS_WARNING,"+failover-state-select-slave",ri,"%@");
2154 ri->failover_state = SENTINEL_FAILOVER_STATE_SELECT_SLAVE;
2155 ri->failover_state_change_time = mstime();
2156 ri->promoted_slave->flags &= ~SRI_PROMOTED;
2157 ri->promoted_slave = NULL;
2158 }
2159 }
2160
2161 void sentinelFailoverDetectEnd(sentinelRedisInstance *master) {
2162 int not_reconfigured = 0, timeout = 0;
2163 dictIterator *di;
2164 dictEntry *de;
2165 mstime_t elapsed = mstime() - master->failover_state_change_time;
2166
2167 /* We can't consider failover finished if the promoted slave is
2168 * not reachable. */
2169 if (master->promoted_slave == NULL ||
2170 master->promoted_slave->flags & SRI_S_DOWN) return;
2171
2172 /* The failover terminates once all the reachable slaves are properly
2173 * configured. */
2174 di = dictGetIterator(master->slaves);
2175 while((de = dictNext(di)) != NULL) {
2176 sentinelRedisInstance *slave = dictGetVal(de);
2177
2178 if (slave->flags & (SRI_PROMOTED|SRI_RECONF_DONE)) continue;
2179 if (slave->flags & SRI_S_DOWN) continue;
2180 not_reconfigured++;
2181 }
2182 dictReleaseIterator(di);
2183
2184 /* Force end of failover on timeout. */
2185 if (elapsed > master->failover_timeout) {
2186 not_reconfigured = 0;
2187 timeout = 1;
2188 sentinelEvent(REDIS_WARNING,"+failover-end-for-timeout",master,"%@");
2189 }
2190
2191 if (not_reconfigured == 0) {
2192 sentinelEvent(REDIS_WARNING,"+failover-end",master,"%@");
2193 master->failover_state = SENTINEL_FAILOVER_STATE_UPDATE_CONFIG;
2194 master->failover_state_change_time = mstime();
2195 }
2196
2197 /* If I'm the leader it is a good idea to send a best effort SLAVEOF
2198 * command to all the slaves still not reconfigured to replicate with
2199 * the new master. */
2200 if (timeout && (master->flags & SRI_I_AM_THE_LEADER)) {
2201 dictIterator *di;
2202 dictEntry *de;
2203 char master_port[32];
2204
2205 ll2string(master_port,sizeof(master_port),
2206 master->promoted_slave->addr->port);
2207
2208 di = dictGetIterator(master->slaves);
2209 while((de = dictNext(di)) != NULL) {
2210 sentinelRedisInstance *slave = dictGetVal(de);
2211 int retval;
2212
2213 if (slave->flags &
2214 (SRI_RECONF_DONE|SRI_RECONF_SENT|SRI_DISCONNECTED)) continue;
2215
2216 retval = redisAsyncCommand(slave->cc,
2217 sentinelDiscardReplyCallback, NULL, "SLAVEOF %s %s",
2218 master->promoted_slave->addr->ip,
2219 master_port);
2220 if (retval == REDIS_OK) {
2221 sentinelEvent(REDIS_NOTICE,"+slave-reconf-sent-be",slave,"%@");
2222 slave->flags |= SRI_RECONF_SENT;
2223 }
2224 }
2225 dictReleaseIterator(di);
2226 }
2227 }
2228
2229 /* Send SLAVE OF <new master address> to all the remaining slaves that
2230 * still don't appear to have the configuration updated. */
2231 void sentinelFailoverReconfNextSlave(sentinelRedisInstance *master) {
2232 dictIterator *di;
2233 dictEntry *de;
2234 int in_progress = 0;
2235
2236 di = dictGetIterator(master->slaves);
2237 while((de = dictNext(di)) != NULL) {
2238 sentinelRedisInstance *slave = dictGetVal(de);
2239
2240 if (slave->flags & (SRI_RECONF_SENT|SRI_RECONF_INPROG))
2241 in_progress++;
2242 }
2243 dictReleaseIterator(di);
2244
2245 di = dictGetIterator(master->slaves);
2246 while(in_progress < master->parallel_syncs &&
2247 (de = dictNext(di)) != NULL)
2248 {
2249 sentinelRedisInstance *slave = dictGetVal(de);
2250 int retval;
2251 char master_port[32];
2252
2253 /* Skip the promoted slave, and already configured slaves. */
2254 if (slave->flags & (SRI_PROMOTED|SRI_RECONF_DONE)) continue;
2255
2256 /* Clear the SRI_RECONF_SENT flag if too much time elapsed without
2257 * the slave moving forward to the next state. */
2258 if ((slave->flags & SRI_RECONF_SENT) &&
2259 (mstime() - slave->slave_reconf_sent_time) >
2260 SENTINEL_SLAVE_RECONF_RETRY_PERIOD)
2261 {
2262 sentinelEvent(REDIS_NOTICE,"-slave-reconf-sent-timeout",slave,"%@");
2263 slave->flags &= ~SRI_RECONF_SENT;
2264 }
2265
2266 /* Nothing to do for instances that are disconnected or already
2267 * in RECONF_SENT state. */
2268 if (slave->flags & (SRI_DISCONNECTED|SRI_RECONF_SENT|SRI_RECONF_INPROG))
2269 continue;
2270
2271 /* Send SLAVEOF <new master>. */
2272 ll2string(master_port,sizeof(master_port),
2273 master->promoted_slave->addr->port);
2274 retval = redisAsyncCommand(slave->cc,
2275 sentinelDiscardReplyCallback, NULL, "SLAVEOF %s %s",
2276 master->promoted_slave->addr->ip,
2277 master_port);
2278 if (retval == REDIS_OK) {
2279 slave->flags |= SRI_RECONF_SENT;
2280 slave->pending_commands++;
2281 slave->slave_reconf_sent_time = mstime();
2282 sentinelEvent(REDIS_NOTICE,"+slave-reconf-sent",slave,"%@");
2283 in_progress++;
2284 }
2285 }
2286 dictReleaseIterator(di);
2287 sentinelFailoverDetectEnd(master);
2288 }
2289
2290 /* This function is called when the slave is in
2291 * SENTINEL_FAILOVER_STATE_UPDATE_CONFIG state. In this state we need
2292 * to remove it from the master table and add the promoted slave instead.
2293 *
2294 * If there are no promoted slaves as this instance is unique, we remove
2295 * and re-add it with the same address to trigger a complete state
2296 * refresh. */
2297 void sentinelFailoverSwitchToPromotedSlave(sentinelRedisInstance *master) {
2298 sentinelRedisInstance *ref = master->promoted_slave ?
2299 master->promoted_slave : master;
2300
2301 sentinelEvent(REDIS_WARNING,"+switch-master",master,"%s %s %d %s %d",
2302 master->name, master->addr->ip, master->addr->port,
2303 ref->addr->ip, ref->addr->port);
2304
2305 sentinelResetMasterAndChangeAddress(master,ref->addr->ip,ref->addr->port);
2306 }
2307
2308 void sentinelFailoverStateMachine(sentinelRedisInstance *ri) {
2309 redisAssert(ri->flags & SRI_MASTER);
2310
2311 if (!(ri->flags & SRI_FAILOVER_IN_PROGRESS)) return;
2312
2313 switch(ri->failover_state) {
2314 case SENTINEL_FAILOVER_STATE_WAIT_START:
2315 sentinelFailoverWaitStart(ri);
2316 break;
2317 case SENTINEL_FAILOVER_STATE_SELECT_SLAVE:
2318 sentinelFailoverSelectSlave(ri);
2319 break;
2320 case SENTINEL_FAILOVER_STATE_SEND_SLAVEOF_NOONE:
2321 sentinelFailoverSendSlaveOfNoOne(ri);
2322 break;
2323 case SENTINEL_FAILOVER_STATE_WAIT_PROMOTION:
2324 sentinelFailoverWaitPromotion(ri);
2325 break;
2326 case SENTINEL_FAILOVER_STATE_RECONF_SLAVES:
2327 sentinelFailoverReconfNextSlave(ri);
2328 break;
2329 case SENTINEL_FAILOVER_STATE_DETECT_END:
2330 sentinelFailoverDetectEnd(ri);
2331 break;
2332 }
2333 }
2334
2335 /* The following is called only for master instances and will abort the
2336 * failover process if:
2337 *
2338 * 1) The failover is in progress.
2339 * 2) We already promoted a slave.
2340 * 3) The promoted slave is in extended SDOWN condition.
2341 */
2342 void sentinelAbortFailoverIfNeeded(sentinelRedisInstance *ri) {
2343 dictIterator *di;
2344 dictEntry *de;
2345
2346 /* Failover is in progress? Do we have a promoted slave? */
2347 if (!(ri->flags & SRI_FAILOVER_IN_PROGRESS) || !ri->promoted_slave) return;
2348
2349 /* Is the promoted slave into an extended SDOWN state? */
2350 if (!(ri->promoted_slave->flags & SRI_S_DOWN) ||
2351 (mstime() - ri->promoted_slave->s_down_since_time) <
2352 (ri->down_after_period * SENTINEL_EXTENDED_SDOWN_MULTIPLIER)) return;
2353
2354 sentinelEvent(REDIS_WARNING,"-failover-abort-x-sdown",ri->promoted_slave,"%@");
2355
2356 /* Clear failover related flags from slaves.
2357 * Also if we are the leader make sure to send SLAVEOF commands to all the
2358 * already reconfigured slaves in order to turn them back into slaves of
2359 * the original master. */
2360
2361 di = dictGetIterator(ri->slaves);
2362 while((de = dictNext(di)) != NULL) {
2363 sentinelRedisInstance *slave = dictGetVal(de);
2364 if (ri->flags & SRI_I_AM_THE_LEADER) {
2365 char master_port[32];
2366 int retval;
2367
2368 ll2string(master_port,sizeof(master_port),ri->addr->port);
2369 retval = redisAsyncCommand(slave->cc,
2370 sentinelDiscardReplyCallback, NULL, "SLAVEOF %s %s",
2371 ri->addr->ip,
2372 master_port);
2373 if (retval == REDIS_OK)
2374 sentinelEvent(REDIS_NOTICE,"-slave-reconf-undo",slave,"%@");
2375 }
2376 slave->flags &= ~(SRI_RECONF_SENT|SRI_RECONF_INPROG|SRI_RECONF_DONE);
2377 }
2378 dictReleaseIterator(di);
2379
2380 ri->flags &= ~(SRI_FAILOVER_IN_PROGRESS|SRI_I_AM_THE_LEADER);
2381 ri->failover_state = SENTINEL_FAILOVER_STATE_NONE;
2382 ri->failover_state_change_time = mstime();
2383 ri->promoted_slave->flags &= ~SRI_PROMOTED;
2384 ri->promoted_slave = NULL;
2385 }
2386
2387 /* ======================== SENTINEL timer handler ==========================
2388 * This is the "main" our Sentinel, being sentinel completely non blocking
2389 * in design. The function is called every second.
2390 * -------------------------------------------------------------------------- */
2391
2392 /* Perform scheduled operations for the specified Redis instance. */
2393 void sentinelHandleRedisInstance(sentinelRedisInstance *ri) {
2394 /* ========== MONITORING HALF ============ */
2395 /* Every kind of instance */
2396 sentinelReconnectInstance(ri);
2397 sentinelPingInstance(ri);
2398
2399 /* Masters and slaves */
2400 if (ri->flags & (SRI_MASTER|SRI_SLAVE)) {
2401 /* Nothing so far. */
2402 }
2403
2404 /* Only masters */
2405 if (ri->flags & SRI_MASTER) {
2406 sentinelAskMasterStateToOtherSentinels(ri);
2407 }
2408
2409 /* ============== ACTING HALF ============= */
2410 /* We don't proceed with the acting half if we are in TILT mode.
2411 * TILT happens when we find something odd with the time, like a
2412 * sudden change in the clock. */
2413 if (sentinel.tilt) {
2414 if (mstime()-sentinel.tilt_start_time < SENTINEL_TILT_PERIOD) return;
2415 sentinel.tilt = 0;
2416 sentinelEvent(REDIS_WARNING,"-tilt",NULL,"#tilt mode exited");
2417 }
2418
2419 /* Every kind of instance */
2420 sentinelCheckSubjectivelyDown(ri);
2421
2422 /* Masters and slaves */
2423 if (ri->flags & (SRI_MASTER|SRI_SLAVE)) {
2424 /* Nothing so far. */
2425 }
2426
2427 /* Only masters */
2428 if (ri->flags & SRI_MASTER) {
2429 sentinelCheckObjectivelyDown(ri);
2430 sentinelStartFailover(ri);
2431 sentinelFailoverStateMachine(ri);
2432 sentinelAbortFailoverIfNeeded(ri);
2433 }
2434 }
2435
2436 /* Perform scheduled operations for all the instances in the dictionary.
2437 * Recursively call the function against dictionaries of slaves. */
2438 void sentinelHandleDictOfRedisInstances(dict *instances) {
2439 dictIterator *di;
2440 dictEntry *de;
2441 sentinelRedisInstance *switch_to_promoted = NULL;
2442
2443 /* There are a number of things we need to perform against every master. */
2444 di = dictGetIterator(instances);
2445 while((de = dictNext(di)) != NULL) {
2446 sentinelRedisInstance *ri = dictGetVal(de);
2447
2448 sentinelHandleRedisInstance(ri);
2449 if (ri->flags & SRI_MASTER) {
2450 sentinelHandleDictOfRedisInstances(ri->slaves);
2451 sentinelHandleDictOfRedisInstances(ri->sentinels);
2452 if (ri->failover_state == SENTINEL_FAILOVER_STATE_UPDATE_CONFIG) {
2453 switch_to_promoted = ri;
2454 }
2455 }
2456 }
2457 if (switch_to_promoted)
2458 sentinelFailoverSwitchToPromotedSlave(switch_to_promoted);
2459 dictReleaseIterator(di);
2460 }
2461
2462 /* This function checks if we need to enter the TITL mode.
2463 *
2464 * The TILT mode is entered if we detect that between two invocations of the
2465 * timer interrupt, a negative amount of time, or too much time has passed.
2466 * Note that we expect that more or less just 100 milliseconds will pass
2467 * if everything is fine. However we'll see a negative number or a
2468 * difference bigger than SENTINEL_TILT_TRIGGER milliseconds if one of the
2469 * following conditions happen:
2470 *
2471 * 1) The Sentiel process for some time is blocked, for every kind of
2472 * random reason: the load is huge, the computer was freezed for some time
2473 * in I/O or alike, the process was stopped by a signal. Everything.
2474 * 2) The system clock was altered significantly.
2475 *
2476 * Under both this conditions we'll see everything as timed out and failing
2477 * without good reasons. Instead we enter the TILT mode and wait
2478 * for SENTIENL_TILT_PERIOD to elapse before starting to act again.
2479 *
2480 * During TILT time we still collect information, we just do not act. */
2481 void sentinelCheckTiltCondition(void) {
2482 mstime_t now = mstime();
2483 mstime_t delta = now - sentinel.previous_time;
2484
2485 if (delta < 0 || delta > SENTINEL_TILT_TRIGGER) {
2486 sentinel.tilt = 1;
2487 sentinel.tilt_start_time = mstime();
2488 sentinelEvent(REDIS_WARNING,"+tilt",NULL,"#tilt mode entered");
2489 }
2490 sentinel.previous_time = mstime();
2491 }
2492
2493 void sentinelTimer(void) {
2494 sentinelCheckTiltCondition();
2495 sentinelHandleDictOfRedisInstances(sentinel.masters);
2496 }
2497