1 /* Redis Sentinel implementation
2 * -----------------------------
4 * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions are met:
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.
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.
37 #include <arpa/inet.h>
38 #include <sys/socket.h>
40 #define REDIS_SENTINEL_PORT 26379
42 /* ======================== Sentinel global state =========================== */
44 typedef long long mstime_t
; /* millisecond time type. */
46 /* Address object, used to describe an ip:port pair. */
47 typedef struct sentinelAddr
{
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
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. */
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
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
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. */
110 #define SENTINEL_MASTER_LINK_STATUS_UP 0
111 #define SENTINEL_MASTER_LINK_STATUS_DOWN 1
113 /* Generic flags that can be used with different functions. */
114 #define SENTINEL_NO_FLAGS 0
115 #define SENTINEL_GENERATE_EVENT 1
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
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. */
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. */
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 */
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. */
173 char *client_reconfig_script
;
174 } sentinelRedisInstance
;
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. */
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. */
191 typedef struct redisAeEvents
{
192 redisAsyncContext
*context
;
195 int reading
, writing
;
198 static void redisAeReadEvent(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
199 ((void)el
); ((void)fd
); ((void)mask
);
201 redisAeEvents
*e
= (redisAeEvents
*)privdata
;
202 redisAsyncHandleRead(e
->context
);
205 static void redisAeWriteEvent(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
206 ((void)el
); ((void)fd
); ((void)mask
);
208 redisAeEvents
*e
= (redisAeEvents
*)privdata
;
209 redisAsyncHandleWrite(e
->context
);
212 static void redisAeAddRead(void *privdata
) {
213 redisAeEvents
*e
= (redisAeEvents
*)privdata
;
214 aeEventLoop
*loop
= e
->loop
;
217 aeCreateFileEvent(loop
,e
->fd
,AE_READABLE
,redisAeReadEvent
,e
);
221 static void redisAeDelRead(void *privdata
) {
222 redisAeEvents
*e
= (redisAeEvents
*)privdata
;
223 aeEventLoop
*loop
= e
->loop
;
226 aeDeleteFileEvent(loop
,e
->fd
,AE_READABLE
);
230 static void redisAeAddWrite(void *privdata
) {
231 redisAeEvents
*e
= (redisAeEvents
*)privdata
;
232 aeEventLoop
*loop
= e
->loop
;
235 aeCreateFileEvent(loop
,e
->fd
,AE_WRITABLE
,redisAeWriteEvent
,e
);
239 static void redisAeDelWrite(void *privdata
) {
240 redisAeEvents
*e
= (redisAeEvents
*)privdata
;
241 aeEventLoop
*loop
= e
->loop
;
244 aeDeleteFileEvent(loop
,e
->fd
,AE_WRITABLE
);
248 static void redisAeCleanup(void *privdata
) {
249 redisAeEvents
*e
= (redisAeEvents
*)privdata
;
250 redisAeDelRead(privdata
);
251 redisAeDelWrite(privdata
);
255 static int redisAeAttach(aeEventLoop
*loop
, redisAsyncContext
*ac
) {
256 redisContext
*c
= &(ac
->c
);
259 /* Nothing should be attached when something is already attached */
260 if (ac
->ev
.data
!= NULL
)
263 /* Create container for context and r/w events */
264 e
= (redisAeEvents
*)zmalloc(sizeof(*e
));
268 e
->reading
= e
->writing
= 0;
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
;
281 /* ============================= Prototypes ================================= */
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
);
294 /* ========================= Dictionary types =============================== */
296 unsigned int dictSdsHash(const void *key
);
297 int dictSdsKeyCompare(void *privdata
, const void *key1
, const void *key2
);
298 void releaseSentinelRedisInstance(sentinelRedisInstance
*ri
);
300 void dictInstancesValDestructor (void *privdata
, void *obj
) {
301 releaseSentinelRedisInstance(obj
);
304 /* Instance name (sds) -> instance (sentinelRedisInstance pointer)
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 */
312 dictSdsKeyCompare
, /* key compare */
313 NULL
, /* key destructor */
314 dictInstancesValDestructor
/* val destructor */
317 /* Instance runid (sds) -> votes (long casted to void*)
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 */
325 dictSdsKeyCompare
, /* key compare */
326 NULL
, /* key destructor */
327 NULL
/* val destructor */
330 /* =========================== Initialization =============================== */
332 void sentinelCommand(redisClient
*c
);
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}
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
;
349 /* Perform the Sentinel mode initialization. */
350 void initSentinel(void) {
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
++) {
358 struct redisCommand
*cmd
= sentinelcmds
+j
;
360 retval
= dictAdd(server
.commands
, sdsnew(cmd
->name
), cmd
);
361 redisAssert(retval
== DICT_OK
);
364 /* Initialize various data structures. */
365 sentinel
.masters
= dictCreate(&instancesDictType
,NULL
);
367 sentinel
.tilt_start_time
= mstime();
368 sentinel
.previous_time
= mstime();
371 /* ============================== sentinelAddr ============================== */
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.
378 sentinelAddr
*createSentinelAddr(char *hostname
, int port
) {
382 if (port
<= 0 || port
> 65535) {
386 if (anetResolve(NULL
,hostname
,buf
) == ANET_ERR
) {
390 sa
= zmalloc(sizeof(*sa
));
391 sa
->ip
= sdsnew(buf
);
396 /* Free a Sentinel address. Can't fail. */
397 void releaseSentinelAddr(sentinelAddr
*sa
) {
402 /* =========================== Events notification ========================== */
404 void sentinelCallNotificationScript(char *scriptpath
, char *type
, char *msg
) {
405 /* TODO: implement it. */
408 /* Send an event to log, pub/sub, user notification script.
410 * 'level' is the log level for logging. Only REDIS_WARNING events will trigger
411 * the execution of the user notification script.
413 * 'type' is the message type, also used as a pub/sub channel name.
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.
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
423 * <instance type> <instance name> <ip> <port>
425 * If the instance type is not master, than the additional string is
426 * added to specify the originating master:
428 * @ <master name> <master ip> <master port>
430 * Any other specifier after "%@" is processed by printf itself.
432 void sentinelEvent(int level
, char *type
, sentinelRedisInstance
*ri
,
433 const char *fmt
, ...) {
435 char msg
[REDIS_MAX_LOGMSG_LEN
];
436 robj
*channel
, *payload
;
439 if (fmt
[0] == '%' && fmt
[1] == '@') {
440 sentinelRedisInstance
*master
= (ri
->flags
& SRI_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
);
449 snprintf(msg
, sizeof(msg
), "%s %s %s %d",
450 sentinelRedisInstanceTypeStr(ri
),
451 ri
->name
, ri
->addr
->ip
, ri
->addr
->port
);
458 /* Use vsprintf for the rest of the formatting if any. */
459 if (fmt
[0] != '\0') {
461 vsnprintf(msg
+strlen(msg
), sizeof(msg
)-strlen(msg
), fmt
, ap
);
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
);
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
);
478 /* Call the notification script if applicable. */
479 if (level
== REDIS_WARNING
&& ri
!= NULL
) {
480 sentinelRedisInstance
*master
= (ri
->flags
& SRI_MASTER
) ?
482 if (master
->notify_script
) {
483 sentinelCallNotificationScript(master
->notify_script
,type
,msg
);
488 /* ========================== sentinelRedisInstance ========================= */
490 /* Create a redis instance, the following fields must be populated by the
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.
495 * If SRI_MASTER is set into initial flags the instance is added to
496 * sentinel.masters table.
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.
501 * If the instance is a slave or sentinel, the name parameter is ignored and
502 * is created automatically as hostname:port.
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.
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
;
514 char slavename
[128], *sdsname
;
516 redisAssert(flags
& (SRI_MASTER
|SRI_SLAVE
|SRI_SENTINEL
));
517 redisAssert((flags
& SRI_MASTER
) || master
!= NULL
);
519 /* Check address validity. */
520 addr
= createSentinelAddr(hostname
,port
);
521 if (addr
== NULL
) return NULL
;
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
);
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
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
)) {
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
;
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
);
574 ri
->parallel_syncs
= SENTINEL_DEFAULT_PARALLEL_SYNCS
;
576 ri
->slaves
= dictCreate(&instancesDictType
,NULL
);
577 ri
->info_refresh
= 0;
579 /* Failover state. */
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
;
589 /* Add into the right table. */
590 dictAdd(table
, ri
->name
, ri
);
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
);
603 /* Release hiredis connections. */
604 if (ri
->cc
) sentinelKillLink(ri
,ri
->cc
);
605 if (ri
->pc
) sentinelKillLink(ri
,ri
->pc
);
607 /* Free other resources. */
610 sdsfree(ri
->notify_script
);
611 sdsfree(ri
->client_reconfig_script
);
612 sdsfree(ri
->slave_master_host
);
614 releaseSentinelAddr(ri
->addr
);
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
;
623 /* Lookup a slave in a master Redis instance, by ip and port. */
624 sentinelRedisInstance
*sentinelRedisInstanceLookupSlave(
625 sentinelRedisInstance
*ri
, char *ip
, int port
)
628 sentinelRedisInstance
*slave
;
630 redisAssert(ri
->flags
& SRI_MASTER
);
631 key
= sdscatprintf(sdsempty(),"%s:%d",ip
,port
);
632 slave
= dictFetchValue(ri
->slaves
,key
);
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";
645 /* This function removes all the instances found in the dictionary of instances
646 * 'd', having either:
648 * 1) The same ip/port as specified.
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.
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.
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).
665 * The function returns the number of Sentinels removed. */
666 int removeMatchingSentinelsFromMaster(sentinelRedisInstance
*master
, char *ip
, int port
, char *runid
) {
671 di
= dictGetSafeIterator(master
->sentinels
);
672 while((de
= dictNext(di
)) != NULL
) {
673 sentinelRedisInstance
*ri
= dictGetVal(de
);
675 if ((ri
->runid
&& runid
&& strcmp(ri
->runid
,runid
) == 0) ||
676 (ip
&& strcmp(ri
->addr
->ip
,ip
) == 0 && port
== ri
->addr
->port
))
678 dictDelete(master
->sentinels
,ri
->name
);
682 dictReleaseIterator(di
);
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
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
) {
695 sentinelRedisInstance
*instance
= NULL
;
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
);
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
)))
711 dictReleaseIterator(di
);
715 /* Simple master lookup by name */
716 sentinelRedisInstance
*sentinelGetMasterByName(char *name
) {
717 sentinelRedisInstance
*ri
;
718 sds sdsname
= sdsnew(name
);
720 ri
= dictFetchValue(sentinel
.masters
,sdsname
);
725 /* Add the specified flags to all the instances in the specified dictionary. */
726 void sentinelAddFlagsToDictOfRedisInstances(dict
*instances
, int flags
) {
730 di
= dictGetIterator(instances
);
731 while((de
= dictNext(di
)) != NULL
) {
732 sentinelRedisInstance
*ri
= dictGetVal(de
);
735 dictReleaseIterator(di
);
738 /* Remove the specified flags to all the instances in the specified
740 void sentinelDelFlagsToDictOfRedisInstances(dict
*instances
, int flags
) {
744 di
= dictGetIterator(instances
);
745 while((de
= dictNext(di
)) != NULL
) {
746 sentinelRedisInstance
*ri
= dictGetVal(de
);
749 dictReleaseIterator(di
);
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).
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
;
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
;
778 sdsfree(ri
->slave_master_host
);
780 ri
->slave_master_host
= NULL
;
781 if (flags
& SENTINEL_GENERATE_EVENT
)
782 sentinelEvent(REDIS_WARNING
,"+reset-master",ri
,"%@");
785 /* Call sentinelResetMaster() on every master with a name matching the specified
787 int sentinelResetMastersByPattern(char *pattern
, int flags
) {
792 di
= dictGetIterator(sentinel
.masters
);
793 while((de
= dictNext(di
)) != NULL
) {
794 sentinelRedisInstance
*ri
= dictGetVal(de
);
797 if (stringmatch(pattern
,ri
->name
,0)) {
798 sentinelResetMaster(ri
,flags
);
803 dictReleaseIterator(di
);
807 /* Reset the specified master with sentinelResetMaster(), and also change
808 * the ip:port address, but take the name of the instance unmodified.
810 * This is used to handle the +switch-master and +redirect-to-master events.
812 * The function returns REDIS_ERR if the address can't be resolved for some
813 * reason. Otherwise REDIS_OK is returned.
815 * TODO: make this reset so that original sentinels are re-added with
816 * same ip / port / runid.
819 int sentinelResetMasterAndChangeAddress(sentinelRedisInstance
*master
, char *ip
, int port
) {
820 sentinelAddr
*oldaddr
, *newaddr
;
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
);
833 /* ============================ Config handling ============================= */
834 char *sentinelHandleConfiguration(char **argv
, int argc
) {
835 sentinelRedisInstance
*ri
;
837 if (!strcasecmp(argv
[0],"monitor") && argc
== 5) {
838 /* monitor <name> <host> <port> <quorum> */
839 int quorum
= atoi(argv
[4]);
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
)
846 case EBUSY
: return "Duplicated master name.";
847 case ENOENT
: return "Can't resolve master instance hostname.";
848 case EINVAL
: return "Invalid port number";
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]);
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.";
873 ri
->flags
|= SRI_CAN_FAILOVER
;
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]);
882 return "Unrecognized sentinel configuration statement.";
887 /* ====================== hiredis connection handling ======================= */
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
;
894 ri
->flags
|= SRI_DISCONNECTED
;
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
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
;
908 if (ri
== NULL
) return; /* The instance no longer exists. */
910 pubsub
= (ri
->pc
== c
);
911 sentinelEvent(REDIS_DEBUG
, pubsub
? "-pubsub-link" : "-cmd-link", ri
,
912 "%@ #%s", c
->errstr
);
917 ri
->flags
|= SRI_DISCONNECTED
;
920 void sentinelLinkEstablishedCallback(const redisAsyncContext
*c
, int status
) {
921 if (status
!= REDIS_OK
) {
922 sentinelDisconnectInstanceFromContext(c
);
924 sentinelRedisInstance
*ri
= c
->data
;
925 int pubsub
= (ri
->pc
== c
);
927 sentinelEvent(REDIS_DEBUG
, pubsub
? "+pubsub-link" : "+cmd-link", ri
,
932 void sentinelDisconnectCallback(const redisAsyncContext
*c
, int status
) {
933 sentinelDisconnectInstanceFromContext(c
);
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;
942 /* Commands connection. */
943 if (ri
->cc
== NULL
) {
944 ri
->cc
= redisAsyncConnect(ri
->addr
->ip
,ri
->addr
->port
);
946 sentinelEvent(REDIS_DEBUG
,"-cmd-link-reconnection",ri
,"%@ #%s",
948 sentinelKillLink(ri
,ri
->cc
);
950 ri
->cc_conn_time
= mstime();
952 redisAeAttach(server
.el
,ri
->cc
);
953 redisAsyncSetConnectCallback(ri
->cc
,
954 sentinelLinkEstablishedCallback
);
955 redisAsyncSetDisconnectCallback(ri
->cc
,
956 sentinelDisconnectCallback
);
960 if ((ri
->flags
& SRI_MASTER
) && ri
->pc
== NULL
) {
961 ri
->pc
= redisAsyncConnect(ri
->addr
->ip
,ri
->addr
->port
);
963 sentinelEvent(REDIS_DEBUG
,"-pubsub-link-reconnection",ri
,"%@ #%s",
965 sentinelKillLink(ri
,ri
->pc
);
969 ri
->pc_conn_time
= mstime();
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
);
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
;
995 /* ======================== Redis instances pinging ======================== */
997 /* Process the INFO output from masters. */
998 void sentinelRefreshInstanceInfo(sentinelRedisInstance
*ri
, const char *info
) {
1002 int runid_changed
= 0; /* true if runid changed. */
1003 int first_runid
= 0; /* true if this is the first runid we receive. */
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;
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
;
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);
1021 if (strncmp(ri
->runid
,l
+7,40) != 0) {
1023 sentinelEvent(REDIS_NOTICE
,"+reboot",ri
,"%@");
1025 ri
->runid
= sdsnewlen(l
+7,40);
1030 /* slave0:<ip>,<port>,<state> */
1031 if ((ri
->flags
& SRI_MASTER
) &&
1033 !memcmp(l
,"slave",5) && isdigit(l
[5]))
1035 char *ip
, *port
, *end
;
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. */
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
)
1051 sentinelEvent(REDIS_NOTICE
,"+slave",slave
,"%@");
1056 /* master_link_down_since_seconds:<seconds> */
1057 if (sdslen(l
) >= 32 &&
1058 !memcmp(l
,"master_link_down_since_seconds",30))
1060 ri
->master_link_down_time
= strtoll(l
+31,NULL
,10)*1000;
1064 if (!memcmp(l
,"role:master",11)) role
= SRI_MASTER
;
1065 else if (!memcmp(l
,"role:slave",10)) role
= SRI_SLAVE
;
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);
1074 /* master_port:<port> */
1075 if (sdslen(l
) >= 12 && !memcmp(l
,"master_port:",12))
1076 ri
->slave_master_port
= atoi(l
+12);
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
;
1087 ri
->info_refresh
= mstime();
1088 sdsfreesplitres(lines
,numlines
);
1090 if (sentinel
.tilt
) return;
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
,
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
);
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
))
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
1118 * Log the event and remove the slave. */
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
);
1125 } else if (ri
->flags
& SRI_PROMOTED
) {
1126 /* If this is a promoted slave we can change state to the
1127 * failover state machine. */
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
))
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",
1141 /* Otherwise we interpret this as the start of the failover. */
1143 (ri
->master
->flags
& SRI_FAILOVER_IN_PROGRESS
) == 0)
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
1155 sentinelAddFlagsToDictOfRedisInstances(ri
->master
->slaves
,
1161 /* Detect if the slave that is in the process of being reconfigured
1163 if ((ri
->flags
& SRI_SLAVE
) && role
== SRI_SLAVE
&&
1164 (ri
->flags
& (SRI_RECONF_SENT
|SRI_RECONF_INPROG
)))
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
)
1173 ri
->flags
&= ~SRI_RECONF_SENT
;
1174 ri
->flags
|= SRI_RECONF_INPROG
;
1175 sentinelEvent(REDIS_NOTICE
,"+slave-reconf-inprog",ri
,"%@");
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
)
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();
1193 void sentinelInfoReplyCallback(redisAsyncContext
*c
, void *reply
, void *privdata
) {
1194 sentinelRedisInstance
*ri
= c
->data
;
1197 if (ri
) ri
->pending_commands
--;
1198 if (!reply
|| !ri
) return;
1201 if (r
->type
== REDIS_REPLY_STRING
) {
1202 sentinelRefreshInstanceInfo(ri
,r
->str
);
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
;
1211 if (ri
) ri
->pending_commands
--;
1214 void sentinelPingReplyCallback(redisAsyncContext
*c
, void *reply
, void *privdata
) {
1215 sentinelRedisInstance
*ri
= c
->data
;
1218 if (ri
) ri
->pending_commands
--;
1219 if (!reply
|| !ri
) return;
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)
1230 ri
->last_avail_time
= mstime();
1233 ri
->last_pong_time
= mstime();
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
;
1242 if (ri
) ri
->pending_commands
--;
1243 if (!reply
|| !ri
) return;
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();
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
;
1258 if (!reply
|| !ri
) return;
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();
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
||
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;
1275 /* We are not interested in meeting ourselves */
1276 if (strstr(r
->element
[2]->str
,server
.runid
) != NULL
) return;
1279 int numtokens
, port
, removed
, canfailover
;
1280 char **token
= sdssplitlen(r
->element
[2]->str
,
1283 sentinelRedisInstance
*sentinel
;
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]);
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
,
1299 sentinelEvent(REDIS_NOTICE
,"-dup-sentinel",ri
,
1300 "%@ #duplicate of %s:%d or %s",
1301 token
[0],port
,token
[2]);
1304 /* Add the new sentinel. */
1305 sentinel
= createSentinelRedisInstance(NULL
,SRI_SENTINEL
,
1306 token
[0],port
,ri
->quorum
,ri
);
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,
1312 sentinel
->runid
= sdsnew(token
[2]);
1316 /* Update the state of the Sentinel. */
1318 sentinel
->last_hello_time
= mstime();
1320 sentinel
->flags
|= SRI_CAN_FAILOVER
;
1322 sentinel
->flags
&= ~SRI_CAN_FAILOVER
;
1325 sdsfreesplitres(token
,numtokens
);
1329 void sentinelPingInstance(sentinelRedisInstance
*ri
) {
1330 mstime_t now
= mstime();
1331 mstime_t info_period
;
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;
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;
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
))) {
1354 info_period
= SENTINEL_INFO_PERIOD
;
1357 if ((ri
->flags
& SRI_SENTINEL
) == 0 &&
1358 (ri
->info_refresh
== 0 ||
1359 (now
- ri
->info_refresh
) > info_period
))
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
)
1375 /* PUBLISH hello messages only to masters. */
1376 struct sockaddr_in sa
;
1377 socklen_t salen
= sizeof(sa
);
1379 if (getsockname(ri
->cc
->c
.fd
,(struct sockaddr
*)&sa
,&salen
) != -1) {
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
++;
1394 /* =========================== SENTINEL command ============================= */
1396 const char *sentinelFailoverStateStr(int 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";
1411 /* Redis instance to Redis protocol representation. */
1412 void addReplySentinelRedisInstance(redisClient
*c
, sentinelRedisInstance
*ri
) {
1413 char *flags
= sdsempty();
1417 mbl
= addDeferredMultiBulkLength(c
);
1419 addReplyBulkCString(c
,"name");
1420 addReplyBulkCString(c
,ri
->name
);
1423 addReplyBulkCString(c
,"ip");
1424 addReplyBulkCString(c
,ri
->addr
->ip
);
1427 addReplyBulkCString(c
,"port");
1428 addReplyBulkLongLong(c
,ri
->addr
->port
);
1431 addReplyBulkCString(c
,"runid");
1432 addReplyBulkCString(c
,ri
->runid
? ri
->runid
: "");
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,");
1452 if (sdslen(flags
) != 0) flags
= sdsrange(flags
,0,-2); /* remove last "," */
1453 addReplyBulkCString(c
,flags
);
1457 addReplyBulkCString(c
,"pending-commands");
1458 addReplyBulkLongLong(c
,ri
->pending_commands
);
1461 if (ri
->flags
& SRI_FAILOVER_IN_PROGRESS
) {
1462 addReplyBulkCString(c
,"failover-state");
1463 addReplyBulkCString(c
,(char*)sentinelFailoverStateStr(ri
->failover_state
));
1467 addReplyBulkCString(c
,"last-ok-ping-reply");
1468 addReplyBulkLongLong(c
,mstime() - ri
->last_avail_time
);
1471 addReplyBulkCString(c
,"last-ping-reply");
1472 addReplyBulkLongLong(c
,mstime() - ri
->last_pong_time
);
1475 if (ri
->flags
& SRI_S_DOWN
) {
1476 addReplyBulkCString(c
,"s-down-time");
1477 addReplyBulkLongLong(c
,mstime()-ri
->s_down_since_time
);
1481 if (ri
->flags
& SRI_O_DOWN
) {
1482 addReplyBulkCString(c
,"o-down-time");
1483 addReplyBulkLongLong(c
,mstime()-ri
->o_down_since_time
);
1487 /* Masters and Slaves */
1488 if (ri
->flags
& (SRI_MASTER
|SRI_SLAVE
)) {
1489 addReplyBulkCString(c
,"info-refresh");
1490 addReplyBulkLongLong(c
,mstime() - ri
->info_refresh
);
1495 if (ri
->flags
& SRI_MASTER
) {
1496 addReplyBulkCString(c
,"num-slaves");
1497 addReplyBulkLongLong(c
,dictSize(ri
->slaves
));
1500 addReplyBulkCString(c
,"num-other-sentinels");
1501 addReplyBulkLongLong(c
,dictSize(ri
->sentinels
));
1504 addReplyBulkCString(c
,"quorum");
1505 addReplyBulkLongLong(c
,ri
->quorum
);
1510 if (ri
->flags
& SRI_SLAVE
) {
1511 addReplyBulkCString(c
,"master-link-down-time");
1512 addReplyBulkLongLong(c
,ri
->master_link_down_time
);
1515 addReplyBulkCString(c
,"master-link-status");
1516 addReplyBulkCString(c
,
1517 (ri
->slave_master_link_status
== SENTINEL_MASTER_LINK_STATUS_UP
) ?
1521 addReplyBulkCString(c
,"master-host");
1522 addReplyBulkCString(c
,
1523 ri
->slave_master_host
? ri
->slave_master_host
: "?");
1526 addReplyBulkCString(c
,"master-port");
1527 addReplyBulkLongLong(c
,ri
->slave_master_port
);
1531 /* Only sentinels */
1532 if (ri
->flags
& SRI_SENTINEL
) {
1533 addReplyBulkCString(c
,"last-hello-message");
1534 addReplyBulkLongLong(c
,mstime() - ri
->last_hello_time
);
1537 addReplyBulkCString(c
,"can-failover-its-master");
1538 addReplyBulkLongLong(c
,(ri
->flags
& SRI_CAN_FAILOVER
) != 0);
1541 if (ri
->flags
& SRI_MASTER_DOWN
) {
1542 addReplyBulkCString(c
,"subjective-leader");
1543 addReplyBulkCString(c
,ri
->leader
? ri
->leader
: "?");
1548 setDeferredMultiBulkLength(c
,mbl
,fields
*2);
1551 /* Output a number of instances contanined inside a dictionary as
1552 * Redis protocol. */
1553 void addReplyDictOfRedisInstances(redisClient
*c
, dict
*instances
) {
1557 di
= dictGetIterator(instances
);
1558 addReplyMultiBulkLen(c
,dictSize(instances
));
1559 while((de
= dictNext(di
)) != NULL
) {
1560 sentinelRedisInstance
*ri
= dictGetVal(de
);
1562 addReplySentinelRedisInstance(c
,ri
);
1564 dictReleaseIterator(di
);
1567 /* Lookup the named master into sentinel.masters.
1568 * If the master is not found reply to the client with an error and returns
1570 sentinelRedisInstance
*sentinelGetMasterByNameOrReplyError(redisClient
*c
,
1573 sentinelRedisInstance
*ri
;
1575 ri
= dictFetchValue(sentinel
.masters
,c
->argv
[2]->ptr
);
1577 addReplyError(c
,"No such master with that name");
1583 void sentinelCommand(redisClient
*c
) {
1584 if (!strcasecmp(c
->argv
[1]->ptr
,"masters")) {
1585 /* SENTINEL MASTERS */
1586 if (c
->argc
!= 2) goto numargserr
;
1588 addReplyDictOfRedisInstances(c
,sentinel
.masters
);
1589 } else if (!strcasecmp(c
->argv
[1]->ptr
,"slaves")) {
1590 /* SENTINEL SLAVES <master-name> */
1591 sentinelRedisInstance
*ri
;
1593 if (c
->argc
!= 3) goto numargserr
;
1594 if ((ri
= sentinelGetMasterByNameOrReplyError(c
,c
->argv
[2])) == NULL
)
1596 addReplyDictOfRedisInstances(c
,ri
->slaves
);
1597 } else if (!strcasecmp(c
->argv
[1]->ptr
,"sentinels")) {
1598 /* SENTINEL SENTINELS <master-name> */
1599 sentinelRedisInstance
*ri
;
1601 if (c
->argc
!= 3) goto numargserr
;
1602 if ((ri
= sentinelGetMasterByNameOrReplyError(c
,c
->argv
[2])) == NULL
)
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
;
1612 if (c
->argc
!= 4) goto numargserr
;
1613 if (getLongFromObjectOrReply(c
,c
->argv
[3],&port
,NULL
) != REDIS_OK
)
1615 ri
= getSentinelRedisInstanceByAddrAndRunID(sentinel
.masters
,
1616 c
->argv
[2]->ptr
,port
,NULL
);
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
))
1623 if (ri
) leader
= sentinelGetSubjectiveLeader(ri
);
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
;
1638 if (c
->argc
!= 3) goto numargserr
;
1639 ri
= sentinelGetMasterByName(c
->argv
[2]->ptr
);
1641 addReply(c
,shared
.nullmultibulk
);
1643 sentinelAddr
*addr
= ri
->addr
;
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
);
1652 addReplyErrorFormat(c
,"Unknown sentinel subcommand '%s'",
1653 (char*)c
->argv
[1]->ptr
);
1658 addReplyErrorFormat(c
,"Wrong number of commands for 'sentinel %s'",
1659 (char*)c
->argv
[1]->ptr
);
1662 /* ===================== SENTINEL availability checks ======================= */
1664 /* Is this instance down from our point of view? */
1665 void sentinelCheckSubjectivelyDown(sentinelRedisInstance
*ri
) {
1666 mstime_t elapsed
= mstime() - ri
->last_avail_time
;
1668 /* Check if we are in need for a reconnection of one of the
1669 * links, because we are detecting low activity.
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. */
1675 (mstime() - ri
->cc_conn_time
) > SENTINEL_MIN_LINK_RECONNECT_PERIOD
&&
1676 (mstime() - ri
->last_pong_time
) > (ri
->down_after_period
/2))
1678 sentinelKillLink(ri
,ri
->cc
);
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.
1687 (mstime() - ri
->pc_conn_time
) > SENTINEL_MIN_LINK_RECONNECT_PERIOD
&&
1688 (mstime() - ri
->pc_last_activity
) > (SENTINEL_PUBLISH_PERIOD
*3))
1690 sentinelKillLink(ri
,ri
->pc
);
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
;
1702 /* Is subjectively up */
1703 if (ri
->flags
& SRI_S_DOWN
) {
1704 sentinelEvent(REDIS_WARNING
,"-sdown",ri
,"%@");
1705 ri
->flags
&= ~SRI_S_DOWN
;
1710 /* Is this instance down accordingly to the configured quorum? */
1711 void sentinelCheckObjectivelyDown(sentinelRedisInstance
*master
) {
1714 int quorum
= 0, odown
= 0;
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
);
1724 if (ri
->flags
& SRI_MASTER_DOWN
) quorum
++;
1726 dictReleaseIterator(di
);
1727 if (quorum
>= master
->quorum
) odown
= 1;
1730 /* Set the flag accordingly to the outcome. */
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();
1739 if (master
->flags
& SRI_O_DOWN
) {
1740 sentinelEvent(REDIS_WARNING
,"-odown",master
,"%@");
1741 master
->flags
&= ~SRI_O_DOWN
;
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
;
1752 if (ri
) ri
->pending_commands
--;
1753 if (!reply
|| !ri
) return;
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
)
1763 ri
->last_master_down_reply_time
= mstime();
1764 if (r
->element
[0]->integer
== 1) {
1765 ri
->flags
|= SRI_MASTER_DOWN
;
1767 ri
->flags
&= ~SRI_MASTER_DOWN
;
1769 sdsfree(ri
->leader
);
1770 ri
->leader
= sdsnew(r
->element
[1]->str
);
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
) {
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
;
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
);
1796 /* Only ask if master is down to other sentinels if:
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)
1803 if (ri
->flags
& SRI_DISCONNECTED
) continue;
1804 if (mstime() - ri
->last_master_down_reply_time
< SENTINEL_ASK_PERIOD
)
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
++;
1815 dictReleaseIterator(di
);
1818 /* =============================== FAILOVER ================================= */
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:
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).
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.
1834 int compareRunID(const void *a
, const void *b
) {
1835 char **aptrptr
= (char**)a
, **bptrptr
= (char**)b
;
1836 return strcasecmp(*aptrptr
, *bptrptr
);
1839 char *sentinelGetSubjectiveLeader(sentinelRedisInstance
*master
) {
1843 zmalloc(sizeof(char*)*(dictSize(master
->sentinels
)+1));
1845 char *leader
= NULL
;
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
;
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
;
1857 if (lag
> SENTINEL_INFO_VALIDITY_TIME
||
1858 !(ri
->flags
& SRI_CAN_FAILOVER
) ||
1859 (ri
->flags
& SRI_DISCONNECTED
) ||
1862 instance
[instances
++] = ri
->runid
;
1864 dictReleaseIterator(di
);
1866 /* If we have at least one instance passing our checks, order the array
1869 qsort(instance
,instances
,sizeof(char*),compareRunID
);
1870 leader
= sdsnew(instance
[0]);
1876 struct sentinelLeader
{
1878 unsigned long votes
;
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
);
1888 oldval
= dictGetUnsignedIntegerVal(de
);
1889 dictSetUnsignedIntegerVal(de
,oldval
+1);
1891 de
= dictAddRaw(counters
,runid
);
1892 redisAssert(de
!= NULL
);
1893 dictSetUnsignedIntegerVal(de
,1);
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
) {
1903 unsigned int voters
= 0, voters_quorum
;
1905 char *winner
= NULL
;
1907 redisAssert(master
->flags
& (SRI_O_DOWN
|SRI_FAILOVER_IN_PROGRESS
));
1908 counters
= dictCreate(&leaderVotesDictType
,NULL
);
1910 /* Count my vote. */
1911 myvote
= sentinelGetSubjectiveLeader(master
);
1913 sentinelObjectiveLeaderIncr(counters
,myvote
);
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
);
1931 dictReleaseIterator(di
);
1932 voters_quorum
= voters
/2+1;
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. */
1938 uint64_t max_votes
= 0; /* Max votes so far. */
1940 di
= dictGetIterator(counters
);
1941 while((de
= dictNext(di
)) != NULL
) {
1942 uint64_t votes
= dictGetUnsignedIntegerVal(de
);
1944 if (max_votes
< votes
) {
1946 winner
= dictGetKey(de
);
1949 dictReleaseIterator(di
);
1950 if (winner
&& (max_votes
< voters_quorum
|| max_votes
< master
->quorum
))
1953 winner
= winner
? sdsnew(winner
) : NULL
;
1955 dictRelease(counters
);
1959 /* This function checks if there are the conditions to start the failover,
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.
1966 * If the conditions are met we flag the master as SRI_FAILOVER_IN_PROGRESS
1967 * and SRI_I_AM_THE_LEADER.
1969 void sentinelStartFailover(sentinelRedisInstance
*master
) {
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;
1980 leader
= sentinelGetObjectiveLeader(master
);
1981 isleader
= leader
&& strcasecmp(leader
,server
.runid
) == 0;
1984 /* If I'm not the leader, I can't failover for sure. */
1985 if (!isleader
) return;
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.
1994 mstime_t elapsed
= mstime() - master
->failover_state_change_time
;
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.
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
,
2017 /* Brand new failover as SRI_FAILOVER_IN_PROGRESS was not set. */
2018 master
->failover_state
= SENTINEL_FAILOVER_STATE_WAIT_START
;
2021 master
->flags
|= SRI_FAILOVER_IN_PROGRESS
|SRI_I_AM_THE_LEADER
;
2022 sentinelEvent(REDIS_WARNING
,"+failover-triggered",master
,"%@");
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());
2034 master
->failover_state_change_time
= mstime();
2037 /* Select a suitable slave to promote. The current algorithm only uses
2038 * the following parameters:
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).
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.
2050 * The function returns the pointer to the selected slave, otherwise
2051 * NULL if no suitable slave was found.
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
);
2062 sentinelRedisInstance
*sentinelSelectSlave(sentinelRedisInstance
*master
) {
2063 sentinelRedisInstance
**instance
=
2064 zmalloc(sizeof(instance
[0])*dictSize(master
->slaves
));
2065 sentinelRedisInstance
*selected
= NULL
;
2069 mstime_t max_master_down_time
;
2071 max_master_down_time
= (mstime() - master
->s_down_since_time
) +
2072 (master
->down_after_period
* 10);
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
;
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
;
2085 dictReleaseIterator(di
);
2087 qsort(instance
,instances
,sizeof(sentinelRedisInstance
*),
2088 compareSlavesForPromotion
);
2089 selected
= instance
[0];
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
,"%@");
2104 void sentinelFailoverSelectSlave(sentinelRedisInstance
*ri
) {
2105 sentinelRedisInstance
*slave
= sentinelSelectSlave(ri
);
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
;
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",
2126 void sentinelFailoverSendSlaveOfNoOne(sentinelRedisInstance
*ri
) {
2129 if (ri
->promoted_slave
->flags
& SRI_DISCONNECTED
) return;
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();
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
;
2150 if (elapsed
>= SENTINEL_PROMOTION_RETRY_PERIOD
) {
2151 sentinelEvent(REDIS_WARNING
,"-promotion-timeout",ri
->promoted_slave
,
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
;
2161 void sentinelFailoverDetectEnd(sentinelRedisInstance
*master
) {
2162 int not_reconfigured
= 0, timeout
= 0;
2165 mstime_t elapsed
= mstime() - master
->failover_state_change_time
;
2167 /* We can't consider failover finished if the promoted slave is
2169 if (master
->promoted_slave
== NULL
||
2170 master
->promoted_slave
->flags
& SRI_S_DOWN
) return;
2172 /* The failover terminates once all the reachable slaves are properly
2174 di
= dictGetIterator(master
->slaves
);
2175 while((de
= dictNext(di
)) != NULL
) {
2176 sentinelRedisInstance
*slave
= dictGetVal(de
);
2178 if (slave
->flags
& (SRI_PROMOTED
|SRI_RECONF_DONE
)) continue;
2179 if (slave
->flags
& SRI_S_DOWN
) continue;
2182 dictReleaseIterator(di
);
2184 /* Force end of failover on timeout. */
2185 if (elapsed
> master
->failover_timeout
) {
2186 not_reconfigured
= 0;
2188 sentinelEvent(REDIS_WARNING
,"+failover-end-for-timeout",master
,"%@");
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();
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
)) {
2203 char master_port
[32];
2205 ll2string(master_port
,sizeof(master_port
),
2206 master
->promoted_slave
->addr
->port
);
2208 di
= dictGetIterator(master
->slaves
);
2209 while((de
= dictNext(di
)) != NULL
) {
2210 sentinelRedisInstance
*slave
= dictGetVal(de
);
2214 (SRI_RECONF_DONE
|SRI_RECONF_SENT
|SRI_DISCONNECTED
)) continue;
2216 retval
= redisAsyncCommand(slave
->cc
,
2217 sentinelDiscardReplyCallback
, NULL
, "SLAVEOF %s %s",
2218 master
->promoted_slave
->addr
->ip
,
2220 if (retval
== REDIS_OK
) {
2221 sentinelEvent(REDIS_NOTICE
,"+slave-reconf-sent-be",slave
,"%@");
2222 slave
->flags
|= SRI_RECONF_SENT
;
2225 dictReleaseIterator(di
);
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
) {
2234 int in_progress
= 0;
2236 di
= dictGetIterator(master
->slaves
);
2237 while((de
= dictNext(di
)) != NULL
) {
2238 sentinelRedisInstance
*slave
= dictGetVal(de
);
2240 if (slave
->flags
& (SRI_RECONF_SENT
|SRI_RECONF_INPROG
))
2243 dictReleaseIterator(di
);
2245 di
= dictGetIterator(master
->slaves
);
2246 while(in_progress
< master
->parallel_syncs
&&
2247 (de
= dictNext(di
)) != NULL
)
2249 sentinelRedisInstance
*slave
= dictGetVal(de
);
2251 char master_port
[32];
2253 /* Skip the promoted slave, and already configured slaves. */
2254 if (slave
->flags
& (SRI_PROMOTED
|SRI_RECONF_DONE
)) continue;
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
)
2262 sentinelEvent(REDIS_NOTICE
,"-slave-reconf-sent-timeout",slave
,"%@");
2263 slave
->flags
&= ~SRI_RECONF_SENT
;
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
))
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
,
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
,"%@");
2286 dictReleaseIterator(di
);
2287 sentinelFailoverDetectEnd(master
);
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.
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
2297 void sentinelFailoverSwitchToPromotedSlave(sentinelRedisInstance
*master
) {
2298 sentinelRedisInstance
*ref
= master
->promoted_slave
?
2299 master
->promoted_slave
: master
;
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
);
2305 sentinelResetMasterAndChangeAddress(master
,ref
->addr
->ip
,ref
->addr
->port
);
2308 void sentinelFailoverStateMachine(sentinelRedisInstance
*ri
) {
2309 redisAssert(ri
->flags
& SRI_MASTER
);
2311 if (!(ri
->flags
& SRI_FAILOVER_IN_PROGRESS
)) return;
2313 switch(ri
->failover_state
) {
2314 case SENTINEL_FAILOVER_STATE_WAIT_START
:
2315 sentinelFailoverWaitStart(ri
);
2317 case SENTINEL_FAILOVER_STATE_SELECT_SLAVE
:
2318 sentinelFailoverSelectSlave(ri
);
2320 case SENTINEL_FAILOVER_STATE_SEND_SLAVEOF_NOONE
:
2321 sentinelFailoverSendSlaveOfNoOne(ri
);
2323 case SENTINEL_FAILOVER_STATE_WAIT_PROMOTION
:
2324 sentinelFailoverWaitPromotion(ri
);
2326 case SENTINEL_FAILOVER_STATE_RECONF_SLAVES
:
2327 sentinelFailoverReconfNextSlave(ri
);
2329 case SENTINEL_FAILOVER_STATE_DETECT_END
:
2330 sentinelFailoverDetectEnd(ri
);
2335 /* The following is called only for master instances and will abort the
2336 * failover process if:
2338 * 1) The failover is in progress.
2339 * 2) We already promoted a slave.
2340 * 3) The promoted slave is in extended SDOWN condition.
2342 void sentinelAbortFailoverIfNeeded(sentinelRedisInstance
*ri
) {
2346 /* Failover is in progress? Do we have a promoted slave? */
2347 if (!(ri
->flags
& SRI_FAILOVER_IN_PROGRESS
) || !ri
->promoted_slave
) return;
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;
2354 sentinelEvent(REDIS_WARNING
,"-failover-abort-x-sdown",ri
->promoted_slave
,"%@");
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. */
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];
2368 ll2string(master_port
,sizeof(master_port
),ri
->addr
->port
);
2369 retval
= redisAsyncCommand(slave
->cc
,
2370 sentinelDiscardReplyCallback
, NULL
, "SLAVEOF %s %s",
2373 if (retval
== REDIS_OK
)
2374 sentinelEvent(REDIS_NOTICE
,"-slave-reconf-undo",slave
,"%@");
2376 slave
->flags
&= ~(SRI_RECONF_SENT
|SRI_RECONF_INPROG
|SRI_RECONF_DONE
);
2378 dictReleaseIterator(di
);
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
;
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 * -------------------------------------------------------------------------- */
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
);
2399 /* Masters and slaves */
2400 if (ri
->flags
& (SRI_MASTER
|SRI_SLAVE
)) {
2401 /* Nothing so far. */
2405 if (ri
->flags
& SRI_MASTER
) {
2406 sentinelAskMasterStateToOtherSentinels(ri
);
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;
2416 sentinelEvent(REDIS_WARNING
,"-tilt",NULL
,"#tilt mode exited");
2419 /* Every kind of instance */
2420 sentinelCheckSubjectivelyDown(ri
);
2422 /* Masters and slaves */
2423 if (ri
->flags
& (SRI_MASTER
|SRI_SLAVE
)) {
2424 /* Nothing so far. */
2428 if (ri
->flags
& SRI_MASTER
) {
2429 sentinelCheckObjectivelyDown(ri
);
2430 sentinelStartFailover(ri
);
2431 sentinelFailoverStateMachine(ri
);
2432 sentinelAbortFailoverIfNeeded(ri
);
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
) {
2441 sentinelRedisInstance
*switch_to_promoted
= NULL
;
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
);
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
;
2457 if (switch_to_promoted
)
2458 sentinelFailoverSwitchToPromotedSlave(switch_to_promoted
);
2459 dictReleaseIterator(di
);
2462 /* This function checks if we need to enter the TITL mode.
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:
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.
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.
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
;
2485 if (delta
< 0 || delta
> SENTINEL_TILT_TRIGGER
) {
2487 sentinel
.tilt_start_time
= mstime();
2488 sentinelEvent(REDIS_WARNING
,"+tilt",NULL
,"#tilt mode entered");
2490 sentinel
.previous_time
= mstime();
2493 void sentinelTimer(void) {
2494 sentinelCheckTiltCondition();
2495 sentinelHandleDictOfRedisInstances(sentinel
.masters
);