xref: /redis-3.2.3/src/sentinel.c (revision f3fd58eb)
1 /* Redis Sentinel implementation
2  *
3  * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  *   * Redistributions of source code must retain the above copyright notice,
10  *     this list of conditions and the following disclaimer.
11  *   * Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution.
14  *   * Neither the name of Redis nor the names of its contributors may be used
15  *     to endorse or promote products derived from this software without
16  *     specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 #include "redis.h"
32 #include "hiredis.h"
33 #include "async.h"
34 
35 #include <ctype.h>
36 #include <arpa/inet.h>
37 #include <sys/socket.h>
38 #include <sys/wait.h>
39 #include <fcntl.h>
40 
41 extern char **environ;
42 
43 #define REDIS_SENTINEL_PORT 26379
44 
45 /* ======================== Sentinel global state =========================== */
46 
47 /* Address object, used to describe an ip:port pair. */
48 typedef struct sentinelAddr {
49     char *ip;
50     int port;
51 } sentinelAddr;
52 
53 /* A Sentinel Redis Instance object is monitoring. */
54 #define SRI_MASTER  (1<<0)
55 #define SRI_SLAVE   (1<<1)
56 #define SRI_SENTINEL (1<<2)
57 #define SRI_DISCONNECTED (1<<3)
58 #define SRI_S_DOWN (1<<4)   /* Subjectively down (no quorum). */
59 #define SRI_O_DOWN (1<<5)   /* Objectively down (confirmed by others). */
60 #define SRI_MASTER_DOWN (1<<6) /* A Sentinel with this flag set thinks that
61                                    its master is down. */
62 #define SRI_FAILOVER_IN_PROGRESS (1<<7) /* Failover is in progress for
63                                            this master. */
64 #define SRI_PROMOTED (1<<8)            /* Slave selected for promotion. */
65 #define SRI_RECONF_SENT (1<<9)     /* SLAVEOF <newmaster> sent. */
66 #define SRI_RECONF_INPROG (1<<10)   /* Slave synchronization in progress. */
67 #define SRI_RECONF_DONE (1<<11)     /* Slave synchronized with new master. */
68 #define SRI_FORCE_FAILOVER (1<<12)  /* Force failover with master up. */
69 #define SRI_SCRIPT_KILL_SENT (1<<13) /* SCRIPT KILL already sent on -BUSY */
70 
71 /* Note: times are in milliseconds. */
72 #define SENTINEL_INFO_PERIOD 10000
73 #define SENTINEL_PING_PERIOD 1000
74 #define SENTINEL_ASK_PERIOD 1000
75 #define SENTINEL_PUBLISH_PERIOD 2000
76 #define SENTINEL_DEFAULT_DOWN_AFTER 30000
77 #define SENTINEL_HELLO_CHANNEL "__sentinel__:hello"
78 #define SENTINEL_TILT_TRIGGER 2000
79 #define SENTINEL_TILT_PERIOD (SENTINEL_PING_PERIOD*30)
80 #define SENTINEL_DEFAULT_SLAVE_PRIORITY 100
81 #define SENTINEL_SLAVE_RECONF_TIMEOUT 10000
82 #define SENTINEL_DEFAULT_PARALLEL_SYNCS 1
83 #define SENTINEL_MIN_LINK_RECONNECT_PERIOD 15000
84 #define SENTINEL_DEFAULT_FAILOVER_TIMEOUT (60*3*1000)
85 #define SENTINEL_MAX_PENDING_COMMANDS 100
86 #define SENTINEL_ELECTION_TIMEOUT 10000
87 #define SENTINEL_MAX_DESYNC 1000
88 
89 /* Failover machine different states. */
90 #define SENTINEL_FAILOVER_STATE_NONE 0  /* No failover in progress. */
91 #define SENTINEL_FAILOVER_STATE_WAIT_START 1  /* Wait for failover_start_time*/
92 #define SENTINEL_FAILOVER_STATE_SELECT_SLAVE 2 /* Select slave to promote */
93 #define SENTINEL_FAILOVER_STATE_SEND_SLAVEOF_NOONE 3 /* Slave -> Master */
94 #define SENTINEL_FAILOVER_STATE_WAIT_PROMOTION 4 /* Wait slave to change role */
95 #define SENTINEL_FAILOVER_STATE_RECONF_SLAVES 5 /* SLAVEOF newmaster */
96 #define SENTINEL_FAILOVER_STATE_UPDATE_CONFIG 6 /* Monitor promoted slave. */
97 
98 #define SENTINEL_MASTER_LINK_STATUS_UP 0
99 #define SENTINEL_MASTER_LINK_STATUS_DOWN 1
100 
101 /* Generic flags that can be used with different functions.
102  * They use higher bits to avoid colliding with the function specific
103  * flags. */
104 #define SENTINEL_NO_FLAGS 0
105 #define SENTINEL_GENERATE_EVENT (1<<16)
106 #define SENTINEL_LEADER (1<<17)
107 #define SENTINEL_OBSERVER (1<<18)
108 
109 /* Script execution flags and limits. */
110 #define SENTINEL_SCRIPT_NONE 0
111 #define SENTINEL_SCRIPT_RUNNING 1
112 #define SENTINEL_SCRIPT_MAX_QUEUE 256
113 #define SENTINEL_SCRIPT_MAX_RUNNING 16
114 #define SENTINEL_SCRIPT_MAX_RUNTIME 60000 /* 60 seconds max exec time. */
115 #define SENTINEL_SCRIPT_MAX_RETRY 10
116 #define SENTINEL_SCRIPT_RETRY_DELAY 30000 /* 30 seconds between retries. */
117 
118 typedef struct sentinelRedisInstance {
119     int flags;      /* See SRI_... defines */
120     char *name;     /* Master name from the point of view of this sentinel. */
121     char *runid;    /* run ID of this instance. */
122     uint64_t config_epoch;  /* Configuration epoch. */
123     sentinelAddr *addr; /* Master host. */
124     redisAsyncContext *cc; /* Hiredis context for commands. */
125     redisAsyncContext *pc; /* Hiredis context for Pub / Sub. */
126     int pending_commands;   /* Number of commands sent waiting for a reply. */
127     mstime_t cc_conn_time; /* cc connection time. */
128     mstime_t pc_conn_time; /* pc connection time. */
129     mstime_t pc_last_activity; /* Last time we received any message. */
130     mstime_t last_avail_time; /* Last time the instance replied to ping with
131                                  a reply we consider valid. */
132     mstime_t last_ping_time;  /* Last time a pending ping was sent in the
133                                  context of the current command connection
134                                  with the instance. 0 if still not sent or
135                                  if pong already received. */
136     mstime_t last_pong_time;  /* Last time the instance replied to ping,
137                                  whatever the reply was. That's used to check
138                                  if the link is idle and must be reconnected. */
139     mstime_t last_pub_time;   /* Last time we sent hello via Pub/Sub. */
140     mstime_t last_hello_time; /* Only used if SRI_SENTINEL is set. Last time
141                                  we received a hello from this Sentinel
142                                  via Pub/Sub. */
143     mstime_t last_master_down_reply_time; /* Time of last reply to
144                                              SENTINEL is-master-down command. */
145     mstime_t s_down_since_time; /* Subjectively down since time. */
146     mstime_t o_down_since_time; /* Objectively down since time. */
147     mstime_t down_after_period; /* Consider it down after that period. */
148     mstime_t info_refresh;  /* Time at which we received INFO output from it. */
149 
150     /* Role and the first time we observed it.
151      * This is useful in order to delay replacing what the instance reports
152      * with our own configuration. We need to always wait some time in order
153      * to give a chance to the leader to report the new configuration before
154      * we do silly things. */
155     int role_reported;
156     mstime_t role_reported_time;
157     mstime_t slave_conf_change_time; /* Last time slave master addr changed. */
158 
159     /* Master specific. */
160     dict *sentinels;    /* Other sentinels monitoring the same master. */
161     dict *slaves;       /* Slaves for this master instance. */
162     unsigned int quorum;/* Number of sentinels that need to agree on failure. */
163     int parallel_syncs; /* How many slaves to reconfigure at same time. */
164     char *auth_pass;    /* Password to use for AUTH against master & slaves. */
165 
166     /* Slave specific. */
167     mstime_t master_link_down_time; /* Slave replication link down time. */
168     int slave_priority; /* Slave priority according to its INFO output. */
169     mstime_t slave_reconf_sent_time; /* Time at which we sent SLAVE OF <new> */
170     struct sentinelRedisInstance *master; /* Master instance if it's slave. */
171     char *slave_master_host;    /* Master host as reported by INFO */
172     int slave_master_port;      /* Master port as reported by INFO */
173     int slave_master_link_status; /* Master link status as reported by INFO */
174     unsigned long long slave_repl_offset; /* Slave replication offset. */
175     /* Failover */
176     char *leader;       /* If this is a master instance, this is the runid of
177                            the Sentinel that should perform the failover. If
178                            this is a Sentinel, this is the runid of the Sentinel
179                            that this Sentinel voted as leader. */
180     uint64_t leader_epoch; /* Epoch of the 'leader' field. */
181     uint64_t failover_epoch; /* Epoch of the currently started failover. */
182     int failover_state; /* See SENTINEL_FAILOVER_STATE_* defines. */
183     mstime_t failover_state_change_time;
184     mstime_t failover_start_time;   /* Last failover attempt start time. */
185     mstime_t failover_timeout;      /* Max time to refresh failover state. */
186     mstime_t failover_delay_logged; /* For what failover_start_time value we
187                                        logged the failover delay. */
188     struct sentinelRedisInstance *promoted_slave; /* Promoted slave instance. */
189     /* Scripts executed to notify admin or reconfigure clients: when they
190      * are set to NULL no script is executed. */
191     char *notification_script;
192     char *client_reconfig_script;
193     sds info; /* cached INFO output */
194 } sentinelRedisInstance;
195 
196 /* Main state. */
197 struct sentinelState {
198     uint64_t current_epoch;     /* Current epoch. */
199     dict *masters;      /* Dictionary of master sentinelRedisInstances.
200                            Key is the instance name, value is the
201                            sentinelRedisInstance structure pointer. */
202     int tilt;           /* Are we in TILT mode? */
203     int running_scripts;    /* Number of scripts in execution right now. */
204     mstime_t tilt_start_time;   /* When TITL started. */
205     mstime_t previous_time;     /* Last time we ran the time handler. */
206     list *scripts_queue;    /* Queue of user scripts to execute. */
207     char *announce_ip;      /* IP addr that is gossiped to other sentinels if
208                                not NULL. */
209     int announce_port;      /* Port that is gossiped to other sentinels if
210                                non zero. */
211 } sentinel;
212 
213 /* A script execution job. */
214 typedef struct sentinelScriptJob {
215     int flags;              /* Script job flags: SENTINEL_SCRIPT_* */
216     int retry_num;          /* Number of times we tried to execute it. */
217     char **argv;            /* Arguments to call the script. */
218     mstime_t start_time;    /* Script execution time if the script is running,
219                                otherwise 0 if we are allowed to retry the
220                                execution at any time. If the script is not
221                                running and it's not 0, it means: do not run
222                                before the specified time. */
223     pid_t pid;              /* Script execution pid. */
224 } sentinelScriptJob;
225 
226 /* ======================= hiredis ae.c adapters =============================
227  * Note: this implementation is taken from hiredis/adapters/ae.h, however
228  * we have our modified copy for Sentinel in order to use our allocator
229  * and to have full control over how the adapter works. */
230 
231 typedef struct redisAeEvents {
232     redisAsyncContext *context;
233     aeEventLoop *loop;
234     int fd;
235     int reading, writing;
236 } redisAeEvents;
237 
238 static void redisAeReadEvent(aeEventLoop *el, int fd, void *privdata, int mask) {
239     ((void)el); ((void)fd); ((void)mask);
240 
241     redisAeEvents *e = (redisAeEvents*)privdata;
242     redisAsyncHandleRead(e->context);
243 }
244 
245 static void redisAeWriteEvent(aeEventLoop *el, int fd, void *privdata, int mask) {
246     ((void)el); ((void)fd); ((void)mask);
247 
248     redisAeEvents *e = (redisAeEvents*)privdata;
249     redisAsyncHandleWrite(e->context);
250 }
251 
252 static void redisAeAddRead(void *privdata) {
253     redisAeEvents *e = (redisAeEvents*)privdata;
254     aeEventLoop *loop = e->loop;
255     if (!e->reading) {
256         e->reading = 1;
257         aeCreateFileEvent(loop,e->fd,AE_READABLE,redisAeReadEvent,e);
258     }
259 }
260 
261 static void redisAeDelRead(void *privdata) {
262     redisAeEvents *e = (redisAeEvents*)privdata;
263     aeEventLoop *loop = e->loop;
264     if (e->reading) {
265         e->reading = 0;
266         aeDeleteFileEvent(loop,e->fd,AE_READABLE);
267     }
268 }
269 
270 static void redisAeAddWrite(void *privdata) {
271     redisAeEvents *e = (redisAeEvents*)privdata;
272     aeEventLoop *loop = e->loop;
273     if (!e->writing) {
274         e->writing = 1;
275         aeCreateFileEvent(loop,e->fd,AE_WRITABLE,redisAeWriteEvent,e);
276     }
277 }
278 
279 static void redisAeDelWrite(void *privdata) {
280     redisAeEvents *e = (redisAeEvents*)privdata;
281     aeEventLoop *loop = e->loop;
282     if (e->writing) {
283         e->writing = 0;
284         aeDeleteFileEvent(loop,e->fd,AE_WRITABLE);
285     }
286 }
287 
288 static void redisAeCleanup(void *privdata) {
289     redisAeEvents *e = (redisAeEvents*)privdata;
290     redisAeDelRead(privdata);
291     redisAeDelWrite(privdata);
292     zfree(e);
293 }
294 
295 static int redisAeAttach(aeEventLoop *loop, redisAsyncContext *ac) {
296     redisContext *c = &(ac->c);
297     redisAeEvents *e;
298 
299     /* Nothing should be attached when something is already attached */
300     if (ac->ev.data != NULL)
301         return REDIS_ERR;
302 
303     /* Create container for context and r/w events */
304     e = (redisAeEvents*)zmalloc(sizeof(*e));
305     e->context = ac;
306     e->loop = loop;
307     e->fd = c->fd;
308     e->reading = e->writing = 0;
309 
310     /* Register functions to start/stop listening for events */
311     ac->ev.addRead = redisAeAddRead;
312     ac->ev.delRead = redisAeDelRead;
313     ac->ev.addWrite = redisAeAddWrite;
314     ac->ev.delWrite = redisAeDelWrite;
315     ac->ev.cleanup = redisAeCleanup;
316     ac->ev.data = e;
317 
318     return REDIS_OK;
319 }
320 
321 /* ============================= Prototypes ================================= */
322 
323 void sentinelLinkEstablishedCallback(const redisAsyncContext *c, int status);
324 void sentinelDisconnectCallback(const redisAsyncContext *c, int status);
325 void sentinelReceiveHelloMessages(redisAsyncContext *c, void *reply, void *privdata);
326 sentinelRedisInstance *sentinelGetMasterByName(char *name);
327 char *sentinelGetSubjectiveLeader(sentinelRedisInstance *master);
328 char *sentinelGetObjectiveLeader(sentinelRedisInstance *master);
329 int yesnotoi(char *s);
330 void sentinelDisconnectInstanceFromContext(const redisAsyncContext *c);
331 void sentinelKillLink(sentinelRedisInstance *ri, redisAsyncContext *c);
332 const char *sentinelRedisInstanceTypeStr(sentinelRedisInstance *ri);
333 void sentinelAbortFailover(sentinelRedisInstance *ri);
334 void sentinelEvent(int level, char *type, sentinelRedisInstance *ri, const char *fmt, ...);
335 sentinelRedisInstance *sentinelSelectSlave(sentinelRedisInstance *master);
336 void sentinelScheduleScriptExecution(char *path, ...);
337 void sentinelStartFailover(sentinelRedisInstance *master);
338 void sentinelDiscardReplyCallback(redisAsyncContext *c, void *reply, void *privdata);
339 int sentinelSendSlaveOf(sentinelRedisInstance *ri, char *host, int port);
340 char *sentinelVoteLeader(sentinelRedisInstance *master, uint64_t req_epoch, char *req_runid, uint64_t *leader_epoch);
341 void sentinelFlushConfig(void);
342 void sentinelGenerateInitialMonitorEvents(void);
343 int sentinelSendPing(sentinelRedisInstance *ri);
344 int sentinelForceHelloUpdateForMaster(sentinelRedisInstance *master);
345 
346 /* ========================= Dictionary types =============================== */
347 
348 unsigned int dictSdsHash(const void *key);
349 int dictSdsKeyCompare(void *privdata, const void *key1, const void *key2);
350 void releaseSentinelRedisInstance(sentinelRedisInstance *ri);
351 
352 void dictInstancesValDestructor (void *privdata, void *obj) {
353     REDIS_NOTUSED(privdata);
354     releaseSentinelRedisInstance(obj);
355 }
356 
357 /* Instance name (sds) -> instance (sentinelRedisInstance pointer)
358  *
359  * also used for: sentinelRedisInstance->sentinels dictionary that maps
360  * sentinels ip:port to last seen time in Pub/Sub hello message. */
361 dictType instancesDictType = {
362     dictSdsHash,               /* hash function */
363     NULL,                      /* key dup */
364     NULL,                      /* val dup */
365     dictSdsKeyCompare,         /* key compare */
366     NULL,                      /* key destructor */
367     dictInstancesValDestructor /* val destructor */
368 };
369 
370 /* Instance runid (sds) -> votes (long casted to void*)
371  *
372  * This is useful into sentinelGetObjectiveLeader() function in order to
373  * count the votes and understand who is the leader. */
374 dictType leaderVotesDictType = {
375     dictSdsHash,               /* hash function */
376     NULL,                      /* key dup */
377     NULL,                      /* val dup */
378     dictSdsKeyCompare,         /* key compare */
379     NULL,                      /* key destructor */
380     NULL                       /* val destructor */
381 };
382 
383 /* =========================== Initialization =============================== */
384 
385 void sentinelCommand(redisClient *c);
386 void sentinelInfoCommand(redisClient *c);
387 void sentinelSetCommand(redisClient *c);
388 void sentinelPublishCommand(redisClient *c);
389 void sentinelRoleCommand(redisClient *c);
390 
391 struct redisCommand sentinelcmds[] = {
392     {"ping",pingCommand,1,"",0,NULL,0,0,0,0,0},
393     {"sentinel",sentinelCommand,-2,"",0,NULL,0,0,0,0,0},
394     {"subscribe",subscribeCommand,-2,"",0,NULL,0,0,0,0,0},
395     {"unsubscribe",unsubscribeCommand,-1,"",0,NULL,0,0,0,0,0},
396     {"psubscribe",psubscribeCommand,-2,"",0,NULL,0,0,0,0,0},
397     {"punsubscribe",punsubscribeCommand,-1,"",0,NULL,0,0,0,0,0},
398     {"publish",sentinelPublishCommand,3,"",0,NULL,0,0,0,0,0},
399     {"info",sentinelInfoCommand,-1,"",0,NULL,0,0,0,0,0},
400     {"role",sentinelRoleCommand,1,"l",0,NULL,0,0,0,0,0},
401     {"shutdown",shutdownCommand,-1,"",0,NULL,0,0,0,0,0}
402 };
403 
404 /* This function overwrites a few normal Redis config default with Sentinel
405  * specific defaults. */
406 void initSentinelConfig(void) {
407     server.port = REDIS_SENTINEL_PORT;
408 }
409 
410 /* Perform the Sentinel mode initialization. */
411 void initSentinel(void) {
412     unsigned int j;
413 
414     /* Remove usual Redis commands from the command table, then just add
415      * the SENTINEL command. */
416     dictEmpty(server.commands,NULL);
417     for (j = 0; j < sizeof(sentinelcmds)/sizeof(sentinelcmds[0]); j++) {
418         int retval;
419         struct redisCommand *cmd = sentinelcmds+j;
420 
421         retval = dictAdd(server.commands, sdsnew(cmd->name), cmd);
422         redisAssert(retval == DICT_OK);
423     }
424 
425     /* Initialize various data structures. */
426     sentinel.current_epoch = 0;
427     sentinel.masters = dictCreate(&instancesDictType,NULL);
428     sentinel.tilt = 0;
429     sentinel.tilt_start_time = 0;
430     sentinel.previous_time = mstime();
431     sentinel.running_scripts = 0;
432     sentinel.scripts_queue = listCreate();
433     sentinel.announce_ip = NULL;
434     sentinel.announce_port = 0;
435 }
436 
437 /* This function gets called when the server is in Sentinel mode, started,
438  * loaded the configuration, and is ready for normal operations. */
439 void sentinelIsRunning(void) {
440     redisLog(REDIS_WARNING,"Sentinel runid is %s", server.runid);
441 
442     if (server.configfile == NULL) {
443         redisLog(REDIS_WARNING,
444             "Sentinel started without a config file. Exiting...");
445         exit(1);
446     } else if (access(server.configfile,W_OK) == -1) {
447         redisLog(REDIS_WARNING,
448             "Sentinel config file %s is not writable: %s. Exiting...",
449             server.configfile,strerror(errno));
450         exit(1);
451     }
452 
453     /* We want to generate a +monitor event for every configured master
454      * at startup. */
455     sentinelGenerateInitialMonitorEvents();
456 }
457 
458 /* ============================== sentinelAddr ============================== */
459 
460 /* Create a sentinelAddr object and return it on success.
461  * On error NULL is returned and errno is set to:
462  *  ENOENT: Can't resolve the hostname.
463  *  EINVAL: Invalid port number.
464  */
465 sentinelAddr *createSentinelAddr(char *hostname, int port) {
466     char ip[REDIS_IP_STR_LEN];
467     sentinelAddr *sa;
468 
469     if (port <= 0 || port > 65535) {
470         errno = EINVAL;
471         return NULL;
472     }
473     if (anetResolve(NULL,hostname,ip,sizeof(ip)) == ANET_ERR) {
474         errno = ENOENT;
475         return NULL;
476     }
477     sa = zmalloc(sizeof(*sa));
478     sa->ip = sdsnew(ip);
479     sa->port = port;
480     return sa;
481 }
482 
483 /* Return a duplicate of the source address. */
484 sentinelAddr *dupSentinelAddr(sentinelAddr *src) {
485     sentinelAddr *sa;
486 
487     sa = zmalloc(sizeof(*sa));
488     sa->ip = sdsnew(src->ip);
489     sa->port = src->port;
490     return sa;
491 }
492 
493 /* Free a Sentinel address. Can't fail. */
494 void releaseSentinelAddr(sentinelAddr *sa) {
495     sdsfree(sa->ip);
496     zfree(sa);
497 }
498 
499 /* Return non-zero if two addresses are equal. */
500 int sentinelAddrIsEqual(sentinelAddr *a, sentinelAddr *b) {
501     return a->port == b->port && !strcasecmp(a->ip,b->ip);
502 }
503 
504 /* =========================== Events notification ========================== */
505 
506 /* Send an event to log, pub/sub, user notification script.
507  *
508  * 'level' is the log level for logging. Only REDIS_WARNING events will trigger
509  * the execution of the user notification script.
510  *
511  * 'type' is the message type, also used as a pub/sub channel name.
512  *
513  * 'ri', is the redis instance target of this event if applicable, and is
514  * used to obtain the path of the notification script to execute.
515  *
516  * The remaining arguments are printf-alike.
517  * If the format specifier starts with the two characters "%@" then ri is
518  * not NULL, and the message is prefixed with an instance identifier in the
519  * following format:
520  *
521  *  <instance type> <instance name> <ip> <port>
522  *
523  *  If the instance type is not master, than the additional string is
524  *  added to specify the originating master:
525  *
526  *  @ <master name> <master ip> <master port>
527  *
528  *  Any other specifier after "%@" is processed by printf itself.
529  */
530 void sentinelEvent(int level, char *type, sentinelRedisInstance *ri,
531                    const char *fmt, ...) {
532     va_list ap;
533     char msg[REDIS_MAX_LOGMSG_LEN];
534     robj *channel, *payload;
535 
536     /* Handle %@ */
537     if (fmt[0] == '%' && fmt[1] == '@') {
538         sentinelRedisInstance *master = (ri->flags & SRI_MASTER) ?
539                                          NULL : ri->master;
540 
541         if (master) {
542             snprintf(msg, sizeof(msg), "%s %s %s %d @ %s %s %d",
543                 sentinelRedisInstanceTypeStr(ri),
544                 ri->name, ri->addr->ip, ri->addr->port,
545                 master->name, master->addr->ip, master->addr->port);
546         } else {
547             snprintf(msg, sizeof(msg), "%s %s %s %d",
548                 sentinelRedisInstanceTypeStr(ri),
549                 ri->name, ri->addr->ip, ri->addr->port);
550         }
551         fmt += 2;
552     } else {
553         msg[0] = '\0';
554     }
555 
556     /* Use vsprintf for the rest of the formatting if any. */
557     if (fmt[0] != '\0') {
558         va_start(ap, fmt);
559         vsnprintf(msg+strlen(msg), sizeof(msg)-strlen(msg), fmt, ap);
560         va_end(ap);
561     }
562 
563     /* Log the message if the log level allows it to be logged. */
564     if (level >= server.verbosity)
565         redisLog(level,"%s %s",type,msg);
566 
567     /* Publish the message via Pub/Sub if it's not a debugging one. */
568     if (level != REDIS_DEBUG) {
569         channel = createStringObject(type,strlen(type));
570         payload = createStringObject(msg,strlen(msg));
571         pubsubPublishMessage(channel,payload);
572         decrRefCount(channel);
573         decrRefCount(payload);
574     }
575 
576     /* Call the notification script if applicable. */
577     if (level == REDIS_WARNING && ri != NULL) {
578         sentinelRedisInstance *master = (ri->flags & SRI_MASTER) ?
579                                          ri : ri->master;
580         if (master && master->notification_script) {
581             sentinelScheduleScriptExecution(master->notification_script,
582                 type,msg,NULL);
583         }
584     }
585 }
586 
587 /* This function is called only at startup and is used to generate a
588  * +monitor event for every configured master. The same events are also
589  * generated when a master to monitor is added at runtime via the
590  * SENTINEL MONITOR command. */
591 void sentinelGenerateInitialMonitorEvents(void) {
592     dictIterator *di;
593     dictEntry *de;
594 
595     di = dictGetIterator(sentinel.masters);
596     while((de = dictNext(di)) != NULL) {
597         sentinelRedisInstance *ri = dictGetVal(de);
598         sentinelEvent(REDIS_WARNING,"+monitor",ri,"%@ quorum %d",ri->quorum);
599     }
600     dictReleaseIterator(di);
601 }
602 
603 /* ============================ script execution ============================ */
604 
605 /* Release a script job structure and all the associated data. */
606 void sentinelReleaseScriptJob(sentinelScriptJob *sj) {
607     int j = 0;
608 
609     while(sj->argv[j]) sdsfree(sj->argv[j++]);
610     zfree(sj->argv);
611     zfree(sj);
612 }
613 
614 #define SENTINEL_SCRIPT_MAX_ARGS 16
615 void sentinelScheduleScriptExecution(char *path, ...) {
616     va_list ap;
617     char *argv[SENTINEL_SCRIPT_MAX_ARGS+1];
618     int argc = 1;
619     sentinelScriptJob *sj;
620 
621     va_start(ap, path);
622     while(argc < SENTINEL_SCRIPT_MAX_ARGS) {
623         argv[argc] = va_arg(ap,char*);
624         if (!argv[argc]) break;
625         argv[argc] = sdsnew(argv[argc]); /* Copy the string. */
626         argc++;
627     }
628     va_end(ap);
629     argv[0] = sdsnew(path);
630 
631     sj = zmalloc(sizeof(*sj));
632     sj->flags = SENTINEL_SCRIPT_NONE;
633     sj->retry_num = 0;
634     sj->argv = zmalloc(sizeof(char*)*(argc+1));
635     sj->start_time = 0;
636     sj->pid = 0;
637     memcpy(sj->argv,argv,sizeof(char*)*(argc+1));
638 
639     listAddNodeTail(sentinel.scripts_queue,sj);
640 
641     /* Remove the oldest non running script if we already hit the limit. */
642     if (listLength(sentinel.scripts_queue) > SENTINEL_SCRIPT_MAX_QUEUE) {
643         listNode *ln;
644         listIter li;
645 
646         listRewind(sentinel.scripts_queue,&li);
647         while ((ln = listNext(&li)) != NULL) {
648             sj = ln->value;
649 
650             if (sj->flags & SENTINEL_SCRIPT_RUNNING) continue;
651             /* The first node is the oldest as we add on tail. */
652             listDelNode(sentinel.scripts_queue,ln);
653             sentinelReleaseScriptJob(sj);
654             break;
655         }
656         redisAssert(listLength(sentinel.scripts_queue) <=
657                     SENTINEL_SCRIPT_MAX_QUEUE);
658     }
659 }
660 
661 /* Lookup a script in the scripts queue via pid, and returns the list node
662  * (so that we can easily remove it from the queue if needed). */
663 listNode *sentinelGetScriptListNodeByPid(pid_t pid) {
664     listNode *ln;
665     listIter li;
666 
667     listRewind(sentinel.scripts_queue,&li);
668     while ((ln = listNext(&li)) != NULL) {
669         sentinelScriptJob *sj = ln->value;
670 
671         if ((sj->flags & SENTINEL_SCRIPT_RUNNING) && sj->pid == pid)
672             return ln;
673     }
674     return NULL;
675 }
676 
677 /* Run pending scripts if we are not already at max number of running
678  * scripts. */
679 void sentinelRunPendingScripts(void) {
680     listNode *ln;
681     listIter li;
682     mstime_t now = mstime();
683 
684     /* Find jobs that are not running and run them, from the top to the
685      * tail of the queue, so we run older jobs first. */
686     listRewind(sentinel.scripts_queue,&li);
687     while (sentinel.running_scripts < SENTINEL_SCRIPT_MAX_RUNNING &&
688            (ln = listNext(&li)) != NULL)
689     {
690         sentinelScriptJob *sj = ln->value;
691         pid_t pid;
692 
693         /* Skip if already running. */
694         if (sj->flags & SENTINEL_SCRIPT_RUNNING) continue;
695 
696         /* Skip if it's a retry, but not enough time has elapsed. */
697         if (sj->start_time && sj->start_time > now) continue;
698 
699         sj->flags |= SENTINEL_SCRIPT_RUNNING;
700         sj->start_time = mstime();
701         sj->retry_num++;
702         pid = fork();
703 
704         if (pid == -1) {
705             /* Parent (fork error).
706              * We report fork errors as signal 99, in order to unify the
707              * reporting with other kind of errors. */
708             sentinelEvent(REDIS_WARNING,"-script-error",NULL,
709                           "%s %d %d", sj->argv[0], 99, 0);
710             sj->flags &= ~SENTINEL_SCRIPT_RUNNING;
711             sj->pid = 0;
712         } else if (pid == 0) {
713             /* Child */
714             execve(sj->argv[0],sj->argv,environ);
715             /* If we are here an error occurred. */
716             _exit(2); /* Don't retry execution. */
717         } else {
718             sentinel.running_scripts++;
719             sj->pid = pid;
720             sentinelEvent(REDIS_DEBUG,"+script-child",NULL,"%ld",(long)pid);
721         }
722     }
723 }
724 
725 /* How much to delay the execution of a script that we need to retry after
726  * an error?
727  *
728  * We double the retry delay for every further retry we do. So for instance
729  * if RETRY_DELAY is set to 30 seconds and the max number of retries is 10
730  * starting from the second attempt to execute the script the delays are:
731  * 30 sec, 60 sec, 2 min, 4 min, 8 min, 16 min, 32 min, 64 min, 128 min. */
732 mstime_t sentinelScriptRetryDelay(int retry_num) {
733     mstime_t delay = SENTINEL_SCRIPT_RETRY_DELAY;
734 
735     while (retry_num-- > 1) delay *= 2;
736     return delay;
737 }
738 
739 /* Check for scripts that terminated, and remove them from the queue if the
740  * script terminated successfully. If instead the script was terminated by
741  * a signal, or returned exit code "1", it is scheduled to run again if
742  * the max number of retries did not already elapsed. */
743 void sentinelCollectTerminatedScripts(void) {
744     int statloc;
745     pid_t pid;
746 
747     while ((pid = wait3(&statloc,WNOHANG,NULL)) > 0) {
748         int exitcode = WEXITSTATUS(statloc);
749         int bysignal = 0;
750         listNode *ln;
751         sentinelScriptJob *sj;
752 
753         if (WIFSIGNALED(statloc)) bysignal = WTERMSIG(statloc);
754         sentinelEvent(REDIS_DEBUG,"-script-child",NULL,"%ld %d %d",
755             (long)pid, exitcode, bysignal);
756 
757         ln = sentinelGetScriptListNodeByPid(pid);
758         if (ln == NULL) {
759             redisLog(REDIS_WARNING,"wait3() returned a pid (%ld) we can't find in our scripts execution queue!", (long)pid);
760             continue;
761         }
762         sj = ln->value;
763 
764         /* If the script was terminated by a signal or returns an
765          * exit code of "1" (that means: please retry), we reschedule it
766          * if the max number of retries is not already reached. */
767         if ((bysignal || exitcode == 1) &&
768             sj->retry_num != SENTINEL_SCRIPT_MAX_RETRY)
769         {
770             sj->flags &= ~SENTINEL_SCRIPT_RUNNING;
771             sj->pid = 0;
772             sj->start_time = mstime() +
773                              sentinelScriptRetryDelay(sj->retry_num);
774         } else {
775             /* Otherwise let's remove the script, but log the event if the
776              * execution did not terminated in the best of the ways. */
777             if (bysignal || exitcode != 0) {
778                 sentinelEvent(REDIS_WARNING,"-script-error",NULL,
779                               "%s %d %d", sj->argv[0], bysignal, exitcode);
780             }
781             listDelNode(sentinel.scripts_queue,ln);
782             sentinelReleaseScriptJob(sj);
783             sentinel.running_scripts--;
784         }
785     }
786 }
787 
788 /* Kill scripts in timeout, they'll be collected by the
789  * sentinelCollectTerminatedScripts() function. */
790 void sentinelKillTimedoutScripts(void) {
791     listNode *ln;
792     listIter li;
793     mstime_t now = mstime();
794 
795     listRewind(sentinel.scripts_queue,&li);
796     while ((ln = listNext(&li)) != NULL) {
797         sentinelScriptJob *sj = ln->value;
798 
799         if (sj->flags & SENTINEL_SCRIPT_RUNNING &&
800             (now - sj->start_time) > SENTINEL_SCRIPT_MAX_RUNTIME)
801         {
802             sentinelEvent(REDIS_WARNING,"-script-timeout",NULL,"%s %ld",
803                 sj->argv[0], (long)sj->pid);
804             kill(sj->pid,SIGKILL);
805         }
806     }
807 }
808 
809 /* Implements SENTINEL PENDING-SCRIPTS command. */
810 void sentinelPendingScriptsCommand(redisClient *c) {
811     listNode *ln;
812     listIter li;
813 
814     addReplyMultiBulkLen(c,listLength(sentinel.scripts_queue));
815     listRewind(sentinel.scripts_queue,&li);
816     while ((ln = listNext(&li)) != NULL) {
817         sentinelScriptJob *sj = ln->value;
818         int j = 0;
819 
820         addReplyMultiBulkLen(c,10);
821 
822         addReplyBulkCString(c,"argv");
823         while (sj->argv[j]) j++;
824         addReplyMultiBulkLen(c,j);
825         j = 0;
826         while (sj->argv[j]) addReplyBulkCString(c,sj->argv[j++]);
827 
828         addReplyBulkCString(c,"flags");
829         addReplyBulkCString(c,
830             (sj->flags & SENTINEL_SCRIPT_RUNNING) ? "running" : "scheduled");
831 
832         addReplyBulkCString(c,"pid");
833         addReplyBulkLongLong(c,sj->pid);
834 
835         if (sj->flags & SENTINEL_SCRIPT_RUNNING) {
836             addReplyBulkCString(c,"run-time");
837             addReplyBulkLongLong(c,mstime() - sj->start_time);
838         } else {
839             mstime_t delay = sj->start_time ? (sj->start_time-mstime()) : 0;
840             if (delay < 0) delay = 0;
841             addReplyBulkCString(c,"run-delay");
842             addReplyBulkLongLong(c,delay);
843         }
844 
845         addReplyBulkCString(c,"retry-num");
846         addReplyBulkLongLong(c,sj->retry_num);
847     }
848 }
849 
850 /* This function calls, if any, the client reconfiguration script with the
851  * following parameters:
852  *
853  * <master-name> <role> <state> <from-ip> <from-port> <to-ip> <to-port>
854  *
855  * It is called every time a failover is performed.
856  *
857  * <state> is currently always "failover".
858  * <role> is either "leader" or "observer".
859  *
860  * from/to fields are respectively master -> promoted slave addresses for
861  * "start" and "end". */
862 void sentinelCallClientReconfScript(sentinelRedisInstance *master, int role, char *state, sentinelAddr *from, sentinelAddr *to) {
863     char fromport[32], toport[32];
864 
865     if (master->client_reconfig_script == NULL) return;
866     ll2string(fromport,sizeof(fromport),from->port);
867     ll2string(toport,sizeof(toport),to->port);
868     sentinelScheduleScriptExecution(master->client_reconfig_script,
869         master->name,
870         (role == SENTINEL_LEADER) ? "leader" : "observer",
871         state, from->ip, fromport, to->ip, toport, NULL);
872 }
873 
874 /* ========================== sentinelRedisInstance ========================= */
875 
876 /* Create a redis instance, the following fields must be populated by the
877  * caller if needed:
878  * runid: set to NULL but will be populated once INFO output is received.
879  * info_refresh: is set to 0 to mean that we never received INFO so far.
880  *
881  * If SRI_MASTER is set into initial flags the instance is added to
882  * sentinel.masters table.
883  *
884  * if SRI_SLAVE or SRI_SENTINEL is set then 'master' must be not NULL and the
885  * instance is added into master->slaves or master->sentinels table.
886  *
887  * If the instance is a slave or sentinel, the name parameter is ignored and
888  * is created automatically as hostname:port.
889  *
890  * The function fails if hostname can't be resolved or port is out of range.
891  * When this happens NULL is returned and errno is set accordingly to the
892  * createSentinelAddr() function.
893  *
894  * The function may also fail and return NULL with errno set to EBUSY if
895  * a master or slave with the same name already exists. */
896 sentinelRedisInstance *createSentinelRedisInstance(char *name, int flags, char *hostname, int port, int quorum, sentinelRedisInstance *master) {
897     sentinelRedisInstance *ri;
898     sentinelAddr *addr;
899     dict *table = NULL;
900     char slavename[REDIS_PEER_ID_LEN], *sdsname;
901 
902     redisAssert(flags & (SRI_MASTER|SRI_SLAVE|SRI_SENTINEL));
903     redisAssert((flags & SRI_MASTER) || master != NULL);
904 
905     /* Check address validity. */
906     addr = createSentinelAddr(hostname,port);
907     if (addr == NULL) return NULL;
908 
909     /* For slaves and sentinel we use ip:port as name. */
910     if (flags & (SRI_SLAVE|SRI_SENTINEL)) {
911         anetFormatAddr(slavename, sizeof(slavename), hostname, port);
912         name = slavename;
913     }
914 
915     /* Make sure the entry is not duplicated. This may happen when the same
916      * name for a master is used multiple times inside the configuration or
917      * if we try to add multiple times a slave or sentinel with same ip/port
918      * to a master. */
919     if (flags & SRI_MASTER) table = sentinel.masters;
920     else if (flags & SRI_SLAVE) table = master->slaves;
921     else if (flags & SRI_SENTINEL) table = master->sentinels;
922     sdsname = sdsnew(name);
923     if (dictFind(table,sdsname)) {
924         sdsfree(sdsname);
925         errno = EBUSY;
926         return NULL;
927     }
928 
929     /* Create the instance object. */
930     ri = zmalloc(sizeof(*ri));
931     /* Note that all the instances are started in the disconnected state,
932      * the event loop will take care of connecting them. */
933     ri->flags = flags | SRI_DISCONNECTED;
934     ri->name = sdsname;
935     ri->runid = NULL;
936     ri->config_epoch = 0;
937     ri->addr = addr;
938     ri->cc = NULL;
939     ri->pc = NULL;
940     ri->pending_commands = 0;
941     ri->cc_conn_time = 0;
942     ri->pc_conn_time = 0;
943     ri->pc_last_activity = 0;
944     /* We set the last_ping_time to "now" even if we actually don't have yet
945      * a connection with the node, nor we sent a ping.
946      * This is useful to detect a timeout in case we'll not be able to connect
947      * with the node at all. */
948     ri->last_ping_time = mstime();
949     ri->last_avail_time = mstime();
950     ri->last_pong_time = mstime();
951     ri->last_pub_time = mstime();
952     ri->last_hello_time = mstime();
953     ri->last_master_down_reply_time = mstime();
954     ri->s_down_since_time = 0;
955     ri->o_down_since_time = 0;
956     ri->down_after_period = master ? master->down_after_period :
957                             SENTINEL_DEFAULT_DOWN_AFTER;
958     ri->master_link_down_time = 0;
959     ri->auth_pass = NULL;
960     ri->slave_priority = SENTINEL_DEFAULT_SLAVE_PRIORITY;
961     ri->slave_reconf_sent_time = 0;
962     ri->slave_master_host = NULL;
963     ri->slave_master_port = 0;
964     ri->slave_master_link_status = SENTINEL_MASTER_LINK_STATUS_DOWN;
965     ri->slave_repl_offset = 0;
966     ri->sentinels = dictCreate(&instancesDictType,NULL);
967     ri->quorum = quorum;
968     ri->parallel_syncs = SENTINEL_DEFAULT_PARALLEL_SYNCS;
969     ri->master = master;
970     ri->slaves = dictCreate(&instancesDictType,NULL);
971     ri->info_refresh = 0;
972 
973     /* Failover state. */
974     ri->leader = NULL;
975     ri->leader_epoch = 0;
976     ri->failover_epoch = 0;
977     ri->failover_state = SENTINEL_FAILOVER_STATE_NONE;
978     ri->failover_state_change_time = 0;
979     ri->failover_start_time = 0;
980     ri->failover_timeout = SENTINEL_DEFAULT_FAILOVER_TIMEOUT;
981     ri->failover_delay_logged = 0;
982     ri->promoted_slave = NULL;
983     ri->notification_script = NULL;
984     ri->client_reconfig_script = NULL;
985     ri->info = NULL;
986 
987     /* Role */
988     ri->role_reported = ri->flags & (SRI_MASTER|SRI_SLAVE);
989     ri->role_reported_time = mstime();
990     ri->slave_conf_change_time = mstime();
991 
992     /* Add into the right table. */
993     dictAdd(table, ri->name, ri);
994     return ri;
995 }
996 
997 /* Release this instance and all its slaves, sentinels, hiredis connections.
998  * This function does not take care of unlinking the instance from the main
999  * masters table (if it is a master) or from its master sentinels/slaves table
1000  * if it is a slave or sentinel. */
1001 void releaseSentinelRedisInstance(sentinelRedisInstance *ri) {
1002     /* Release all its slaves or sentinels if any. */
1003     dictRelease(ri->sentinels);
1004     dictRelease(ri->slaves);
1005 
1006     /* Release hiredis connections. */
1007     if (ri->cc) sentinelKillLink(ri,ri->cc);
1008     if (ri->pc) sentinelKillLink(ri,ri->pc);
1009 
1010     /* Free other resources. */
1011     sdsfree(ri->name);
1012     sdsfree(ri->runid);
1013     sdsfree(ri->notification_script);
1014     sdsfree(ri->client_reconfig_script);
1015     sdsfree(ri->slave_master_host);
1016     sdsfree(ri->leader);
1017     sdsfree(ri->auth_pass);
1018     sdsfree(ri->info);
1019     releaseSentinelAddr(ri->addr);
1020 
1021     /* Clear state into the master if needed. */
1022     if ((ri->flags & SRI_SLAVE) && (ri->flags & SRI_PROMOTED) && ri->master)
1023         ri->master->promoted_slave = NULL;
1024 
1025     zfree(ri);
1026 }
1027 
1028 /* Lookup a slave in a master Redis instance, by ip and port. */
1029 sentinelRedisInstance *sentinelRedisInstanceLookupSlave(
1030                 sentinelRedisInstance *ri, char *ip, int port)
1031 {
1032     sds key;
1033     sentinelRedisInstance *slave;
1034     char buf[REDIS_PEER_ID_LEN];
1035 
1036     redisAssert(ri->flags & SRI_MASTER);
1037     anetFormatAddr(buf,sizeof(buf),ip,port);
1038     key = sdsnew(buf);
1039     slave = dictFetchValue(ri->slaves,key);
1040     sdsfree(key);
1041     return slave;
1042 }
1043 
1044 /* Return the name of the type of the instance as a string. */
1045 const char *sentinelRedisInstanceTypeStr(sentinelRedisInstance *ri) {
1046     if (ri->flags & SRI_MASTER) return "master";
1047     else if (ri->flags & SRI_SLAVE) return "slave";
1048     else if (ri->flags & SRI_SENTINEL) return "sentinel";
1049     else return "unknown";
1050 }
1051 
1052 /* This function removes all the instances found in the dictionary of
1053  * sentinels in the specified 'master', having either:
1054  *
1055  * 1) The same ip/port as specified.
1056  * 2) The same runid.
1057  *
1058  * "1" and "2" don't need to verify at the same time, just one is enough.
1059  * If "runid" is NULL it is not checked.
1060  * Similarly if "ip" is NULL it is not checked.
1061  *
1062  * This function is useful because every time we add a new Sentinel into
1063  * a master's Sentinels dictionary, we want to be very sure about not
1064  * having duplicated instances for any reason. This is important because
1065  * other sentinels are needed to reach ODOWN quorum, and later to get
1066  * voted for a given configuration epoch in order to perform the failover.
1067  *
1068  * The function returns the number of Sentinels removed. */
1069 int removeMatchingSentinelsFromMaster(sentinelRedisInstance *master, char *ip, int port, char *runid) {
1070     dictIterator *di;
1071     dictEntry *de;
1072     int removed = 0;
1073 
1074     di = dictGetSafeIterator(master->sentinels);
1075     while((de = dictNext(di)) != NULL) {
1076         sentinelRedisInstance *ri = dictGetVal(de);
1077 
1078         if ((ri->runid && runid && strcmp(ri->runid,runid) == 0) ||
1079             (ip && strcmp(ri->addr->ip,ip) == 0 && port == ri->addr->port))
1080         {
1081             dictDelete(master->sentinels,ri->name);
1082             removed++;
1083         }
1084     }
1085     dictReleaseIterator(di);
1086     return removed;
1087 }
1088 
1089 /* Search an instance with the same runid, ip and port into a dictionary
1090  * of instances. Return NULL if not found, otherwise return the instance
1091  * pointer.
1092  *
1093  * runid or ip can be NULL. In such a case the search is performed only
1094  * by the non-NULL field. */
1095 sentinelRedisInstance *getSentinelRedisInstanceByAddrAndRunID(dict *instances, char *ip, int port, char *runid) {
1096     dictIterator *di;
1097     dictEntry *de;
1098     sentinelRedisInstance *instance = NULL;
1099 
1100     redisAssert(ip || runid);   /* User must pass at least one search param. */
1101     di = dictGetIterator(instances);
1102     while((de = dictNext(di)) != NULL) {
1103         sentinelRedisInstance *ri = dictGetVal(de);
1104 
1105         if (runid && !ri->runid) continue;
1106         if ((runid == NULL || strcmp(ri->runid, runid) == 0) &&
1107             (ip == NULL || (strcmp(ri->addr->ip, ip) == 0 &&
1108                             ri->addr->port == port)))
1109         {
1110             instance = ri;
1111             break;
1112         }
1113     }
1114     dictReleaseIterator(di);
1115     return instance;
1116 }
1117 
1118 /* Master lookup by name */
1119 sentinelRedisInstance *sentinelGetMasterByName(char *name) {
1120     sentinelRedisInstance *ri;
1121     sds sdsname = sdsnew(name);
1122 
1123     ri = dictFetchValue(sentinel.masters,sdsname);
1124     sdsfree(sdsname);
1125     return ri;
1126 }
1127 
1128 /* Add the specified flags to all the instances in the specified dictionary. */
1129 void sentinelAddFlagsToDictOfRedisInstances(dict *instances, int flags) {
1130     dictIterator *di;
1131     dictEntry *de;
1132 
1133     di = dictGetIterator(instances);
1134     while((de = dictNext(di)) != NULL) {
1135         sentinelRedisInstance *ri = dictGetVal(de);
1136         ri->flags |= flags;
1137     }
1138     dictReleaseIterator(di);
1139 }
1140 
1141 /* Remove the specified flags to all the instances in the specified
1142  * dictionary. */
1143 void sentinelDelFlagsToDictOfRedisInstances(dict *instances, int flags) {
1144     dictIterator *di;
1145     dictEntry *de;
1146 
1147     di = dictGetIterator(instances);
1148     while((de = dictNext(di)) != NULL) {
1149         sentinelRedisInstance *ri = dictGetVal(de);
1150         ri->flags &= ~flags;
1151     }
1152     dictReleaseIterator(di);
1153 }
1154 
1155 /* Reset the state of a monitored master:
1156  * 1) Remove all slaves.
1157  * 2) Remove all sentinels.
1158  * 3) Remove most of the flags resulting from runtime operations.
1159  * 4) Reset timers to their default value.
1160  * 5) In the process of doing this undo the failover if in progress.
1161  * 6) Disconnect the connections with the master (will reconnect automatically).
1162  */
1163 
1164 #define SENTINEL_RESET_NO_SENTINELS (1<<0)
1165 void sentinelResetMaster(sentinelRedisInstance *ri, int flags) {
1166     redisAssert(ri->flags & SRI_MASTER);
1167     dictRelease(ri->slaves);
1168     ri->slaves = dictCreate(&instancesDictType,NULL);
1169     if (!(flags & SENTINEL_RESET_NO_SENTINELS)) {
1170         dictRelease(ri->sentinels);
1171         ri->sentinels = dictCreate(&instancesDictType,NULL);
1172     }
1173     if (ri->cc) sentinelKillLink(ri,ri->cc);
1174     if (ri->pc) sentinelKillLink(ri,ri->pc);
1175     ri->flags &= SRI_MASTER|SRI_DISCONNECTED;
1176     if (ri->leader) {
1177         sdsfree(ri->leader);
1178         ri->leader = NULL;
1179     }
1180     ri->failover_state = SENTINEL_FAILOVER_STATE_NONE;
1181     ri->failover_state_change_time = 0;
1182     ri->failover_start_time = 0;
1183     ri->promoted_slave = NULL;
1184     sdsfree(ri->runid);
1185     sdsfree(ri->slave_master_host);
1186     ri->runid = NULL;
1187     ri->slave_master_host = NULL;
1188     ri->last_ping_time = mstime();
1189     ri->last_avail_time = mstime();
1190     ri->last_pong_time = mstime();
1191     ri->role_reported_time = mstime();
1192     ri->role_reported = SRI_MASTER;
1193     if (flags & SENTINEL_GENERATE_EVENT)
1194         sentinelEvent(REDIS_WARNING,"+reset-master",ri,"%@");
1195 }
1196 
1197 /* Call sentinelResetMaster() on every master with a name matching the specified
1198  * pattern. */
1199 int sentinelResetMastersByPattern(char *pattern, int flags) {
1200     dictIterator *di;
1201     dictEntry *de;
1202     int reset = 0;
1203 
1204     di = dictGetIterator(sentinel.masters);
1205     while((de = dictNext(di)) != NULL) {
1206         sentinelRedisInstance *ri = dictGetVal(de);
1207 
1208         if (ri->name) {
1209             if (stringmatch(pattern,ri->name,0)) {
1210                 sentinelResetMaster(ri,flags);
1211                 reset++;
1212             }
1213         }
1214     }
1215     dictReleaseIterator(di);
1216     return reset;
1217 }
1218 
1219 /* Reset the specified master with sentinelResetMaster(), and also change
1220  * the ip:port address, but take the name of the instance unmodified.
1221  *
1222  * This is used to handle the +switch-master event.
1223  *
1224  * The function returns REDIS_ERR if the address can't be resolved for some
1225  * reason. Otherwise REDIS_OK is returned.  */
1226 int sentinelResetMasterAndChangeAddress(sentinelRedisInstance *master, char *ip, int port) {
1227     sentinelAddr *oldaddr, *newaddr;
1228     sentinelAddr **slaves = NULL;
1229     int numslaves = 0, j;
1230     dictIterator *di;
1231     dictEntry *de;
1232 
1233     newaddr = createSentinelAddr(ip,port);
1234     if (newaddr == NULL) return REDIS_ERR;
1235 
1236     /* Make a list of slaves to add back after the reset.
1237      * Don't include the one having the address we are switching to. */
1238     di = dictGetIterator(master->slaves);
1239     while((de = dictNext(di)) != NULL) {
1240         sentinelRedisInstance *slave = dictGetVal(de);
1241 
1242         if (sentinelAddrIsEqual(slave->addr,newaddr)) continue;
1243         slaves = zrealloc(slaves,sizeof(sentinelAddr*)*(numslaves+1));
1244         slaves[numslaves++] = createSentinelAddr(slave->addr->ip,
1245                                                  slave->addr->port);
1246     }
1247     dictReleaseIterator(di);
1248 
1249     /* If we are switching to a different address, include the old address
1250      * as a slave as well, so that we'll be able to sense / reconfigure
1251      * the old master. */
1252     if (!sentinelAddrIsEqual(newaddr,master->addr)) {
1253         slaves = zrealloc(slaves,sizeof(sentinelAddr*)*(numslaves+1));
1254         slaves[numslaves++] = createSentinelAddr(master->addr->ip,
1255                                                  master->addr->port);
1256     }
1257 
1258     /* Reset and switch address. */
1259     sentinelResetMaster(master,SENTINEL_RESET_NO_SENTINELS);
1260     oldaddr = master->addr;
1261     master->addr = newaddr;
1262     master->o_down_since_time = 0;
1263     master->s_down_since_time = 0;
1264 
1265     /* Add slaves back. */
1266     for (j = 0; j < numslaves; j++) {
1267         sentinelRedisInstance *slave;
1268 
1269         slave = createSentinelRedisInstance(NULL,SRI_SLAVE,slaves[j]->ip,
1270                     slaves[j]->port, master->quorum, master);
1271         releaseSentinelAddr(slaves[j]);
1272         if (slave) {
1273             sentinelEvent(REDIS_NOTICE,"+slave",slave,"%@");
1274             sentinelFlushConfig();
1275         }
1276     }
1277     zfree(slaves);
1278 
1279     /* Release the old address at the end so we are safe even if the function
1280      * gets the master->addr->ip and master->addr->port as arguments. */
1281     releaseSentinelAddr(oldaddr);
1282     sentinelFlushConfig();
1283     return REDIS_OK;
1284 }
1285 
1286 /* Return non-zero if there was no SDOWN or ODOWN error associated to this
1287  * instance in the latest 'ms' milliseconds. */
1288 int sentinelRedisInstanceNoDownFor(sentinelRedisInstance *ri, mstime_t ms) {
1289     mstime_t most_recent;
1290 
1291     most_recent = ri->s_down_since_time;
1292     if (ri->o_down_since_time > most_recent)
1293         most_recent = ri->o_down_since_time;
1294     return most_recent == 0 || (mstime() - most_recent) > ms;
1295 }
1296 
1297 /* Return the current master address, that is, its address or the address
1298  * of the promoted slave if already operational. */
1299 sentinelAddr *sentinelGetCurrentMasterAddress(sentinelRedisInstance *master) {
1300     /* If we are failing over the master, and the state is already
1301      * SENTINEL_FAILOVER_STATE_RECONF_SLAVES or greater, it means that we
1302      * already have the new configuration epoch in the master, and the
1303      * slave acknowledged the configuration switch. Advertise the new
1304      * address. */
1305     if ((master->flags & SRI_FAILOVER_IN_PROGRESS) &&
1306         master->promoted_slave &&
1307         master->failover_state >= SENTINEL_FAILOVER_STATE_RECONF_SLAVES)
1308     {
1309         return master->promoted_slave->addr;
1310     } else {
1311         return master->addr;
1312     }
1313 }
1314 
1315 /* This function sets the down_after_period field value in 'master' to all
1316  * the slaves and sentinel instances connected to this master. */
1317 void sentinelPropagateDownAfterPeriod(sentinelRedisInstance *master) {
1318     dictIterator *di;
1319     dictEntry *de;
1320     int j;
1321     dict *d[] = {master->slaves, master->sentinels, NULL};
1322 
1323     for (j = 0; d[j]; j++) {
1324         di = dictGetIterator(d[j]);
1325         while((de = dictNext(di)) != NULL) {
1326             sentinelRedisInstance *ri = dictGetVal(de);
1327             ri->down_after_period = master->down_after_period;
1328         }
1329         dictReleaseIterator(di);
1330     }
1331 }
1332 
1333 /* ============================ Config handling ============================= */
1334 char *sentinelHandleConfiguration(char **argv, int argc) {
1335     sentinelRedisInstance *ri;
1336 
1337     if (!strcasecmp(argv[0],"monitor") && argc == 5) {
1338         /* monitor <name> <host> <port> <quorum> */
1339         int quorum = atoi(argv[4]);
1340 
1341         if (quorum <= 0) return "Quorum must be 1 or greater.";
1342         if (createSentinelRedisInstance(argv[1],SRI_MASTER,argv[2],
1343                                         atoi(argv[3]),quorum,NULL) == NULL)
1344         {
1345             switch(errno) {
1346             case EBUSY: return "Duplicated master name.";
1347             case ENOENT: return "Can't resolve master instance hostname.";
1348             case EINVAL: return "Invalid port number";
1349             }
1350         }
1351     } else if (!strcasecmp(argv[0],"down-after-milliseconds") && argc == 3) {
1352         /* down-after-milliseconds <name> <milliseconds> */
1353         ri = sentinelGetMasterByName(argv[1]);
1354         if (!ri) return "No such master with specified name.";
1355         ri->down_after_period = atoi(argv[2]);
1356         if (ri->down_after_period <= 0)
1357             return "negative or zero time parameter.";
1358         sentinelPropagateDownAfterPeriod(ri);
1359     } else if (!strcasecmp(argv[0],"failover-timeout") && argc == 3) {
1360         /* failover-timeout <name> <milliseconds> */
1361         ri = sentinelGetMasterByName(argv[1]);
1362         if (!ri) return "No such master with specified name.";
1363         ri->failover_timeout = atoi(argv[2]);
1364         if (ri->failover_timeout <= 0)
1365             return "negative or zero time parameter.";
1366    } else if (!strcasecmp(argv[0],"parallel-syncs") && argc == 3) {
1367         /* parallel-syncs <name> <milliseconds> */
1368         ri = sentinelGetMasterByName(argv[1]);
1369         if (!ri) return "No such master with specified name.";
1370         ri->parallel_syncs = atoi(argv[2]);
1371    } else if (!strcasecmp(argv[0],"notification-script") && argc == 3) {
1372         /* notification-script <name> <path> */
1373         ri = sentinelGetMasterByName(argv[1]);
1374         if (!ri) return "No such master with specified name.";
1375         if (access(argv[2],X_OK) == -1)
1376             return "Notification script seems non existing or non executable.";
1377         ri->notification_script = sdsnew(argv[2]);
1378    } else if (!strcasecmp(argv[0],"client-reconfig-script") && argc == 3) {
1379         /* client-reconfig-script <name> <path> */
1380         ri = sentinelGetMasterByName(argv[1]);
1381         if (!ri) return "No such master with specified name.";
1382         if (access(argv[2],X_OK) == -1)
1383             return "Client reconfiguration script seems non existing or "
1384                    "non executable.";
1385         ri->client_reconfig_script = sdsnew(argv[2]);
1386    } else if (!strcasecmp(argv[0],"auth-pass") && argc == 3) {
1387         /* auth-pass <name> <password> */
1388         ri = sentinelGetMasterByName(argv[1]);
1389         if (!ri) return "No such master with specified name.";
1390         ri->auth_pass = sdsnew(argv[2]);
1391     } else if (!strcasecmp(argv[0],"current-epoch") && argc == 2) {
1392         /* current-epoch <epoch> */
1393         unsigned long long current_epoch = strtoull(argv[1],NULL,10);
1394         if (current_epoch > sentinel.current_epoch)
1395             sentinel.current_epoch = current_epoch;
1396     } else if (!strcasecmp(argv[0],"config-epoch") && argc == 3) {
1397         /* config-epoch <name> <epoch> */
1398         ri = sentinelGetMasterByName(argv[1]);
1399         if (!ri) return "No such master with specified name.";
1400         ri->config_epoch = strtoull(argv[2],NULL,10);
1401         /* The following update of current_epoch is not really useful as
1402          * now the current epoch is persisted on the config file, but
1403          * we leave this check here for redundancy. */
1404         if (ri->config_epoch > sentinel.current_epoch)
1405             sentinel.current_epoch = ri->config_epoch;
1406     } else if (!strcasecmp(argv[0],"leader-epoch") && argc == 3) {
1407         /* leader-epoch <name> <epoch> */
1408         ri = sentinelGetMasterByName(argv[1]);
1409         if (!ri) return "No such master with specified name.";
1410         ri->leader_epoch = strtoull(argv[2],NULL,10);
1411     } else if (!strcasecmp(argv[0],"known-slave") && argc == 4) {
1412         sentinelRedisInstance *slave;
1413 
1414         /* known-slave <name> <ip> <port> */
1415         ri = sentinelGetMasterByName(argv[1]);
1416         if (!ri) return "No such master with specified name.";
1417         if ((slave = createSentinelRedisInstance(NULL,SRI_SLAVE,argv[2],
1418                     atoi(argv[3]), ri->quorum, ri)) == NULL)
1419         {
1420             return "Wrong hostname or port for slave.";
1421         }
1422     } else if (!strcasecmp(argv[0],"known-sentinel") &&
1423                (argc == 4 || argc == 5)) {
1424         sentinelRedisInstance *si;
1425 
1426         /* known-sentinel <name> <ip> <port> [runid] */
1427         ri = sentinelGetMasterByName(argv[1]);
1428         if (!ri) return "No such master with specified name.";
1429         if ((si = createSentinelRedisInstance(NULL,SRI_SENTINEL,argv[2],
1430                     atoi(argv[3]), ri->quorum, ri)) == NULL)
1431         {
1432             return "Wrong hostname or port for sentinel.";
1433         }
1434         if (argc == 5) si->runid = sdsnew(argv[4]);
1435     } else if (!strcasecmp(argv[0],"announce-ip") && argc == 2) {
1436         /* announce-ip <ip-address> */
1437         if (strlen(argv[1]))
1438             sentinel.announce_ip = sdsnew(argv[1]);
1439     } else if (!strcasecmp(argv[0],"announce-port") && argc == 2) {
1440         /* announce-port <port> */
1441         sentinel.announce_port = atoi(argv[1]);
1442     } else {
1443         return "Unrecognized sentinel configuration statement.";
1444     }
1445     return NULL;
1446 }
1447 
1448 /* Implements CONFIG REWRITE for "sentinel" option.
1449  * This is used not just to rewrite the configuration given by the user
1450  * (the configured masters) but also in order to retain the state of
1451  * Sentinel across restarts: config epoch of masters, associated slaves
1452  * and sentinel instances, and so forth. */
1453 void rewriteConfigSentinelOption(struct rewriteConfigState *state) {
1454     dictIterator *di, *di2;
1455     dictEntry *de;
1456     sds line;
1457 
1458     /* For every master emit a "sentinel monitor" config entry. */
1459     di = dictGetIterator(sentinel.masters);
1460     while((de = dictNext(di)) != NULL) {
1461         sentinelRedisInstance *master, *ri;
1462         sentinelAddr *master_addr;
1463 
1464         /* sentinel monitor */
1465         master = dictGetVal(de);
1466         master_addr = sentinelGetCurrentMasterAddress(master);
1467         line = sdscatprintf(sdsempty(),"sentinel monitor %s %s %d %d",
1468             master->name, master_addr->ip, master_addr->port,
1469             master->quorum);
1470         rewriteConfigRewriteLine(state,"sentinel",line,1);
1471 
1472         /* sentinel down-after-milliseconds */
1473         if (master->down_after_period != SENTINEL_DEFAULT_DOWN_AFTER) {
1474             line = sdscatprintf(sdsempty(),
1475                 "sentinel down-after-milliseconds %s %ld",
1476                 master->name, (long) master->down_after_period);
1477             rewriteConfigRewriteLine(state,"sentinel",line,1);
1478         }
1479 
1480         /* sentinel failover-timeout */
1481         if (master->failover_timeout != SENTINEL_DEFAULT_FAILOVER_TIMEOUT) {
1482             line = sdscatprintf(sdsempty(),
1483                 "sentinel failover-timeout %s %ld",
1484                 master->name, (long) master->failover_timeout);
1485             rewriteConfigRewriteLine(state,"sentinel",line,1);
1486         }
1487 
1488         /* sentinel parallel-syncs */
1489         if (master->parallel_syncs != SENTINEL_DEFAULT_PARALLEL_SYNCS) {
1490             line = sdscatprintf(sdsempty(),
1491                 "sentinel parallel-syncs %s %d",
1492                 master->name, master->parallel_syncs);
1493             rewriteConfigRewriteLine(state,"sentinel",line,1);
1494         }
1495 
1496         /* sentinel notification-script */
1497         if (master->notification_script) {
1498             line = sdscatprintf(sdsempty(),
1499                 "sentinel notification-script %s %s",
1500                 master->name, master->notification_script);
1501             rewriteConfigRewriteLine(state,"sentinel",line,1);
1502         }
1503 
1504         /* sentinel client-reconfig-script */
1505         if (master->client_reconfig_script) {
1506             line = sdscatprintf(sdsempty(),
1507                 "sentinel client-reconfig-script %s %s",
1508                 master->name, master->client_reconfig_script);
1509             rewriteConfigRewriteLine(state,"sentinel",line,1);
1510         }
1511 
1512         /* sentinel auth-pass */
1513         if (master->auth_pass) {
1514             line = sdscatprintf(sdsempty(),
1515                 "sentinel auth-pass %s %s",
1516                 master->name, master->auth_pass);
1517             rewriteConfigRewriteLine(state,"sentinel",line,1);
1518         }
1519 
1520         /* sentinel config-epoch */
1521         line = sdscatprintf(sdsempty(),
1522             "sentinel config-epoch %s %llu",
1523             master->name, (unsigned long long) master->config_epoch);
1524         rewriteConfigRewriteLine(state,"sentinel",line,1);
1525 
1526         /* sentinel leader-epoch */
1527         line = sdscatprintf(sdsempty(),
1528             "sentinel leader-epoch %s %llu",
1529             master->name, (unsigned long long) master->leader_epoch);
1530         rewriteConfigRewriteLine(state,"sentinel",line,1);
1531 
1532         /* sentinel known-slave */
1533         di2 = dictGetIterator(master->slaves);
1534         while((de = dictNext(di2)) != NULL) {
1535             sentinelAddr *slave_addr;
1536 
1537             ri = dictGetVal(de);
1538             slave_addr = ri->addr;
1539 
1540             /* If master_addr (obtained using sentinelGetCurrentMasterAddress()
1541              * so it may be the address of the promoted slave) is equal to this
1542              * slave's address, a failover is in progress and the slave was
1543              * already successfully promoted. So as the address of this slave
1544              * we use the old master address instead. */
1545             if (sentinelAddrIsEqual(slave_addr,master_addr))
1546                 slave_addr = master->addr;
1547             line = sdscatprintf(sdsempty(),
1548                 "sentinel known-slave %s %s %d",
1549                 master->name, ri->addr->ip, ri->addr->port);
1550             rewriteConfigRewriteLine(state,"sentinel",line,1);
1551         }
1552         dictReleaseIterator(di2);
1553 
1554         /* sentinel known-sentinel */
1555         di2 = dictGetIterator(master->sentinels);
1556         while((de = dictNext(di2)) != NULL) {
1557             ri = dictGetVal(de);
1558             line = sdscatprintf(sdsempty(),
1559                 "sentinel known-sentinel %s %s %d%s%s",
1560                 master->name, ri->addr->ip, ri->addr->port,
1561                 ri->runid ? " " : "",
1562                 ri->runid ? ri->runid : "");
1563             rewriteConfigRewriteLine(state,"sentinel",line,1);
1564         }
1565         dictReleaseIterator(di2);
1566     }
1567 
1568     /* sentinel current-epoch is a global state valid for all the masters. */
1569     line = sdscatprintf(sdsempty(),
1570         "sentinel current-epoch %llu", (unsigned long long) sentinel.current_epoch);
1571     rewriteConfigRewriteLine(state,"sentinel",line,1);
1572 
1573     /* sentinel announce-ip. */
1574     if (sentinel.announce_ip) {
1575         line = sdsnew("sentinel announce-ip ");
1576         line = sdscatrepr(line, sentinel.announce_ip, sdslen(sentinel.announce_ip));
1577         rewriteConfigRewriteLine(state,"sentinel",line,1);
1578     }
1579 
1580     /* sentinel announce-port. */
1581     if (sentinel.announce_port) {
1582         line = sdscatprintf(sdsempty(),"sentinel announce-port %d",
1583                             sentinel.announce_port);
1584         rewriteConfigRewriteLine(state,"sentinel",line,1);
1585     }
1586 
1587     dictReleaseIterator(di);
1588 }
1589 
1590 /* This function uses the config rewriting Redis engine in order to persist
1591  * the state of the Sentinel in the current configuration file.
1592  *
1593  * Before returning the function calls fsync() against the generated
1594  * configuration file to make sure changes are committed to disk.
1595  *
1596  * On failure the function logs a warning on the Redis log. */
1597 void sentinelFlushConfig(void) {
1598     int fd = -1;
1599     int saved_hz = server.hz;
1600     int rewrite_status;
1601 
1602     server.hz = REDIS_DEFAULT_HZ;
1603     rewrite_status = rewriteConfig(server.configfile);
1604     server.hz = saved_hz;
1605 
1606     if (rewrite_status == -1) goto werr;
1607     if ((fd = open(server.configfile,O_RDONLY)) == -1) goto werr;
1608     if (fsync(fd) == -1) goto werr;
1609     if (close(fd) == EOF) goto werr;
1610     return;
1611 
1612 werr:
1613     if (fd != -1) close(fd);
1614     redisLog(REDIS_WARNING,"WARNING: Sentinel was not able to save the new configuration on disk!!!: %s", strerror(errno));
1615 }
1616 
1617 /* ====================== hiredis connection handling ======================= */
1618 
1619 /* Completely disconnect a hiredis link from an instance. */
1620 void sentinelKillLink(sentinelRedisInstance *ri, redisAsyncContext *c) {
1621     if (ri->cc == c) {
1622         ri->cc = NULL;
1623         ri->pending_commands = 0;
1624     }
1625     if (ri->pc == c) ri->pc = NULL;
1626     c->data = NULL;
1627     ri->flags |= SRI_DISCONNECTED;
1628     redisAsyncFree(c);
1629 }
1630 
1631 /* This function takes a hiredis context that is in an error condition
1632  * and make sure to mark the instance as disconnected performing the
1633  * cleanup needed.
1634  *
1635  * Note: we don't free the hiredis context as hiredis will do it for us
1636  * for async connections. */
1637 void sentinelDisconnectInstanceFromContext(const redisAsyncContext *c) {
1638     sentinelRedisInstance *ri = c->data;
1639     int pubsub;
1640 
1641     if (ri == NULL) return; /* The instance no longer exists. */
1642 
1643     pubsub = (ri->pc == c);
1644     sentinelEvent(REDIS_DEBUG, pubsub ? "-pubsub-link" : "-cmd-link", ri,
1645         "%@ #%s", c->errstr);
1646     if (pubsub)
1647         ri->pc = NULL;
1648     else
1649         ri->cc = NULL;
1650     ri->flags |= SRI_DISCONNECTED;
1651 }
1652 
1653 void sentinelLinkEstablishedCallback(const redisAsyncContext *c, int status) {
1654     if (status != REDIS_OK) {
1655         sentinelDisconnectInstanceFromContext(c);
1656     } else {
1657         sentinelRedisInstance *ri = c->data;
1658         int pubsub = (ri->pc == c);
1659 
1660         sentinelEvent(REDIS_DEBUG, pubsub ? "+pubsub-link" : "+cmd-link", ri,
1661             "%@");
1662     }
1663 }
1664 
1665 void sentinelDisconnectCallback(const redisAsyncContext *c, int status) {
1666     REDIS_NOTUSED(status);
1667     sentinelDisconnectInstanceFromContext(c);
1668 }
1669 
1670 /* Send the AUTH command with the specified master password if needed.
1671  * Note that for slaves the password set for the master is used.
1672  *
1673  * We don't check at all if the command was successfully transmitted
1674  * to the instance as if it fails Sentinel will detect the instance down,
1675  * will disconnect and reconnect the link and so forth. */
1676 void sentinelSendAuthIfNeeded(sentinelRedisInstance *ri, redisAsyncContext *c) {
1677     char *auth_pass = (ri->flags & SRI_MASTER) ? ri->auth_pass :
1678                                                  ri->master->auth_pass;
1679 
1680     if (auth_pass) {
1681         if (redisAsyncCommand(c, sentinelDiscardReplyCallback, NULL, "AUTH %s",
1682             auth_pass) == REDIS_OK) ri->pending_commands++;
1683     }
1684 }
1685 
1686 /* Use CLIENT SETNAME to name the connection in the Redis instance as
1687  * sentinel-<first_8_chars_of_runid>-<connection_type>
1688  * The connection type is "cmd" or "pubsub" as specified by 'type'.
1689  *
1690  * This makes it possible to list all the sentinel instances connected
1691  * to a Redis servewr with CLIENT LIST, grepping for a specific name format. */
1692 void sentinelSetClientName(sentinelRedisInstance *ri, redisAsyncContext *c, char *type) {
1693     char name[64];
1694 
1695     snprintf(name,sizeof(name),"sentinel-%.8s-%s",server.runid,type);
1696     if (redisAsyncCommand(c, sentinelDiscardReplyCallback, NULL,
1697         "CLIENT SETNAME %s", name) == REDIS_OK)
1698     {
1699         ri->pending_commands++;
1700     }
1701 }
1702 
1703 /* Create the async connections for the specified instance if the instance
1704  * is disconnected. Note that the SRI_DISCONNECTED flag is set even if just
1705  * one of the two links (commands and pub/sub) is missing. */
1706 void sentinelReconnectInstance(sentinelRedisInstance *ri) {
1707     if (!(ri->flags & SRI_DISCONNECTED)) return;
1708 
1709     /* Commands connection. */
1710     if (ri->cc == NULL) {
1711         ri->cc = redisAsyncConnectBind(ri->addr->ip,ri->addr->port,REDIS_BIND_ADDR);
1712         if (ri->cc->err) {
1713             sentinelEvent(REDIS_DEBUG,"-cmd-link-reconnection",ri,"%@ #%s",
1714                 ri->cc->errstr);
1715             sentinelKillLink(ri,ri->cc);
1716         } else {
1717             ri->cc_conn_time = mstime();
1718             ri->cc->data = ri;
1719             redisAeAttach(server.el,ri->cc);
1720             redisAsyncSetConnectCallback(ri->cc,
1721                                             sentinelLinkEstablishedCallback);
1722             redisAsyncSetDisconnectCallback(ri->cc,
1723                                             sentinelDisconnectCallback);
1724             sentinelSendAuthIfNeeded(ri,ri->cc);
1725             sentinelSetClientName(ri,ri->cc,"cmd");
1726 
1727             /* Send a PING ASAP when reconnecting. */
1728             sentinelSendPing(ri);
1729         }
1730     }
1731     /* Pub / Sub */
1732     if ((ri->flags & (SRI_MASTER|SRI_SLAVE)) && ri->pc == NULL) {
1733         ri->pc = redisAsyncConnectBind(ri->addr->ip,ri->addr->port,REDIS_BIND_ADDR);
1734         if (ri->pc->err) {
1735             sentinelEvent(REDIS_DEBUG,"-pubsub-link-reconnection",ri,"%@ #%s",
1736                 ri->pc->errstr);
1737             sentinelKillLink(ri,ri->pc);
1738         } else {
1739             int retval;
1740 
1741             ri->pc_conn_time = mstime();
1742             ri->pc->data = ri;
1743             redisAeAttach(server.el,ri->pc);
1744             redisAsyncSetConnectCallback(ri->pc,
1745                                             sentinelLinkEstablishedCallback);
1746             redisAsyncSetDisconnectCallback(ri->pc,
1747                                             sentinelDisconnectCallback);
1748             sentinelSendAuthIfNeeded(ri,ri->pc);
1749             sentinelSetClientName(ri,ri->pc,"pubsub");
1750             /* Now we subscribe to the Sentinels "Hello" channel. */
1751             retval = redisAsyncCommand(ri->pc,
1752                 sentinelReceiveHelloMessages, NULL, "SUBSCRIBE %s",
1753                     SENTINEL_HELLO_CHANNEL);
1754             if (retval != REDIS_OK) {
1755                 /* If we can't subscribe, the Pub/Sub connection is useless
1756                  * and we can simply disconnect it and try again. */
1757                 sentinelKillLink(ri,ri->pc);
1758                 return;
1759             }
1760         }
1761     }
1762     /* Clear the DISCONNECTED flags only if we have both the connections
1763      * (or just the commands connection if this is a sentinel instance). */
1764     if (ri->cc && (ri->flags & SRI_SENTINEL || ri->pc))
1765         ri->flags &= ~SRI_DISCONNECTED;
1766 }
1767 
1768 /* ======================== Redis instances pinging  ======================== */
1769 
1770 /* Return true if master looks "sane", that is:
1771  * 1) It is actually a master in the current configuration.
1772  * 2) It reports itself as a master.
1773  * 3) It is not SDOWN or ODOWN.
1774  * 4) We obtained last INFO no more than two times the INFO period time ago. */
1775 int sentinelMasterLooksSane(sentinelRedisInstance *master) {
1776     return
1777         master->flags & SRI_MASTER &&
1778         master->role_reported == SRI_MASTER &&
1779         (master->flags & (SRI_S_DOWN|SRI_O_DOWN)) == 0 &&
1780         (mstime() - master->info_refresh) < SENTINEL_INFO_PERIOD*2;
1781 }
1782 
1783 /* Process the INFO output from masters. */
1784 void sentinelRefreshInstanceInfo(sentinelRedisInstance *ri, const char *info) {
1785     sds *lines;
1786     int numlines, j;
1787     int role = 0;
1788 
1789     /* cache full INFO output for instance */
1790     sdsfree(ri->info);
1791     ri->info = sdsnew(info);
1792 
1793     /* The following fields must be reset to a given value in the case they
1794      * are not found at all in the INFO output. */
1795     ri->master_link_down_time = 0;
1796 
1797     /* Process line by line. */
1798     lines = sdssplitlen(info,strlen(info),"\r\n",2,&numlines);
1799     for (j = 0; j < numlines; j++) {
1800         sentinelRedisInstance *slave;
1801         sds l = lines[j];
1802 
1803         /* run_id:<40 hex chars>*/
1804         if (sdslen(l) >= 47 && !memcmp(l,"run_id:",7)) {
1805             if (ri->runid == NULL) {
1806                 ri->runid = sdsnewlen(l+7,40);
1807             } else {
1808                 if (strncmp(ri->runid,l+7,40) != 0) {
1809                     sentinelEvent(REDIS_NOTICE,"+reboot",ri,"%@");
1810                     sdsfree(ri->runid);
1811                     ri->runid = sdsnewlen(l+7,40);
1812                 }
1813             }
1814         }
1815 
1816         /* old versions: slave0:<ip>,<port>,<state>
1817          * new versions: slave0:ip=127.0.0.1,port=9999,... */
1818         if ((ri->flags & SRI_MASTER) &&
1819             sdslen(l) >= 7 &&
1820             !memcmp(l,"slave",5) && isdigit(l[5]))
1821         {
1822             char *ip, *port, *end;
1823 
1824             if (strstr(l,"ip=") == NULL) {
1825                 /* Old format. */
1826                 ip = strchr(l,':'); if (!ip) continue;
1827                 ip++; /* Now ip points to start of ip address. */
1828                 port = strchr(ip,','); if (!port) continue;
1829                 *port = '\0'; /* nul term for easy access. */
1830                 port++; /* Now port points to start of port number. */
1831                 end = strchr(port,','); if (!end) continue;
1832                 *end = '\0'; /* nul term for easy access. */
1833             } else {
1834                 /* New format. */
1835                 ip = strstr(l,"ip="); if (!ip) continue;
1836                 ip += 3; /* Now ip points to start of ip address. */
1837                 port = strstr(l,"port="); if (!port) continue;
1838                 port += 5; /* Now port points to start of port number. */
1839                 /* Nul term both fields for easy access. */
1840                 end = strchr(ip,','); if (end) *end = '\0';
1841                 end = strchr(port,','); if (end) *end = '\0';
1842             }
1843 
1844             /* Check if we already have this slave into our table,
1845              * otherwise add it. */
1846             if (sentinelRedisInstanceLookupSlave(ri,ip,atoi(port)) == NULL) {
1847                 if ((slave = createSentinelRedisInstance(NULL,SRI_SLAVE,ip,
1848                             atoi(port), ri->quorum, ri)) != NULL)
1849                 {
1850                     sentinelEvent(REDIS_NOTICE,"+slave",slave,"%@");
1851                 }
1852             }
1853         }
1854 
1855         /* master_link_down_since_seconds:<seconds> */
1856         if (sdslen(l) >= 32 &&
1857             !memcmp(l,"master_link_down_since_seconds",30))
1858         {
1859             ri->master_link_down_time = strtoll(l+31,NULL,10)*1000;
1860         }
1861 
1862         /* role:<role> */
1863         if (!memcmp(l,"role:master",11)) role = SRI_MASTER;
1864         else if (!memcmp(l,"role:slave",10)) role = SRI_SLAVE;
1865 
1866         if (role == SRI_SLAVE) {
1867             /* master_host:<host> */
1868             if (sdslen(l) >= 12 && !memcmp(l,"master_host:",12)) {
1869                 if (ri->slave_master_host == NULL ||
1870                     strcasecmp(l+12,ri->slave_master_host))
1871                 {
1872                     sdsfree(ri->slave_master_host);
1873                     ri->slave_master_host = sdsnew(l+12);
1874                     ri->slave_conf_change_time = mstime();
1875                 }
1876             }
1877 
1878             /* master_port:<port> */
1879             if (sdslen(l) >= 12 && !memcmp(l,"master_port:",12)) {
1880                 int slave_master_port = atoi(l+12);
1881 
1882                 if (ri->slave_master_port != slave_master_port) {
1883                     ri->slave_master_port = slave_master_port;
1884                     ri->slave_conf_change_time = mstime();
1885                 }
1886             }
1887 
1888             /* master_link_status:<status> */
1889             if (sdslen(l) >= 19 && !memcmp(l,"master_link_status:",19)) {
1890                 ri->slave_master_link_status =
1891                     (strcasecmp(l+19,"up") == 0) ?
1892                     SENTINEL_MASTER_LINK_STATUS_UP :
1893                     SENTINEL_MASTER_LINK_STATUS_DOWN;
1894             }
1895 
1896             /* slave_priority:<priority> */
1897             if (sdslen(l) >= 15 && !memcmp(l,"slave_priority:",15))
1898                 ri->slave_priority = atoi(l+15);
1899 
1900             /* slave_repl_offset:<offset> */
1901             if (sdslen(l) >= 18 && !memcmp(l,"slave_repl_offset:",18))
1902                 ri->slave_repl_offset = strtoull(l+18,NULL,10);
1903         }
1904     }
1905     ri->info_refresh = mstime();
1906     sdsfreesplitres(lines,numlines);
1907 
1908     /* ---------------------------- Acting half -----------------------------
1909      * Some things will not happen if sentinel.tilt is true, but some will
1910      * still be processed. */
1911 
1912     /* Remember when the role changed. */
1913     if (role != ri->role_reported) {
1914         ri->role_reported_time = mstime();
1915         ri->role_reported = role;
1916         if (role == SRI_SLAVE) ri->slave_conf_change_time = mstime();
1917         /* Log the event with +role-change if the new role is coherent or
1918          * with -role-change if there is a mismatch with the current config. */
1919         sentinelEvent(REDIS_VERBOSE,
1920             ((ri->flags & (SRI_MASTER|SRI_SLAVE)) == role) ?
1921             "+role-change" : "-role-change",
1922             ri, "%@ new reported role is %s",
1923             role == SRI_MASTER ? "master" : "slave",
1924             ri->flags & SRI_MASTER ? "master" : "slave");
1925     }
1926 
1927     /* None of the following conditions are processed when in tilt mode, so
1928      * return asap. */
1929     if (sentinel.tilt) return;
1930 
1931     /* Handle master -> slave role switch. */
1932     if ((ri->flags & SRI_MASTER) && role == SRI_SLAVE) {
1933         /* Nothing to do, but masters claiming to be slaves are
1934          * considered to be unreachable by Sentinel, so eventually
1935          * a failover will be triggered. */
1936     }
1937 
1938     /* Handle slave -> master role switch. */
1939     if ((ri->flags & SRI_SLAVE) && role == SRI_MASTER) {
1940         /* If this is a promoted slave we can change state to the
1941          * failover state machine. */
1942         if ((ri->flags & SRI_PROMOTED) &&
1943             (ri->master->flags & SRI_FAILOVER_IN_PROGRESS) &&
1944             (ri->master->failover_state ==
1945                 SENTINEL_FAILOVER_STATE_WAIT_PROMOTION))
1946         {
1947             /* Now that we are sure the slave was reconfigured as a master
1948              * set the master configuration epoch to the epoch we won the
1949              * election to perform this failover. This will force the other
1950              * Sentinels to update their config (assuming there is not
1951              * a newer one already available). */
1952             ri->master->config_epoch = ri->master->failover_epoch;
1953             ri->master->failover_state = SENTINEL_FAILOVER_STATE_RECONF_SLAVES;
1954             ri->master->failover_state_change_time = mstime();
1955             sentinelFlushConfig();
1956             sentinelEvent(REDIS_WARNING,"+promoted-slave",ri,"%@");
1957             sentinelEvent(REDIS_WARNING,"+failover-state-reconf-slaves",
1958                 ri->master,"%@");
1959             sentinelCallClientReconfScript(ri->master,SENTINEL_LEADER,
1960                 "start",ri->master->addr,ri->addr);
1961             sentinelForceHelloUpdateForMaster(ri->master);
1962         } else {
1963             /* A slave turned into a master. We want to force our view and
1964              * reconfigure as slave. Wait some time after the change before
1965              * going forward, to receive new configs if any. */
1966             mstime_t wait_time = SENTINEL_PUBLISH_PERIOD*4;
1967 
1968             if (!(ri->flags & SRI_PROMOTED) &&
1969                  sentinelMasterLooksSane(ri->master) &&
1970                  sentinelRedisInstanceNoDownFor(ri,wait_time) &&
1971                  mstime() - ri->role_reported_time > wait_time)
1972             {
1973                 int retval = sentinelSendSlaveOf(ri,
1974                         ri->master->addr->ip,
1975                         ri->master->addr->port);
1976                 if (retval == REDIS_OK)
1977                     sentinelEvent(REDIS_NOTICE,"+convert-to-slave",ri,"%@");
1978             }
1979         }
1980     }
1981 
1982     /* Handle slaves replicating to a different master address. */
1983     if ((ri->flags & SRI_SLAVE) &&
1984         role == SRI_SLAVE &&
1985         (ri->slave_master_port != ri->master->addr->port ||
1986          strcasecmp(ri->slave_master_host,ri->master->addr->ip)))
1987     {
1988         mstime_t wait_time = ri->master->failover_timeout;
1989 
1990         /* Make sure the master is sane before reconfiguring this instance
1991          * into a slave. */
1992         if (sentinelMasterLooksSane(ri->master) &&
1993             sentinelRedisInstanceNoDownFor(ri,wait_time) &&
1994             mstime() - ri->slave_conf_change_time > wait_time)
1995         {
1996             int retval = sentinelSendSlaveOf(ri,
1997                     ri->master->addr->ip,
1998                     ri->master->addr->port);
1999             if (retval == REDIS_OK)
2000                 sentinelEvent(REDIS_NOTICE,"+fix-slave-config",ri,"%@");
2001         }
2002     }
2003 
2004     /* Detect if the slave that is in the process of being reconfigured
2005      * changed state. */
2006     if ((ri->flags & SRI_SLAVE) && role == SRI_SLAVE &&
2007         (ri->flags & (SRI_RECONF_SENT|SRI_RECONF_INPROG)))
2008     {
2009         /* SRI_RECONF_SENT -> SRI_RECONF_INPROG. */
2010         if ((ri->flags & SRI_RECONF_SENT) &&
2011             ri->slave_master_host &&
2012             strcmp(ri->slave_master_host,
2013                     ri->master->promoted_slave->addr->ip) == 0 &&
2014             ri->slave_master_port == ri->master->promoted_slave->addr->port)
2015         {
2016             ri->flags &= ~SRI_RECONF_SENT;
2017             ri->flags |= SRI_RECONF_INPROG;
2018             sentinelEvent(REDIS_NOTICE,"+slave-reconf-inprog",ri,"%@");
2019         }
2020 
2021         /* SRI_RECONF_INPROG -> SRI_RECONF_DONE */
2022         if ((ri->flags & SRI_RECONF_INPROG) &&
2023             ri->slave_master_link_status == SENTINEL_MASTER_LINK_STATUS_UP)
2024         {
2025             ri->flags &= ~SRI_RECONF_INPROG;
2026             ri->flags |= SRI_RECONF_DONE;
2027             sentinelEvent(REDIS_NOTICE,"+slave-reconf-done",ri,"%@");
2028         }
2029     }
2030 }
2031 
2032 void sentinelInfoReplyCallback(redisAsyncContext *c, void *reply, void *privdata) {
2033     sentinelRedisInstance *ri = c->data;
2034     redisReply *r;
2035     REDIS_NOTUSED(privdata);
2036 
2037     if (ri) ri->pending_commands--;
2038     if (!reply || !ri) return;
2039     r = reply;
2040 
2041     if (r->type == REDIS_REPLY_STRING) {
2042         sentinelRefreshInstanceInfo(ri,r->str);
2043     }
2044 }
2045 
2046 /* Just discard the reply. We use this when we are not monitoring the return
2047  * value of the command but its effects directly. */
2048 void sentinelDiscardReplyCallback(redisAsyncContext *c, void *reply, void *privdata) {
2049     sentinelRedisInstance *ri = c->data;
2050     REDIS_NOTUSED(reply);
2051     REDIS_NOTUSED(privdata);
2052 
2053     if (ri) ri->pending_commands--;
2054 }
2055 
2056 void sentinelPingReplyCallback(redisAsyncContext *c, void *reply, void *privdata) {
2057     sentinelRedisInstance *ri = c->data;
2058     redisReply *r;
2059     REDIS_NOTUSED(privdata);
2060 
2061     if (ri) ri->pending_commands--;
2062     if (!reply || !ri) return;
2063     r = reply;
2064 
2065     if (r->type == REDIS_REPLY_STATUS ||
2066         r->type == REDIS_REPLY_ERROR) {
2067         /* Update the "instance available" field only if this is an
2068          * acceptable reply. */
2069         if (strncmp(r->str,"PONG",4) == 0 ||
2070             strncmp(r->str,"LOADING",7) == 0 ||
2071             strncmp(r->str,"MASTERDOWN",10) == 0)
2072         {
2073             ri->last_avail_time = mstime();
2074             ri->last_ping_time = 0; /* Flag the pong as received. */
2075         } else {
2076             /* Send a SCRIPT KILL command if the instance appears to be
2077              * down because of a busy script. */
2078             if (strncmp(r->str,"BUSY",4) == 0 &&
2079                 (ri->flags & SRI_S_DOWN) &&
2080                 !(ri->flags & SRI_SCRIPT_KILL_SENT))
2081             {
2082                 if (redisAsyncCommand(ri->cc,
2083                         sentinelDiscardReplyCallback, NULL,
2084                         "SCRIPT KILL") == REDIS_OK)
2085                     ri->pending_commands++;
2086                 ri->flags |= SRI_SCRIPT_KILL_SENT;
2087             }
2088         }
2089     }
2090     ri->last_pong_time = mstime();
2091 }
2092 
2093 /* This is called when we get the reply about the PUBLISH command we send
2094  * to the master to advertise this sentinel. */
2095 void sentinelPublishReplyCallback(redisAsyncContext *c, void *reply, void *privdata) {
2096     sentinelRedisInstance *ri = c->data;
2097     redisReply *r;
2098     REDIS_NOTUSED(privdata);
2099 
2100     if (ri) ri->pending_commands--;
2101     if (!reply || !ri) return;
2102     r = reply;
2103 
2104     /* Only update pub_time if we actually published our message. Otherwise
2105      * we'll retry again in 100 milliseconds. */
2106     if (r->type != REDIS_REPLY_ERROR)
2107         ri->last_pub_time = mstime();
2108 }
2109 
2110 /* Process an hello message received via Pub/Sub in master or slave instance,
2111  * or sent directly to this sentinel via the (fake) PUBLISH command of Sentinel.
2112  *
2113  * If the master name specified in the message is not known, the message is
2114  * discarded. */
2115 void sentinelProcessHelloMessage(char *hello, int hello_len) {
2116     /* Format is composed of 8 tokens:
2117      * 0=ip,1=port,2=runid,3=current_epoch,4=master_name,
2118      * 5=master_ip,6=master_port,7=master_config_epoch. */
2119     int numtokens, port, removed, master_port;
2120     uint64_t current_epoch, master_config_epoch;
2121     char **token = sdssplitlen(hello, hello_len, ",", 1, &numtokens);
2122     sentinelRedisInstance *si, *master;
2123 
2124     if (numtokens == 8) {
2125         /* Obtain a reference to the master this hello message is about */
2126         master = sentinelGetMasterByName(token[4]);
2127         if (!master) goto cleanup; /* Unknown master, skip the message. */
2128 
2129         /* First, try to see if we already have this sentinel. */
2130         port = atoi(token[1]);
2131         master_port = atoi(token[6]);
2132         si = getSentinelRedisInstanceByAddrAndRunID(
2133                         master->sentinels,token[0],port,token[2]);
2134         current_epoch = strtoull(token[3],NULL,10);
2135         master_config_epoch = strtoull(token[7],NULL,10);
2136 
2137         if (!si) {
2138             /* If not, remove all the sentinels that have the same runid
2139              * OR the same ip/port, because it's either a restart or a
2140              * network topology change. */
2141             removed = removeMatchingSentinelsFromMaster(master,token[0],port,
2142                             token[2]);
2143             if (removed) {
2144                 sentinelEvent(REDIS_NOTICE,"-dup-sentinel",master,
2145                     "%@ #duplicate of %s:%d or %s",
2146                     token[0],port,token[2]);
2147             }
2148 
2149             /* Add the new sentinel. */
2150             si = createSentinelRedisInstance(NULL,SRI_SENTINEL,
2151                             token[0],port,master->quorum,master);
2152             if (si) {
2153                 sentinelEvent(REDIS_NOTICE,"+sentinel",si,"%@");
2154                 /* The runid is NULL after a new instance creation and
2155                  * for Sentinels we don't have a later chance to fill it,
2156                  * so do it now. */
2157                 si->runid = sdsnew(token[2]);
2158                 sentinelFlushConfig();
2159             }
2160         }
2161 
2162         /* Update local current_epoch if received current_epoch is greater.*/
2163         if (current_epoch > sentinel.current_epoch) {
2164             sentinel.current_epoch = current_epoch;
2165             sentinelFlushConfig();
2166             sentinelEvent(REDIS_WARNING,"+new-epoch",master,"%llu",
2167                 (unsigned long long) sentinel.current_epoch);
2168         }
2169 
2170         /* Update master info if received configuration is newer. */
2171         if (master->config_epoch < master_config_epoch) {
2172             master->config_epoch = master_config_epoch;
2173             if (master_port != master->addr->port ||
2174                 strcmp(master->addr->ip, token[5]))
2175             {
2176                 sentinelAddr *old_addr;
2177 
2178                 sentinelEvent(REDIS_WARNING,"+config-update-from",si,"%@");
2179                 sentinelEvent(REDIS_WARNING,"+switch-master",
2180                     master,"%s %s %d %s %d",
2181                     master->name,
2182                     master->addr->ip, master->addr->port,
2183                     token[5], master_port);
2184 
2185                 old_addr = dupSentinelAddr(master->addr);
2186                 sentinelResetMasterAndChangeAddress(master, token[5], master_port);
2187                 sentinelCallClientReconfScript(master,
2188                     SENTINEL_OBSERVER,"start",
2189                     old_addr,master->addr);
2190                 releaseSentinelAddr(old_addr);
2191             }
2192         }
2193 
2194         /* Update the state of the Sentinel. */
2195         if (si) si->last_hello_time = mstime();
2196     }
2197 
2198 cleanup:
2199     sdsfreesplitres(token,numtokens);
2200 }
2201 
2202 
2203 /* This is our Pub/Sub callback for the Hello channel. It's useful in order
2204  * to discover other sentinels attached at the same master. */
2205 void sentinelReceiveHelloMessages(redisAsyncContext *c, void *reply, void *privdata) {
2206     sentinelRedisInstance *ri = c->data;
2207     redisReply *r;
2208     REDIS_NOTUSED(privdata);
2209 
2210     if (!reply || !ri) return;
2211     r = reply;
2212 
2213     /* Update the last activity in the pubsub channel. Note that since we
2214      * receive our messages as well this timestamp can be used to detect
2215      * if the link is probably disconnected even if it seems otherwise. */
2216     ri->pc_last_activity = mstime();
2217 
2218     /* Sanity check in the reply we expect, so that the code that follows
2219      * can avoid to check for details. */
2220     if (r->type != REDIS_REPLY_ARRAY ||
2221         r->elements != 3 ||
2222         r->element[0]->type != REDIS_REPLY_STRING ||
2223         r->element[1]->type != REDIS_REPLY_STRING ||
2224         r->element[2]->type != REDIS_REPLY_STRING ||
2225         strcmp(r->element[0]->str,"message") != 0) return;
2226 
2227     /* We are not interested in meeting ourselves */
2228     if (strstr(r->element[2]->str,server.runid) != NULL) return;
2229 
2230     sentinelProcessHelloMessage(r->element[2]->str, r->element[2]->len);
2231 }
2232 
2233 /* Send an "Hello" message via Pub/Sub to the specified 'ri' Redis
2234  * instance in order to broadcast the current configuraiton for this
2235  * master, and to advertise the existence of this Sentinel at the same time.
2236  *
2237  * The message has the following format:
2238  *
2239  * sentinel_ip,sentinel_port,sentinel_runid,current_epoch,
2240  * master_name,master_ip,master_port,master_config_epoch.
2241  *
2242  * Returns REDIS_OK if the PUBLISH was queued correctly, otherwise
2243  * REDIS_ERR is returned. */
2244 int sentinelSendHello(sentinelRedisInstance *ri) {
2245     char ip[REDIS_IP_STR_LEN];
2246     char payload[REDIS_IP_STR_LEN+1024];
2247     int retval;
2248     char *announce_ip;
2249     int announce_port;
2250     sentinelRedisInstance *master = (ri->flags & SRI_MASTER) ? ri : ri->master;
2251     sentinelAddr *master_addr = sentinelGetCurrentMasterAddress(master);
2252 
2253     if (ri->flags & SRI_DISCONNECTED) return REDIS_ERR;
2254 
2255     /* Use the specified announce address if specified, otherwise try to
2256      * obtain our own IP address. */
2257     if (sentinel.announce_ip) {
2258         announce_ip = sentinel.announce_ip;
2259     } else {
2260         if (anetSockName(ri->cc->c.fd,ip,sizeof(ip),NULL) == -1)
2261             return REDIS_ERR;
2262         announce_ip = ip;
2263     }
2264     announce_port = sentinel.announce_port ?
2265                     sentinel.announce_port : server.port;
2266 
2267     /* Format and send the Hello message. */
2268     snprintf(payload,sizeof(payload),
2269         "%s,%d,%s,%llu," /* Info about this sentinel. */
2270         "%s,%s,%d,%llu", /* Info about current master. */
2271         announce_ip, announce_port, server.runid,
2272         (unsigned long long) sentinel.current_epoch,
2273         /* --- */
2274         master->name,master_addr->ip,master_addr->port,
2275         (unsigned long long) master->config_epoch);
2276     retval = redisAsyncCommand(ri->cc,
2277         sentinelPublishReplyCallback, NULL, "PUBLISH %s %s",
2278             SENTINEL_HELLO_CHANNEL,payload);
2279     if (retval != REDIS_OK) return REDIS_ERR;
2280     ri->pending_commands++;
2281     return REDIS_OK;
2282 }
2283 
2284 /* Reset last_pub_time in all the instances in the specified dictionary
2285  * in order to force the delivery of an Hello update ASAP. */
2286 void sentinelForceHelloUpdateDictOfRedisInstances(dict *instances) {
2287     dictIterator *di;
2288     dictEntry *de;
2289 
2290     di = dictGetSafeIterator(instances);
2291     while((de = dictNext(di)) != NULL) {
2292         sentinelRedisInstance *ri = dictGetVal(de);
2293         if (ri->last_pub_time >= (SENTINEL_PUBLISH_PERIOD+1))
2294             ri->last_pub_time -= (SENTINEL_PUBLISH_PERIOD+1);
2295     }
2296     dictReleaseIterator(di);
2297 }
2298 
2299 /* This function forces the delivery of an "Hello" message (see
2300  * sentinelSendHello() top comment for further information) to all the Redis
2301  * and Sentinel instances related to the specified 'master'.
2302  *
2303  * It is technically not needed since we send an update to every instance
2304  * with a period of SENTINEL_PUBLISH_PERIOD milliseconds, however when a
2305  * Sentinel upgrades a configuration it is a good idea to deliever an update
2306  * to the other Sentinels ASAP. */
2307 int sentinelForceHelloUpdateForMaster(sentinelRedisInstance *master) {
2308     if (!(master->flags & SRI_MASTER)) return REDIS_ERR;
2309     if (master->last_pub_time >= (SENTINEL_PUBLISH_PERIOD+1))
2310         master->last_pub_time -= (SENTINEL_PUBLISH_PERIOD+1);
2311     sentinelForceHelloUpdateDictOfRedisInstances(master->sentinels);
2312     sentinelForceHelloUpdateDictOfRedisInstances(master->slaves);
2313     return REDIS_OK;
2314 }
2315 
2316 /* Send a PING to the specified instance and refresh the last_ping_time
2317  * if it is zero (that is, if we received a pong for the previous ping).
2318  *
2319  * On error zero is returned, and we can't consider the PING command
2320  * queued in the connection. */
2321 int sentinelSendPing(sentinelRedisInstance *ri) {
2322     int retval = redisAsyncCommand(ri->cc,
2323         sentinelPingReplyCallback, NULL, "PING");
2324     if (retval == REDIS_OK) {
2325         ri->pending_commands++;
2326         /* We update the ping time only if we received the pong for
2327          * the previous ping, otherwise we are technically waiting
2328          * since the first ping that did not received a reply. */
2329         if (ri->last_ping_time == 0) ri->last_ping_time = mstime();
2330         return 1;
2331     } else {
2332         return 0;
2333     }
2334 }
2335 
2336 /* Send periodic PING, INFO, and PUBLISH to the Hello channel to
2337  * the specified master or slave instance. */
2338 void sentinelSendPeriodicCommands(sentinelRedisInstance *ri) {
2339     mstime_t now = mstime();
2340     mstime_t info_period, ping_period;
2341     int retval;
2342 
2343     /* Return ASAP if we have already a PING or INFO already pending, or
2344      * in the case the instance is not properly connected. */
2345     if (ri->flags & SRI_DISCONNECTED) return;
2346 
2347     /* For INFO, PING, PUBLISH that are not critical commands to send we
2348      * also have a limit of SENTINEL_MAX_PENDING_COMMANDS. We don't
2349      * want to use a lot of memory just because a link is not working
2350      * properly (note that anyway there is a redundant protection about this,
2351      * that is, the link will be disconnected and reconnected if a long
2352      * timeout condition is detected. */
2353     if (ri->pending_commands >= SENTINEL_MAX_PENDING_COMMANDS) return;
2354 
2355     /* If this is a slave of a master in O_DOWN condition we start sending
2356      * it INFO every second, instead of the usual SENTINEL_INFO_PERIOD
2357      * period. In this state we want to closely monitor slaves in case they
2358      * are turned into masters by another Sentinel, or by the sysadmin. */
2359     if ((ri->flags & SRI_SLAVE) &&
2360         (ri->master->flags & (SRI_O_DOWN|SRI_FAILOVER_IN_PROGRESS))) {
2361         info_period = 1000;
2362     } else {
2363         info_period = SENTINEL_INFO_PERIOD;
2364     }
2365 
2366     /* We ping instances every time the last received pong is older than
2367      * the configured 'down-after-milliseconds' time, but every second
2368      * anyway if 'down-after-milliseconds' is greater than 1 second. */
2369     ping_period = ri->down_after_period;
2370     if (ping_period > SENTINEL_PING_PERIOD) ping_period = SENTINEL_PING_PERIOD;
2371 
2372     if ((ri->flags & SRI_SENTINEL) == 0 &&
2373         (ri->info_refresh == 0 ||
2374         (now - ri->info_refresh) > info_period))
2375     {
2376         /* Send INFO to masters and slaves, not sentinels. */
2377         retval = redisAsyncCommand(ri->cc,
2378             sentinelInfoReplyCallback, NULL, "INFO");
2379         if (retval == REDIS_OK) ri->pending_commands++;
2380     } else if ((now - ri->last_pong_time) > ping_period) {
2381         /* Send PING to all the three kinds of instances. */
2382         sentinelSendPing(ri);
2383     } else if ((now - ri->last_pub_time) > SENTINEL_PUBLISH_PERIOD) {
2384         /* PUBLISH hello messages to all the three kinds of instances. */
2385         sentinelSendHello(ri);
2386     }
2387 }
2388 
2389 /* =========================== SENTINEL command ============================= */
2390 
2391 const char *sentinelFailoverStateStr(int state) {
2392     switch(state) {
2393     case SENTINEL_FAILOVER_STATE_NONE: return "none";
2394     case SENTINEL_FAILOVER_STATE_WAIT_START: return "wait_start";
2395     case SENTINEL_FAILOVER_STATE_SELECT_SLAVE: return "select_slave";
2396     case SENTINEL_FAILOVER_STATE_SEND_SLAVEOF_NOONE: return "send_slaveof_noone";
2397     case SENTINEL_FAILOVER_STATE_WAIT_PROMOTION: return "wait_promotion";
2398     case SENTINEL_FAILOVER_STATE_RECONF_SLAVES: return "reconf_slaves";
2399     case SENTINEL_FAILOVER_STATE_UPDATE_CONFIG: return "update_config";
2400     default: return "unknown";
2401     }
2402 }
2403 
2404 /* Redis instance to Redis protocol representation. */
2405 void addReplySentinelRedisInstance(redisClient *c, sentinelRedisInstance *ri) {
2406     char *flags = sdsempty();
2407     void *mbl;
2408     int fields = 0;
2409 
2410     mbl = addDeferredMultiBulkLength(c);
2411 
2412     addReplyBulkCString(c,"name");
2413     addReplyBulkCString(c,ri->name);
2414     fields++;
2415 
2416     addReplyBulkCString(c,"ip");
2417     addReplyBulkCString(c,ri->addr->ip);
2418     fields++;
2419 
2420     addReplyBulkCString(c,"port");
2421     addReplyBulkLongLong(c,ri->addr->port);
2422     fields++;
2423 
2424     addReplyBulkCString(c,"runid");
2425     addReplyBulkCString(c,ri->runid ? ri->runid : "");
2426     fields++;
2427 
2428     addReplyBulkCString(c,"flags");
2429     if (ri->flags & SRI_S_DOWN) flags = sdscat(flags,"s_down,");
2430     if (ri->flags & SRI_O_DOWN) flags = sdscat(flags,"o_down,");
2431     if (ri->flags & SRI_MASTER) flags = sdscat(flags,"master,");
2432     if (ri->flags & SRI_SLAVE) flags = sdscat(flags,"slave,");
2433     if (ri->flags & SRI_SENTINEL) flags = sdscat(flags,"sentinel,");
2434     if (ri->flags & SRI_DISCONNECTED) flags = sdscat(flags,"disconnected,");
2435     if (ri->flags & SRI_MASTER_DOWN) flags = sdscat(flags,"master_down,");
2436     if (ri->flags & SRI_FAILOVER_IN_PROGRESS)
2437         flags = sdscat(flags,"failover_in_progress,");
2438     if (ri->flags & SRI_PROMOTED) flags = sdscat(flags,"promoted,");
2439     if (ri->flags & SRI_RECONF_SENT) flags = sdscat(flags,"reconf_sent,");
2440     if (ri->flags & SRI_RECONF_INPROG) flags = sdscat(flags,"reconf_inprog,");
2441     if (ri->flags & SRI_RECONF_DONE) flags = sdscat(flags,"reconf_done,");
2442 
2443     if (sdslen(flags) != 0) sdsrange(flags,0,-2); /* remove last "," */
2444     addReplyBulkCString(c,flags);
2445     sdsfree(flags);
2446     fields++;
2447 
2448     addReplyBulkCString(c,"pending-commands");
2449     addReplyBulkLongLong(c,ri->pending_commands);
2450     fields++;
2451 
2452     if (ri->flags & SRI_FAILOVER_IN_PROGRESS) {
2453         addReplyBulkCString(c,"failover-state");
2454         addReplyBulkCString(c,(char*)sentinelFailoverStateStr(ri->failover_state));
2455         fields++;
2456     }
2457 
2458     addReplyBulkCString(c,"last-ping-sent");
2459     addReplyBulkLongLong(c,
2460         ri->last_ping_time ? (mstime() - ri->last_ping_time) : 0);
2461     fields++;
2462 
2463     addReplyBulkCString(c,"last-ok-ping-reply");
2464     addReplyBulkLongLong(c,mstime() - ri->last_avail_time);
2465     fields++;
2466 
2467     addReplyBulkCString(c,"last-ping-reply");
2468     addReplyBulkLongLong(c,mstime() - ri->last_pong_time);
2469     fields++;
2470 
2471     if (ri->flags & SRI_S_DOWN) {
2472         addReplyBulkCString(c,"s-down-time");
2473         addReplyBulkLongLong(c,mstime()-ri->s_down_since_time);
2474         fields++;
2475     }
2476 
2477     if (ri->flags & SRI_O_DOWN) {
2478         addReplyBulkCString(c,"o-down-time");
2479         addReplyBulkLongLong(c,mstime()-ri->o_down_since_time);
2480         fields++;
2481     }
2482 
2483     addReplyBulkCString(c,"down-after-milliseconds");
2484     addReplyBulkLongLong(c,ri->down_after_period);
2485     fields++;
2486 
2487     /* Masters and Slaves */
2488     if (ri->flags & (SRI_MASTER|SRI_SLAVE)) {
2489         addReplyBulkCString(c,"info-refresh");
2490         addReplyBulkLongLong(c,mstime() - ri->info_refresh);
2491         fields++;
2492 
2493         addReplyBulkCString(c,"role-reported");
2494         addReplyBulkCString(c, (ri->role_reported == SRI_MASTER) ? "master" :
2495                                                                    "slave");
2496         fields++;
2497 
2498         addReplyBulkCString(c,"role-reported-time");
2499         addReplyBulkLongLong(c,mstime() - ri->role_reported_time);
2500         fields++;
2501     }
2502 
2503     /* Only masters */
2504     if (ri->flags & SRI_MASTER) {
2505         addReplyBulkCString(c,"config-epoch");
2506         addReplyBulkLongLong(c,ri->config_epoch);
2507         fields++;
2508 
2509         addReplyBulkCString(c,"num-slaves");
2510         addReplyBulkLongLong(c,dictSize(ri->slaves));
2511         fields++;
2512 
2513         addReplyBulkCString(c,"num-other-sentinels");
2514         addReplyBulkLongLong(c,dictSize(ri->sentinels));
2515         fields++;
2516 
2517         addReplyBulkCString(c,"quorum");
2518         addReplyBulkLongLong(c,ri->quorum);
2519         fields++;
2520 
2521         addReplyBulkCString(c,"failover-timeout");
2522         addReplyBulkLongLong(c,ri->failover_timeout);
2523         fields++;
2524 
2525         addReplyBulkCString(c,"parallel-syncs");
2526         addReplyBulkLongLong(c,ri->parallel_syncs);
2527         fields++;
2528 
2529         if (ri->notification_script) {
2530             addReplyBulkCString(c,"notification-script");
2531             addReplyBulkCString(c,ri->notification_script);
2532             fields++;
2533         }
2534 
2535         if (ri->client_reconfig_script) {
2536             addReplyBulkCString(c,"client-reconfig-script");
2537             addReplyBulkCString(c,ri->client_reconfig_script);
2538             fields++;
2539         }
2540     }
2541 
2542     /* Only slaves */
2543     if (ri->flags & SRI_SLAVE) {
2544         addReplyBulkCString(c,"master-link-down-time");
2545         addReplyBulkLongLong(c,ri->master_link_down_time);
2546         fields++;
2547 
2548         addReplyBulkCString(c,"master-link-status");
2549         addReplyBulkCString(c,
2550             (ri->slave_master_link_status == SENTINEL_MASTER_LINK_STATUS_UP) ?
2551             "ok" : "err");
2552         fields++;
2553 
2554         addReplyBulkCString(c,"master-host");
2555         addReplyBulkCString(c,
2556             ri->slave_master_host ? ri->slave_master_host : "?");
2557         fields++;
2558 
2559         addReplyBulkCString(c,"master-port");
2560         addReplyBulkLongLong(c,ri->slave_master_port);
2561         fields++;
2562 
2563         addReplyBulkCString(c,"slave-priority");
2564         addReplyBulkLongLong(c,ri->slave_priority);
2565         fields++;
2566 
2567         addReplyBulkCString(c,"slave-repl-offset");
2568         addReplyBulkLongLong(c,ri->slave_repl_offset);
2569         fields++;
2570     }
2571 
2572     /* Only sentinels */
2573     if (ri->flags & SRI_SENTINEL) {
2574         addReplyBulkCString(c,"last-hello-message");
2575         addReplyBulkLongLong(c,mstime() - ri->last_hello_time);
2576         fields++;
2577 
2578         addReplyBulkCString(c,"voted-leader");
2579         addReplyBulkCString(c,ri->leader ? ri->leader : "?");
2580         fields++;
2581 
2582         addReplyBulkCString(c,"voted-leader-epoch");
2583         addReplyBulkLongLong(c,ri->leader_epoch);
2584         fields++;
2585     }
2586 
2587     setDeferredMultiBulkLength(c,mbl,fields*2);
2588 }
2589 
2590 /* Output a number of instances contained inside a dictionary as
2591  * Redis protocol. */
2592 void addReplyDictOfRedisInstances(redisClient *c, dict *instances) {
2593     dictIterator *di;
2594     dictEntry *de;
2595 
2596     di = dictGetIterator(instances);
2597     addReplyMultiBulkLen(c,dictSize(instances));
2598     while((de = dictNext(di)) != NULL) {
2599         sentinelRedisInstance *ri = dictGetVal(de);
2600 
2601         addReplySentinelRedisInstance(c,ri);
2602     }
2603     dictReleaseIterator(di);
2604 }
2605 
2606 /* Lookup the named master into sentinel.masters.
2607  * If the master is not found reply to the client with an error and returns
2608  * NULL. */
2609 sentinelRedisInstance *sentinelGetMasterByNameOrReplyError(redisClient *c,
2610                         robj *name)
2611 {
2612     sentinelRedisInstance *ri;
2613 
2614     ri = dictFetchValue(sentinel.masters,name->ptr);
2615     if (!ri) {
2616         addReplyError(c,"No such master with that name");
2617         return NULL;
2618     }
2619     return ri;
2620 }
2621 
2622 void sentinelCommand(redisClient *c) {
2623     if (!strcasecmp(c->argv[1]->ptr,"masters")) {
2624         /* SENTINEL MASTERS */
2625         if (c->argc != 2) goto numargserr;
2626         addReplyDictOfRedisInstances(c,sentinel.masters);
2627     } else if (!strcasecmp(c->argv[1]->ptr,"master")) {
2628         /* SENTINEL MASTER <name> */
2629         sentinelRedisInstance *ri;
2630 
2631         if (c->argc != 3) goto numargserr;
2632         if ((ri = sentinelGetMasterByNameOrReplyError(c,c->argv[2]))
2633             == NULL) return;
2634         addReplySentinelRedisInstance(c,ri);
2635     } else if (!strcasecmp(c->argv[1]->ptr,"slaves")) {
2636         /* SENTINEL SLAVES <master-name> */
2637         sentinelRedisInstance *ri;
2638 
2639         if (c->argc != 3) goto numargserr;
2640         if ((ri = sentinelGetMasterByNameOrReplyError(c,c->argv[2])) == NULL)
2641             return;
2642         addReplyDictOfRedisInstances(c,ri->slaves);
2643     } else if (!strcasecmp(c->argv[1]->ptr,"sentinels")) {
2644         /* SENTINEL SENTINELS <master-name> */
2645         sentinelRedisInstance *ri;
2646 
2647         if (c->argc != 3) goto numargserr;
2648         if ((ri = sentinelGetMasterByNameOrReplyError(c,c->argv[2])) == NULL)
2649             return;
2650         addReplyDictOfRedisInstances(c,ri->sentinels);
2651     } else if (!strcasecmp(c->argv[1]->ptr,"is-master-down-by-addr")) {
2652         /* SENTINEL IS-MASTER-DOWN-BY-ADDR <ip> <port> <current-epoch> <runid>*/
2653         sentinelRedisInstance *ri;
2654         long long req_epoch;
2655         uint64_t leader_epoch = 0;
2656         char *leader = NULL;
2657         long port;
2658         int isdown = 0;
2659 
2660         if (c->argc != 6) goto numargserr;
2661         if (getLongFromObjectOrReply(c,c->argv[3],&port,NULL) != REDIS_OK ||
2662             getLongLongFromObjectOrReply(c,c->argv[4],&req_epoch,NULL)
2663                                                               != REDIS_OK)
2664             return;
2665         ri = getSentinelRedisInstanceByAddrAndRunID(sentinel.masters,
2666             c->argv[2]->ptr,port,NULL);
2667 
2668         /* It exists? Is actually a master? Is subjectively down? It's down.
2669          * Note: if we are in tilt mode we always reply with "0". */
2670         if (!sentinel.tilt && ri && (ri->flags & SRI_S_DOWN) &&
2671                                     (ri->flags & SRI_MASTER))
2672             isdown = 1;
2673 
2674         /* Vote for the master (or fetch the previous vote) if the request
2675          * includes a runid, otherwise the sender is not seeking for a vote. */
2676         if (ri && ri->flags & SRI_MASTER && strcasecmp(c->argv[5]->ptr,"*")) {
2677             leader = sentinelVoteLeader(ri,(uint64_t)req_epoch,
2678                                             c->argv[5]->ptr,
2679                                             &leader_epoch);
2680         }
2681 
2682         /* Reply with a three-elements multi-bulk reply:
2683          * down state, leader, vote epoch. */
2684         addReplyMultiBulkLen(c,3);
2685         addReply(c, isdown ? shared.cone : shared.czero);
2686         addReplyBulkCString(c, leader ? leader : "*");
2687         addReplyLongLong(c, (long long)leader_epoch);
2688         if (leader) sdsfree(leader);
2689     } else if (!strcasecmp(c->argv[1]->ptr,"reset")) {
2690         /* SENTINEL RESET <pattern> */
2691         if (c->argc != 3) goto numargserr;
2692         addReplyLongLong(c,sentinelResetMastersByPattern(c->argv[2]->ptr,SENTINEL_GENERATE_EVENT));
2693     } else if (!strcasecmp(c->argv[1]->ptr,"get-master-addr-by-name")) {
2694         /* SENTINEL GET-MASTER-ADDR-BY-NAME <master-name> */
2695         sentinelRedisInstance *ri;
2696 
2697         if (c->argc != 3) goto numargserr;
2698         ri = sentinelGetMasterByName(c->argv[2]->ptr);
2699         if (ri == NULL) {
2700             addReply(c,shared.nullmultibulk);
2701         } else {
2702             sentinelAddr *addr = sentinelGetCurrentMasterAddress(ri);
2703 
2704             addReplyMultiBulkLen(c,2);
2705             addReplyBulkCString(c,addr->ip);
2706             addReplyBulkLongLong(c,addr->port);
2707         }
2708     } else if (!strcasecmp(c->argv[1]->ptr,"failover")) {
2709         /* SENTINEL FAILOVER <master-name> */
2710         sentinelRedisInstance *ri;
2711 
2712         if (c->argc != 3) goto numargserr;
2713         if ((ri = sentinelGetMasterByNameOrReplyError(c,c->argv[2])) == NULL)
2714             return;
2715         if (ri->flags & SRI_FAILOVER_IN_PROGRESS) {
2716             addReplySds(c,sdsnew("-INPROG Failover already in progress\r\n"));
2717             return;
2718         }
2719         if (sentinelSelectSlave(ri) == NULL) {
2720             addReplySds(c,sdsnew("-NOGOODSLAVE No suitable slave to promote\r\n"));
2721             return;
2722         }
2723         redisLog(REDIS_WARNING,"Executing user requested FAILOVER of '%s'",
2724             ri->name);
2725         sentinelStartFailover(ri);
2726         ri->flags |= SRI_FORCE_FAILOVER;
2727         addReply(c,shared.ok);
2728     } else if (!strcasecmp(c->argv[1]->ptr,"pending-scripts")) {
2729         /* SENTINEL PENDING-SCRIPTS */
2730 
2731         if (c->argc != 2) goto numargserr;
2732         sentinelPendingScriptsCommand(c);
2733     } else if (!strcasecmp(c->argv[1]->ptr,"monitor")) {
2734         /* SENTINEL MONITOR <name> <ip> <port> <quorum> */
2735         sentinelRedisInstance *ri;
2736         long quorum, port;
2737         char ip[REDIS_IP_STR_LEN];
2738 
2739         if (c->argc != 6) goto numargserr;
2740         if (getLongFromObjectOrReply(c,c->argv[5],&quorum,"Invalid quorum")
2741             != REDIS_OK) return;
2742         if (getLongFromObjectOrReply(c,c->argv[4],&port,"Invalid port")
2743             != REDIS_OK) return;
2744         /* Make sure the IP field is actually a valid IP before passing it
2745          * to createSentinelRedisInstance(), otherwise we may trigger a
2746          * DNS lookup at runtime. */
2747         if (anetResolveIP(NULL,c->argv[3]->ptr,ip,sizeof(ip)) == ANET_ERR) {
2748             addReplyError(c,"Invalid IP address specified");
2749             return;
2750         }
2751 
2752         /* Parameters are valid. Try to create the master instance. */
2753         ri = createSentinelRedisInstance(c->argv[2]->ptr,SRI_MASTER,
2754                 c->argv[3]->ptr,port,quorum,NULL);
2755         if (ri == NULL) {
2756             switch(errno) {
2757             case EBUSY:
2758                 addReplyError(c,"Duplicated master name");
2759                 break;
2760             case EINVAL:
2761                 addReplyError(c,"Invalid port number");
2762                 break;
2763             default:
2764                 addReplyError(c,"Unspecified error adding the instance");
2765                 break;
2766             }
2767         } else {
2768             sentinelFlushConfig();
2769             sentinelEvent(REDIS_WARNING,"+monitor",ri,"%@ quorum %d",ri->quorum);
2770             addReply(c,shared.ok);
2771         }
2772     } else if (!strcasecmp(c->argv[1]->ptr,"remove")) {
2773         /* SENTINEL REMOVE <name> */
2774         sentinelRedisInstance *ri;
2775 
2776         if ((ri = sentinelGetMasterByNameOrReplyError(c,c->argv[2]))
2777             == NULL) return;
2778         sentinelEvent(REDIS_WARNING,"-monitor",ri,"%@");
2779         dictDelete(sentinel.masters,c->argv[2]->ptr);
2780         sentinelFlushConfig();
2781         addReply(c,shared.ok);
2782     } else if (!strcasecmp(c->argv[1]->ptr,"set")) {
2783         if (c->argc < 3 || c->argc % 2 == 0) goto numargserr;
2784         sentinelSetCommand(c);
2785     } else if (!strcasecmp(c->argv[1]->ptr,"info-cache")) {
2786         if (c->argc < 2) goto numargserr;
2787         mstime_t now = mstime();
2788 
2789         /* Create an ad-hoc dictionary type so that we can iterate
2790          * a dictionary composed of just the master groups the user
2791          * requested. */
2792         dictType copy_keeper = instancesDictType;
2793         copy_keeper.valDestructor = NULL;
2794         dict *masters_local = sentinel.masters;
2795         if (c->argc > 2) {
2796             masters_local = dictCreate(&copy_keeper, NULL);
2797 
2798             for (int i = 2; i < c->argc; i++) {
2799                 sentinelRedisInstance *ri;
2800                 ri = sentinelGetMasterByName(c->argv[i]->ptr);
2801                 if (!ri) continue; /* ignore non-existing names */
2802                 dictAdd(masters_local, ri->name, ri);
2803             }
2804         }
2805 
2806         /* Reply format:
2807          *   1.) master name
2808          *   2.) 1.) info from master
2809          *       2.) info from replica
2810          *       ...
2811          *   3.) other master name
2812          *   ...
2813          */
2814         addReplyMultiBulkLen(c,dictSize(masters_local) * 2);
2815 
2816         dictIterator  *di;
2817         dictEntry *de;
2818         di = dictGetIterator(masters_local);
2819         while ((de = dictNext(di)) != NULL) {
2820             sentinelRedisInstance *ri = dictGetVal(de);
2821             addReplyBulkCBuffer(c,ri->name,strlen(ri->name));
2822             addReplyMultiBulkLen(c,dictSize(ri->slaves) + 1); /* +1 for self */
2823             addReplyMultiBulkLen(c,2);
2824             addReplyLongLong(c, now - ri->info_refresh);
2825             if (ri->info)
2826                 addReplyBulkCBuffer(c,ri->info,sdslen(ri->info));
2827             else
2828                 addReply(c,shared.nullbulk);
2829 
2830             dictIterator *sdi;
2831             dictEntry *sde;
2832             sdi = dictGetIterator(ri->slaves);
2833             while ((sde = dictNext(sdi)) != NULL) {
2834                 sentinelRedisInstance *sri = dictGetVal(sde);
2835                 addReplyMultiBulkLen(c,2);
2836                 addReplyLongLong(c, now - sri->info_refresh);
2837                 if (sri->info)
2838                     addReplyBulkCBuffer(c,sri->info,sdslen(sri->info));
2839                 else
2840                     addReply(c,shared.nullbulk);
2841             }
2842             dictReleaseIterator(sdi);
2843         }
2844         dictReleaseIterator(di);
2845         if (masters_local != sentinel.masters) dictRelease(masters_local);
2846     } else {
2847         addReplyErrorFormat(c,"Unknown sentinel subcommand '%s'",
2848                                (char*)c->argv[1]->ptr);
2849     }
2850     return;
2851 
2852 numargserr:
2853     addReplyErrorFormat(c,"Wrong number of arguments for 'sentinel %s'",
2854                           (char*)c->argv[1]->ptr);
2855 }
2856 
2857 /* SENTINEL INFO [section] */
2858 void sentinelInfoCommand(redisClient *c) {
2859     char *section = c->argc == 2 ? c->argv[1]->ptr : "default";
2860     sds info = sdsempty();
2861     int defsections = !strcasecmp(section,"default");
2862     int sections = 0;
2863 
2864     if (c->argc > 2) {
2865         addReply(c,shared.syntaxerr);
2866         return;
2867     }
2868 
2869     if (!strcasecmp(section,"server") || defsections) {
2870         if (sections++) info = sdscat(info,"\r\n");
2871         sds serversection = genRedisInfoString("server");
2872         info = sdscatlen(info,serversection,sdslen(serversection));
2873         sdsfree(serversection);
2874     }
2875 
2876     if (!strcasecmp(section,"sentinel") || defsections) {
2877         dictIterator *di;
2878         dictEntry *de;
2879         int master_id = 0;
2880 
2881         if (sections++) info = sdscat(info,"\r\n");
2882         info = sdscatprintf(info,
2883             "# Sentinel\r\n"
2884             "sentinel_masters:%lu\r\n"
2885             "sentinel_tilt:%d\r\n"
2886             "sentinel_running_scripts:%d\r\n"
2887             "sentinel_scripts_queue_length:%ld\r\n",
2888             dictSize(sentinel.masters),
2889             sentinel.tilt,
2890             sentinel.running_scripts,
2891             listLength(sentinel.scripts_queue));
2892 
2893         di = dictGetIterator(sentinel.masters);
2894         while((de = dictNext(di)) != NULL) {
2895             sentinelRedisInstance *ri = dictGetVal(de);
2896             char *status = "ok";
2897 
2898             if (ri->flags & SRI_O_DOWN) status = "odown";
2899             else if (ri->flags & SRI_S_DOWN) status = "sdown";
2900             info = sdscatprintf(info,
2901                 "master%d:name=%s,status=%s,address=%s:%d,"
2902                 "slaves=%lu,sentinels=%lu\r\n",
2903                 master_id++, ri->name, status,
2904                 ri->addr->ip, ri->addr->port,
2905                 dictSize(ri->slaves),
2906                 dictSize(ri->sentinels)+1);
2907         }
2908         dictReleaseIterator(di);
2909     }
2910 
2911     addReplyBulkSds(c, info);
2912 }
2913 
2914 /* Implements Sentinel verison of the ROLE command. The output is
2915  * "sentinel" and the list of currently monitored master names. */
2916 void sentinelRoleCommand(redisClient *c) {
2917     dictIterator *di;
2918     dictEntry *de;
2919 
2920     addReplyMultiBulkLen(c,2);
2921     addReplyBulkCBuffer(c,"sentinel",8);
2922     addReplyMultiBulkLen(c,dictSize(sentinel.masters));
2923 
2924     di = dictGetIterator(sentinel.masters);
2925     while((de = dictNext(di)) != NULL) {
2926         sentinelRedisInstance *ri = dictGetVal(de);
2927 
2928         addReplyBulkCString(c,ri->name);
2929     }
2930     dictReleaseIterator(di);
2931 }
2932 
2933 /* SENTINEL SET <mastername> [<option> <value> ...] */
2934 void sentinelSetCommand(redisClient *c) {
2935     sentinelRedisInstance *ri;
2936     int j, changes = 0;
2937     char *option, *value;
2938 
2939     if ((ri = sentinelGetMasterByNameOrReplyError(c,c->argv[2]))
2940         == NULL) return;
2941 
2942     /* Process option - value pairs. */
2943     for (j = 3; j < c->argc; j += 2) {
2944         option = c->argv[j]->ptr;
2945         value = c->argv[j+1]->ptr;
2946         robj *o = c->argv[j+1];
2947         long long ll;
2948 
2949         if (!strcasecmp(option,"down-after-milliseconds")) {
2950             /* down-after-millisecodns <milliseconds> */
2951             if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll <= 0)
2952                 goto badfmt;
2953             ri->down_after_period = ll;
2954             sentinelPropagateDownAfterPeriod(ri);
2955             changes++;
2956         } else if (!strcasecmp(option,"failover-timeout")) {
2957             /* failover-timeout <milliseconds> */
2958             if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll <= 0)
2959                 goto badfmt;
2960             ri->failover_timeout = ll;
2961             changes++;
2962        } else if (!strcasecmp(option,"parallel-syncs")) {
2963             /* parallel-syncs <milliseconds> */
2964             if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll <= 0)
2965                 goto badfmt;
2966             ri->parallel_syncs = ll;
2967             changes++;
2968        } else if (!strcasecmp(option,"notification-script")) {
2969             /* notification-script <path> */
2970             if (strlen(value) && access(value,X_OK) == -1) {
2971                 addReplyError(c,
2972                     "Notification script seems non existing or non executable");
2973                 if (changes) sentinelFlushConfig();
2974                 return;
2975             }
2976             sdsfree(ri->notification_script);
2977             ri->notification_script = strlen(value) ? sdsnew(value) : NULL;
2978             changes++;
2979        } else if (!strcasecmp(option,"client-reconfig-script")) {
2980             /* client-reconfig-script <path> */
2981             if (strlen(value) && access(value,X_OK) == -1) {
2982                 addReplyError(c,
2983                     "Client reconfiguration script seems non existing or "
2984                     "non executable");
2985                 if (changes) sentinelFlushConfig();
2986                 return;
2987             }
2988             sdsfree(ri->client_reconfig_script);
2989             ri->client_reconfig_script = strlen(value) ? sdsnew(value) : NULL;
2990             changes++;
2991        } else if (!strcasecmp(option,"auth-pass")) {
2992             /* auth-pass <password> */
2993             sdsfree(ri->auth_pass);
2994             ri->auth_pass = strlen(value) ? sdsnew(value) : NULL;
2995             changes++;
2996        } else if (!strcasecmp(option,"quorum")) {
2997             /* quorum <count> */
2998             if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll <= 0)
2999                 goto badfmt;
3000             ri->quorum = ll;
3001             changes++;
3002         } else {
3003             addReplyErrorFormat(c,"Unknown option '%s' for SENTINEL SET",
3004                 option);
3005             if (changes) sentinelFlushConfig();
3006             return;
3007         }
3008         sentinelEvent(REDIS_WARNING,"+set",ri,"%@ %s %s",option,value);
3009     }
3010 
3011     if (changes) sentinelFlushConfig();
3012     addReply(c,shared.ok);
3013     return;
3014 
3015 badfmt: /* Bad format errors */
3016     if (changes) sentinelFlushConfig();
3017     addReplyErrorFormat(c,"Invalid argument '%s' for SENTINEL SET '%s'",
3018             value, option);
3019 }
3020 
3021 /* Our fake PUBLISH command: it is actually useful only to receive hello messages
3022  * from the other sentinel instances, and publishing to a channel other than
3023  * SENTINEL_HELLO_CHANNEL is forbidden.
3024  *
3025  * Because we have a Sentinel PUBLISH, the code to send hello messages is the same
3026  * for all the three kind of instances: masters, slaves, sentinels. */
3027 void sentinelPublishCommand(redisClient *c) {
3028     if (strcmp(c->argv[1]->ptr,SENTINEL_HELLO_CHANNEL)) {
3029         addReplyError(c, "Only HELLO messages are accepted by Sentinel instances.");
3030         return;
3031     }
3032     sentinelProcessHelloMessage(c->argv[2]->ptr,sdslen(c->argv[2]->ptr));
3033     addReplyLongLong(c,1);
3034 }
3035 
3036 /* ===================== SENTINEL availability checks ======================= */
3037 
3038 /* Is this instance down from our point of view? */
3039 void sentinelCheckSubjectivelyDown(sentinelRedisInstance *ri) {
3040     mstime_t elapsed = 0;
3041 
3042     if (ri->last_ping_time)
3043         elapsed = mstime() - ri->last_ping_time;
3044 
3045     /* Check if we are in need for a reconnection of one of the
3046      * links, because we are detecting low activity.
3047      *
3048      * 1) Check if the command link seems connected, was connected not less
3049      *    than SENTINEL_MIN_LINK_RECONNECT_PERIOD, but still we have a
3050      *    pending ping for more than half the timeout. */
3051     if (ri->cc &&
3052         (mstime() - ri->cc_conn_time) > SENTINEL_MIN_LINK_RECONNECT_PERIOD &&
3053         ri->last_ping_time != 0 && /* Ther is a pending ping... */
3054         /* The pending ping is delayed, and we did not received
3055          * error replies as well. */
3056         (mstime() - ri->last_ping_time) > (ri->down_after_period/2) &&
3057         (mstime() - ri->last_pong_time) > (ri->down_after_period/2))
3058     {
3059         sentinelKillLink(ri,ri->cc);
3060     }
3061 
3062     /* 2) Check if the pubsub link seems connected, was connected not less
3063      *    than SENTINEL_MIN_LINK_RECONNECT_PERIOD, but still we have no
3064      *    activity in the Pub/Sub channel for more than
3065      *    SENTINEL_PUBLISH_PERIOD * 3.
3066      */
3067     if (ri->pc &&
3068         (mstime() - ri->pc_conn_time) > SENTINEL_MIN_LINK_RECONNECT_PERIOD &&
3069         (mstime() - ri->pc_last_activity) > (SENTINEL_PUBLISH_PERIOD*3))
3070     {
3071         sentinelKillLink(ri,ri->pc);
3072     }
3073 
3074     /* Update the SDOWN flag. We believe the instance is SDOWN if:
3075      *
3076      * 1) It is not replying.
3077      * 2) We believe it is a master, it reports to be a slave for enough time
3078      *    to meet the down_after_period, plus enough time to get two times
3079      *    INFO report from the instance. */
3080     if (elapsed > ri->down_after_period ||
3081         (ri->flags & SRI_MASTER &&
3082          ri->role_reported == SRI_SLAVE &&
3083          mstime() - ri->role_reported_time >
3084           (ri->down_after_period+SENTINEL_INFO_PERIOD*2)))
3085     {
3086         /* Is subjectively down */
3087         if ((ri->flags & SRI_S_DOWN) == 0) {
3088             sentinelEvent(REDIS_WARNING,"+sdown",ri,"%@");
3089             ri->s_down_since_time = mstime();
3090             ri->flags |= SRI_S_DOWN;
3091         }
3092     } else {
3093         /* Is subjectively up */
3094         if (ri->flags & SRI_S_DOWN) {
3095             sentinelEvent(REDIS_WARNING,"-sdown",ri,"%@");
3096             ri->flags &= ~(SRI_S_DOWN|SRI_SCRIPT_KILL_SENT);
3097         }
3098     }
3099 }
3100 
3101 /* Is this instance down according to the configured quorum?
3102  *
3103  * Note that ODOWN is a weak quorum, it only means that enough Sentinels
3104  * reported in a given time range that the instance was not reachable.
3105  * However messages can be delayed so there are no strong guarantees about
3106  * N instances agreeing at the same time about the down state. */
3107 void sentinelCheckObjectivelyDown(sentinelRedisInstance *master) {
3108     dictIterator *di;
3109     dictEntry *de;
3110     unsigned int quorum = 0, odown = 0;
3111 
3112     if (master->flags & SRI_S_DOWN) {
3113         /* Is down for enough sentinels? */
3114         quorum = 1; /* the current sentinel. */
3115         /* Count all the other sentinels. */
3116         di = dictGetIterator(master->sentinels);
3117         while((de = dictNext(di)) != NULL) {
3118             sentinelRedisInstance *ri = dictGetVal(de);
3119 
3120             if (ri->flags & SRI_MASTER_DOWN) quorum++;
3121         }
3122         dictReleaseIterator(di);
3123         if (quorum >= master->quorum) odown = 1;
3124     }
3125 
3126     /* Set the flag accordingly to the outcome. */
3127     if (odown) {
3128         if ((master->flags & SRI_O_DOWN) == 0) {
3129             sentinelEvent(REDIS_WARNING,"+odown",master,"%@ #quorum %d/%d",
3130                 quorum, master->quorum);
3131             master->flags |= SRI_O_DOWN;
3132             master->o_down_since_time = mstime();
3133         }
3134     } else {
3135         if (master->flags & SRI_O_DOWN) {
3136             sentinelEvent(REDIS_WARNING,"-odown",master,"%@");
3137             master->flags &= ~SRI_O_DOWN;
3138         }
3139     }
3140 }
3141 
3142 /* Receive the SENTINEL is-master-down-by-addr reply, see the
3143  * sentinelAskMasterStateToOtherSentinels() function for more information. */
3144 void sentinelReceiveIsMasterDownReply(redisAsyncContext *c, void *reply, void *privdata) {
3145     sentinelRedisInstance *ri = c->data;
3146     redisReply *r;
3147     REDIS_NOTUSED(privdata);
3148 
3149     if (ri) ri->pending_commands--;
3150     if (!reply || !ri) return;
3151     r = reply;
3152 
3153     /* Ignore every error or unexpected reply.
3154      * Note that if the command returns an error for any reason we'll
3155      * end clearing the SRI_MASTER_DOWN flag for timeout anyway. */
3156     if (r->type == REDIS_REPLY_ARRAY && r->elements == 3 &&
3157         r->element[0]->type == REDIS_REPLY_INTEGER &&
3158         r->element[1]->type == REDIS_REPLY_STRING &&
3159         r->element[2]->type == REDIS_REPLY_INTEGER)
3160     {
3161         ri->last_master_down_reply_time = mstime();
3162         if (r->element[0]->integer == 1) {
3163             ri->flags |= SRI_MASTER_DOWN;
3164         } else {
3165             ri->flags &= ~SRI_MASTER_DOWN;
3166         }
3167         if (strcmp(r->element[1]->str,"*")) {
3168             /* If the runid in the reply is not "*" the Sentinel actually
3169              * replied with a vote. */
3170             sdsfree(ri->leader);
3171             if ((long long)ri->leader_epoch != r->element[2]->integer)
3172                 redisLog(REDIS_WARNING,
3173                     "%s voted for %s %llu", ri->name,
3174                     r->element[1]->str,
3175                     (unsigned long long) r->element[2]->integer);
3176             ri->leader = sdsnew(r->element[1]->str);
3177             ri->leader_epoch = r->element[2]->integer;
3178         }
3179     }
3180 }
3181 
3182 /* If we think the master is down, we start sending
3183  * SENTINEL IS-MASTER-DOWN-BY-ADDR requests to other sentinels
3184  * in order to get the replies that allow to reach the quorum
3185  * needed to mark the master in ODOWN state and trigger a failover. */
3186 #define SENTINEL_ASK_FORCED (1<<0)
3187 void sentinelAskMasterStateToOtherSentinels(sentinelRedisInstance *master, int flags) {
3188     dictIterator *di;
3189     dictEntry *de;
3190 
3191     di = dictGetIterator(master->sentinels);
3192     while((de = dictNext(di)) != NULL) {
3193         sentinelRedisInstance *ri = dictGetVal(de);
3194         mstime_t elapsed = mstime() - ri->last_master_down_reply_time;
3195         char port[32];
3196         int retval;
3197 
3198         /* If the master state from other sentinel is too old, we clear it. */
3199         if (elapsed > SENTINEL_ASK_PERIOD*5) {
3200             ri->flags &= ~SRI_MASTER_DOWN;
3201             sdsfree(ri->leader);
3202             ri->leader = NULL;
3203         }
3204 
3205         /* Only ask if master is down to other sentinels if:
3206          *
3207          * 1) We believe it is down, or there is a failover in progress.
3208          * 2) Sentinel is connected.
3209          * 3) We did not received the info within SENTINEL_ASK_PERIOD ms. */
3210         if ((master->flags & SRI_S_DOWN) == 0) continue;
3211         if (ri->flags & SRI_DISCONNECTED) continue;
3212         if (!(flags & SENTINEL_ASK_FORCED) &&
3213             mstime() - ri->last_master_down_reply_time < SENTINEL_ASK_PERIOD)
3214             continue;
3215 
3216         /* Ask */
3217         ll2string(port,sizeof(port),master->addr->port);
3218         retval = redisAsyncCommand(ri->cc,
3219                     sentinelReceiveIsMasterDownReply, NULL,
3220                     "SENTINEL is-master-down-by-addr %s %s %llu %s",
3221                     master->addr->ip, port,
3222                     sentinel.current_epoch,
3223                     (master->failover_state > SENTINEL_FAILOVER_STATE_NONE) ?
3224                     server.runid : "*");
3225         if (retval == REDIS_OK) ri->pending_commands++;
3226     }
3227     dictReleaseIterator(di);
3228 }
3229 
3230 /* =============================== FAILOVER ================================= */
3231 
3232 /* Vote for the sentinel with 'req_runid' or return the old vote if already
3233  * voted for the specifed 'req_epoch' or one greater.
3234  *
3235  * If a vote is not available returns NULL, otherwise return the Sentinel
3236  * runid and populate the leader_epoch with the epoch of the vote. */
3237 char *sentinelVoteLeader(sentinelRedisInstance *master, uint64_t req_epoch, char *req_runid, uint64_t *leader_epoch) {
3238     if (req_epoch > sentinel.current_epoch) {
3239         sentinel.current_epoch = req_epoch;
3240         sentinelFlushConfig();
3241         sentinelEvent(REDIS_WARNING,"+new-epoch",master,"%llu",
3242             (unsigned long long) sentinel.current_epoch);
3243     }
3244 
3245     if (master->leader_epoch < req_epoch && sentinel.current_epoch <= req_epoch)
3246     {
3247         sdsfree(master->leader);
3248         master->leader = sdsnew(req_runid);
3249         master->leader_epoch = sentinel.current_epoch;
3250         sentinelFlushConfig();
3251         sentinelEvent(REDIS_WARNING,"+vote-for-leader",master,"%s %llu",
3252             master->leader, (unsigned long long) master->leader_epoch);
3253         /* If we did not voted for ourselves, set the master failover start
3254          * time to now, in order to force a delay before we can start a
3255          * failover for the same master. */
3256         if (strcasecmp(master->leader,server.runid))
3257             master->failover_start_time = mstime()+rand()%SENTINEL_MAX_DESYNC;
3258     }
3259 
3260     *leader_epoch = master->leader_epoch;
3261     return master->leader ? sdsnew(master->leader) : NULL;
3262 }
3263 
3264 struct sentinelLeader {
3265     char *runid;
3266     unsigned long votes;
3267 };
3268 
3269 /* Helper function for sentinelGetLeader, increment the counter
3270  * relative to the specified runid. */
3271 int sentinelLeaderIncr(dict *counters, char *runid) {
3272     dictEntry *de = dictFind(counters,runid);
3273     uint64_t oldval;
3274 
3275     if (de) {
3276         oldval = dictGetUnsignedIntegerVal(de);
3277         dictSetUnsignedIntegerVal(de,oldval+1);
3278         return oldval+1;
3279     } else {
3280         de = dictAddRaw(counters,runid);
3281         redisAssert(de != NULL);
3282         dictSetUnsignedIntegerVal(de,1);
3283         return 1;
3284     }
3285 }
3286 
3287 /* Scan all the Sentinels attached to this master to check if there
3288  * is a leader for the specified epoch.
3289  *
3290  * To be a leader for a given epoch, we should have the majority of
3291  * the Sentinels we know (ever seen since the last SENTINEL RESET) that
3292  * reported the same instance as leader for the same epoch. */
3293 char *sentinelGetLeader(sentinelRedisInstance *master, uint64_t epoch) {
3294     dict *counters;
3295     dictIterator *di;
3296     dictEntry *de;
3297     unsigned int voters = 0, voters_quorum;
3298     char *myvote;
3299     char *winner = NULL;
3300     uint64_t leader_epoch;
3301     uint64_t max_votes = 0;
3302 
3303     redisAssert(master->flags & (SRI_O_DOWN|SRI_FAILOVER_IN_PROGRESS));
3304     counters = dictCreate(&leaderVotesDictType,NULL);
3305 
3306     voters = dictSize(master->sentinels)+1; /* All the other sentinels and me. */
3307 
3308     /* Count other sentinels votes */
3309     di = dictGetIterator(master->sentinels);
3310     while((de = dictNext(di)) != NULL) {
3311         sentinelRedisInstance *ri = dictGetVal(de);
3312         if (ri->leader != NULL && ri->leader_epoch == sentinel.current_epoch)
3313             sentinelLeaderIncr(counters,ri->leader);
3314     }
3315     dictReleaseIterator(di);
3316 
3317     /* Check what's the winner. For the winner to win, it needs two conditions:
3318      * 1) Absolute majority between voters (50% + 1).
3319      * 2) And anyway at least master->quorum votes. */
3320     di = dictGetIterator(counters);
3321     while((de = dictNext(di)) != NULL) {
3322         uint64_t votes = dictGetUnsignedIntegerVal(de);
3323 
3324         if (votes > max_votes) {
3325             max_votes = votes;
3326             winner = dictGetKey(de);
3327         }
3328     }
3329     dictReleaseIterator(di);
3330 
3331     /* Count this Sentinel vote:
3332      * if this Sentinel did not voted yet, either vote for the most
3333      * common voted sentinel, or for itself if no vote exists at all. */
3334     if (winner)
3335         myvote = sentinelVoteLeader(master,epoch,winner,&leader_epoch);
3336     else
3337         myvote = sentinelVoteLeader(master,epoch,server.runid,&leader_epoch);
3338 
3339     if (myvote && leader_epoch == epoch) {
3340         uint64_t votes = sentinelLeaderIncr(counters,myvote);
3341 
3342         if (votes > max_votes) {
3343             max_votes = votes;
3344             winner = myvote;
3345         }
3346     }
3347 
3348     voters_quorum = voters/2+1;
3349     if (winner && (max_votes < voters_quorum || max_votes < master->quorum))
3350         winner = NULL;
3351 
3352     winner = winner ? sdsnew(winner) : NULL;
3353     sdsfree(myvote);
3354     dictRelease(counters);
3355     return winner;
3356 }
3357 
3358 /* Send SLAVEOF to the specified instance, always followed by a
3359  * CONFIG REWRITE command in order to store the new configuration on disk
3360  * when possible (that is, if the Redis instance is recent enough to support
3361  * config rewriting, and if the server was started with a configuration file).
3362  *
3363  * If Host is NULL the function sends "SLAVEOF NO ONE".
3364  *
3365  * The command returns REDIS_OK if the SLAVEOF command was accepted for
3366  * (later) delivery otherwise REDIS_ERR. The command replies are just
3367  * discarded. */
3368 int sentinelSendSlaveOf(sentinelRedisInstance *ri, char *host, int port) {
3369     char portstr[32];
3370     int retval;
3371 
3372     ll2string(portstr,sizeof(portstr),port);
3373 
3374     /* If host is NULL we send SLAVEOF NO ONE that will turn the instance
3375      * into a master. */
3376     if (host == NULL) {
3377         host = "NO";
3378         memcpy(portstr,"ONE",4);
3379     }
3380 
3381     /* In order to send SLAVEOF in a safe way, we send a transaction performing
3382      * the following tasks:
3383      * 1) Reconfigure the instance according to the specified host/port params.
3384      * 2) Rewrite the configuraiton.
3385      * 3) Disconnect all clients (but this one sending the commnad) in order
3386      *    to trigger the ask-master-on-reconnection protocol for connected
3387      *    clients.
3388      *
3389      * Note that we don't check the replies returned by commands, since we
3390      * will observe instead the effects in the next INFO output. */
3391     retval = redisAsyncCommand(ri->cc,
3392         sentinelDiscardReplyCallback, NULL, "MULTI");
3393     if (retval == REDIS_ERR) return retval;
3394     ri->pending_commands++;
3395 
3396     retval = redisAsyncCommand(ri->cc,
3397         sentinelDiscardReplyCallback, NULL, "SLAVEOF %s %s", host, portstr);
3398     if (retval == REDIS_ERR) return retval;
3399     ri->pending_commands++;
3400 
3401     retval = redisAsyncCommand(ri->cc,
3402         sentinelDiscardReplyCallback, NULL, "CONFIG REWRITE");
3403     if (retval == REDIS_ERR) return retval;
3404     ri->pending_commands++;
3405 
3406     /* CLIENT KILL TYPE <type> is only supported starting from Redis 2.8.12,
3407      * however sending it to an instance not understanding this command is not
3408      * an issue because CLIENT is variadic command, so Redis will not
3409      * recognized as a syntax error, and the transaction will not fail (but
3410      * only the unsupported command will fail). */
3411     retval = redisAsyncCommand(ri->cc,
3412         sentinelDiscardReplyCallback, NULL, "CLIENT KILL TYPE normal");
3413     if (retval == REDIS_ERR) return retval;
3414     ri->pending_commands++;
3415 
3416     retval = redisAsyncCommand(ri->cc,
3417         sentinelDiscardReplyCallback, NULL, "EXEC");
3418     if (retval == REDIS_ERR) return retval;
3419     ri->pending_commands++;
3420 
3421     return REDIS_OK;
3422 }
3423 
3424 /* Setup the master state to start a failover. */
3425 void sentinelStartFailover(sentinelRedisInstance *master) {
3426     redisAssert(master->flags & SRI_MASTER);
3427 
3428     master->failover_state = SENTINEL_FAILOVER_STATE_WAIT_START;
3429     master->flags |= SRI_FAILOVER_IN_PROGRESS;
3430     master->failover_epoch = ++sentinel.current_epoch;
3431     sentinelEvent(REDIS_WARNING,"+new-epoch",master,"%llu",
3432         (unsigned long long) sentinel.current_epoch);
3433     sentinelEvent(REDIS_WARNING,"+try-failover",master,"%@");
3434     master->failover_start_time = mstime()+rand()%SENTINEL_MAX_DESYNC;
3435     master->failover_state_change_time = mstime();
3436 }
3437 
3438 /* This function checks if there are the conditions to start the failover,
3439  * that is:
3440  *
3441  * 1) Master must be in ODOWN condition.
3442  * 2) No failover already in progress.
3443  * 3) No failover already attempted recently.
3444  *
3445  * We still don't know if we'll win the election so it is possible that we
3446  * start the failover but that we'll not be able to act.
3447  *
3448  * Return non-zero if a failover was started. */
3449 int sentinelStartFailoverIfNeeded(sentinelRedisInstance *master) {
3450     /* We can't failover if the master is not in O_DOWN state. */
3451     if (!(master->flags & SRI_O_DOWN)) return 0;
3452 
3453     /* Failover already in progress? */
3454     if (master->flags & SRI_FAILOVER_IN_PROGRESS) return 0;
3455 
3456     /* Last failover attempt started too little time ago? */
3457     if (mstime() - master->failover_start_time <
3458         master->failover_timeout*2)
3459     {
3460         if (master->failover_delay_logged != master->failover_start_time) {
3461             time_t clock = (master->failover_start_time +
3462                             master->failover_timeout*2) / 1000;
3463             char ctimebuf[26];
3464 
3465             ctime_r(&clock,ctimebuf);
3466             ctimebuf[24] = '\0'; /* Remove newline. */
3467             master->failover_delay_logged = master->failover_start_time;
3468             redisLog(REDIS_WARNING,
3469                 "Next failover delay: I will not start a failover before %s",
3470                 ctimebuf);
3471         }
3472         return 0;
3473     }
3474 
3475     sentinelStartFailover(master);
3476     return 1;
3477 }
3478 
3479 /* Select a suitable slave to promote. The current algorithm only uses
3480  * the following parameters:
3481  *
3482  * 1) None of the following conditions: S_DOWN, O_DOWN, DISCONNECTED.
3483  * 2) Last time the slave replied to ping no more than 5 times the PING period.
3484  * 3) info_refresh not older than 3 times the INFO refresh period.
3485  * 4) master_link_down_time no more than:
3486  *     (now - master->s_down_since_time) + (master->down_after_period * 10).
3487  *    Basically since the master is down from our POV, the slave reports
3488  *    to be disconnected no more than 10 times the configured down-after-period.
3489  *    This is pretty much black magic but the idea is, the master was not
3490  *    available so the slave may be lagging, but not over a certain time.
3491  *    Anyway we'll select the best slave according to replication offset.
3492  * 5) Slave priority can't be zero, otherwise the slave is discarded.
3493  *
3494  * Among all the slaves matching the above conditions we select the slave
3495  * with, in order of sorting key:
3496  *
3497  * - lower slave_priority.
3498  * - bigger processed replication offset.
3499  * - lexicographically smaller runid.
3500  *
3501  * Basically if runid is the same, the slave that processed more commands
3502  * from the master is selected.
3503  *
3504  * The function returns the pointer to the selected slave, otherwise
3505  * NULL if no suitable slave was found.
3506  */
3507 
3508 /* Helper for sentinelSelectSlave(). This is used by qsort() in order to
3509  * sort suitable slaves in a "better first" order, to take the first of
3510  * the list. */
3511 int compareSlavesForPromotion(const void *a, const void *b) {
3512     sentinelRedisInstance **sa = (sentinelRedisInstance **)a,
3513                           **sb = (sentinelRedisInstance **)b;
3514     char *sa_runid, *sb_runid;
3515 
3516     if ((*sa)->slave_priority != (*sb)->slave_priority)
3517         return (*sa)->slave_priority - (*sb)->slave_priority;
3518 
3519     /* If priority is the same, select the slave with greater replication
3520      * offset (processed more data frmo the master). */
3521     if ((*sa)->slave_repl_offset > (*sb)->slave_repl_offset) {
3522         return -1; /* a < b */
3523     } else if ((*sa)->slave_repl_offset < (*sb)->slave_repl_offset) {
3524         return 1; /* b > a */
3525     }
3526 
3527     /* If the replication offset is the same select the slave with that has
3528      * the lexicographically smaller runid. Note that we try to handle runid
3529      * == NULL as there are old Redis versions that don't publish runid in
3530      * INFO. A NULL runid is considered bigger than any other runid. */
3531     sa_runid = (*sa)->runid;
3532     sb_runid = (*sb)->runid;
3533     if (sa_runid == NULL && sb_runid == NULL) return 0;
3534     else if (sa_runid == NULL) return 1;  /* a > b */
3535     else if (sb_runid == NULL) return -1; /* a < b */
3536     return strcasecmp(sa_runid, sb_runid);
3537 }
3538 
3539 sentinelRedisInstance *sentinelSelectSlave(sentinelRedisInstance *master) {
3540     sentinelRedisInstance **instance =
3541         zmalloc(sizeof(instance[0])*dictSize(master->slaves));
3542     sentinelRedisInstance *selected = NULL;
3543     int instances = 0;
3544     dictIterator *di;
3545     dictEntry *de;
3546     mstime_t max_master_down_time = 0;
3547 
3548     if (master->flags & SRI_S_DOWN)
3549         max_master_down_time += mstime() - master->s_down_since_time;
3550     max_master_down_time += master->down_after_period * 10;
3551 
3552     di = dictGetIterator(master->slaves);
3553     while((de = dictNext(di)) != NULL) {
3554         sentinelRedisInstance *slave = dictGetVal(de);
3555         mstime_t info_validity_time;
3556 
3557         if (slave->flags & (SRI_S_DOWN|SRI_O_DOWN|SRI_DISCONNECTED)) continue;
3558         if (mstime() - slave->last_avail_time > SENTINEL_PING_PERIOD*5) continue;
3559         if (slave->slave_priority == 0) continue;
3560 
3561         /* If the master is in SDOWN state we get INFO for slaves every second.
3562          * Otherwise we get it with the usual period so we need to account for
3563          * a larger delay. */
3564         if (master->flags & SRI_S_DOWN)
3565             info_validity_time = SENTINEL_PING_PERIOD*5;
3566         else
3567             info_validity_time = SENTINEL_INFO_PERIOD*3;
3568         if (mstime() - slave->info_refresh > info_validity_time) continue;
3569         if (slave->master_link_down_time > max_master_down_time) continue;
3570         instance[instances++] = slave;
3571     }
3572     dictReleaseIterator(di);
3573     if (instances) {
3574         qsort(instance,instances,sizeof(sentinelRedisInstance*),
3575             compareSlavesForPromotion);
3576         selected = instance[0];
3577     }
3578     zfree(instance);
3579     return selected;
3580 }
3581 
3582 /* ---------------- Failover state machine implementation ------------------- */
3583 void sentinelFailoverWaitStart(sentinelRedisInstance *ri) {
3584     char *leader;
3585     int isleader;
3586 
3587     /* Check if we are the leader for the failover epoch. */
3588     leader = sentinelGetLeader(ri, ri->failover_epoch);
3589     isleader = leader && strcasecmp(leader,server.runid) == 0;
3590     sdsfree(leader);
3591 
3592     /* If I'm not the leader, and it is not a forced failover via
3593      * SENTINEL FAILOVER, then I can't continue with the failover. */
3594     if (!isleader && !(ri->flags & SRI_FORCE_FAILOVER)) {
3595         int election_timeout = SENTINEL_ELECTION_TIMEOUT;
3596 
3597         /* The election timeout is the MIN between SENTINEL_ELECTION_TIMEOUT
3598          * and the configured failover timeout. */
3599         if (election_timeout > ri->failover_timeout)
3600             election_timeout = ri->failover_timeout;
3601         /* Abort the failover if I'm not the leader after some time. */
3602         if (mstime() - ri->failover_start_time > election_timeout) {
3603             sentinelEvent(REDIS_WARNING,"-failover-abort-not-elected",ri,"%@");
3604             sentinelAbortFailover(ri);
3605         }
3606         return;
3607     }
3608     sentinelEvent(REDIS_WARNING,"+elected-leader",ri,"%@");
3609     ri->failover_state = SENTINEL_FAILOVER_STATE_SELECT_SLAVE;
3610     ri->failover_state_change_time = mstime();
3611     sentinelEvent(REDIS_WARNING,"+failover-state-select-slave",ri,"%@");
3612 }
3613 
3614 void sentinelFailoverSelectSlave(sentinelRedisInstance *ri) {
3615     sentinelRedisInstance *slave = sentinelSelectSlave(ri);
3616 
3617     /* We don't handle the timeout in this state as the function aborts
3618      * the failover or go forward in the next state. */
3619     if (slave == NULL) {
3620         sentinelEvent(REDIS_WARNING,"-failover-abort-no-good-slave",ri,"%@");
3621         sentinelAbortFailover(ri);
3622     } else {
3623         sentinelEvent(REDIS_WARNING,"+selected-slave",slave,"%@");
3624         slave->flags |= SRI_PROMOTED;
3625         ri->promoted_slave = slave;
3626         ri->failover_state = SENTINEL_FAILOVER_STATE_SEND_SLAVEOF_NOONE;
3627         ri->failover_state_change_time = mstime();
3628         sentinelEvent(REDIS_NOTICE,"+failover-state-send-slaveof-noone",
3629             slave, "%@");
3630     }
3631 }
3632 
3633 void sentinelFailoverSendSlaveOfNoOne(sentinelRedisInstance *ri) {
3634     int retval;
3635 
3636     /* We can't send the command to the promoted slave if it is now
3637      * disconnected. Retry again and again with this state until the timeout
3638      * is reached, then abort the failover. */
3639     if (ri->promoted_slave->flags & SRI_DISCONNECTED) {
3640         if (mstime() - ri->failover_state_change_time > ri->failover_timeout) {
3641             sentinelEvent(REDIS_WARNING,"-failover-abort-slave-timeout",ri,"%@");
3642             sentinelAbortFailover(ri);
3643         }
3644         return;
3645     }
3646 
3647     /* Send SLAVEOF NO ONE command to turn the slave into a master.
3648      * We actually register a generic callback for this command as we don't
3649      * really care about the reply. We check if it worked indirectly observing
3650      * if INFO returns a different role (master instead of slave). */
3651     retval = sentinelSendSlaveOf(ri->promoted_slave,NULL,0);
3652     if (retval != REDIS_OK) return;
3653     sentinelEvent(REDIS_NOTICE, "+failover-state-wait-promotion",
3654         ri->promoted_slave,"%@");
3655     ri->failover_state = SENTINEL_FAILOVER_STATE_WAIT_PROMOTION;
3656     ri->failover_state_change_time = mstime();
3657 }
3658 
3659 /* We actually wait for promotion indirectly checking with INFO when the
3660  * slave turns into a master. */
3661 void sentinelFailoverWaitPromotion(sentinelRedisInstance *ri) {
3662     /* Just handle the timeout. Switching to the next state is handled
3663      * by the function parsing the INFO command of the promoted slave. */
3664     if (mstime() - ri->failover_state_change_time > ri->failover_timeout) {
3665         sentinelEvent(REDIS_WARNING,"-failover-abort-slave-timeout",ri,"%@");
3666         sentinelAbortFailover(ri);
3667     }
3668 }
3669 
3670 void sentinelFailoverDetectEnd(sentinelRedisInstance *master) {
3671     int not_reconfigured = 0, timeout = 0;
3672     dictIterator *di;
3673     dictEntry *de;
3674     mstime_t elapsed = mstime() - master->failover_state_change_time;
3675 
3676     /* We can't consider failover finished if the promoted slave is
3677      * not reachable. */
3678     if (master->promoted_slave == NULL ||
3679         master->promoted_slave->flags & SRI_S_DOWN) return;
3680 
3681     /* The failover terminates once all the reachable slaves are properly
3682      * configured. */
3683     di = dictGetIterator(master->slaves);
3684     while((de = dictNext(di)) != NULL) {
3685         sentinelRedisInstance *slave = dictGetVal(de);
3686 
3687         if (slave->flags & (SRI_PROMOTED|SRI_RECONF_DONE)) continue;
3688         if (slave->flags & SRI_S_DOWN) continue;
3689         not_reconfigured++;
3690     }
3691     dictReleaseIterator(di);
3692 
3693     /* Force end of failover on timeout. */
3694     if (elapsed > master->failover_timeout) {
3695         not_reconfigured = 0;
3696         timeout = 1;
3697         sentinelEvent(REDIS_WARNING,"+failover-end-for-timeout",master,"%@");
3698     }
3699 
3700     if (not_reconfigured == 0) {
3701         sentinelEvent(REDIS_WARNING,"+failover-end",master,"%@");
3702         master->failover_state = SENTINEL_FAILOVER_STATE_UPDATE_CONFIG;
3703         master->failover_state_change_time = mstime();
3704     }
3705 
3706     /* If I'm the leader it is a good idea to send a best effort SLAVEOF
3707      * command to all the slaves still not reconfigured to replicate with
3708      * the new master. */
3709     if (timeout) {
3710         dictIterator *di;
3711         dictEntry *de;
3712 
3713         di = dictGetIterator(master->slaves);
3714         while((de = dictNext(di)) != NULL) {
3715             sentinelRedisInstance *slave = dictGetVal(de);
3716             int retval;
3717 
3718             if (slave->flags &
3719                 (SRI_RECONF_DONE|SRI_RECONF_SENT|SRI_DISCONNECTED)) continue;
3720 
3721             retval = sentinelSendSlaveOf(slave,
3722                     master->promoted_slave->addr->ip,
3723                     master->promoted_slave->addr->port);
3724             if (retval == REDIS_OK) {
3725                 sentinelEvent(REDIS_NOTICE,"+slave-reconf-sent-be",slave,"%@");
3726                 slave->flags |= SRI_RECONF_SENT;
3727             }
3728         }
3729         dictReleaseIterator(di);
3730     }
3731 }
3732 
3733 /* Send SLAVE OF <new master address> to all the remaining slaves that
3734  * still don't appear to have the configuration updated. */
3735 void sentinelFailoverReconfNextSlave(sentinelRedisInstance *master) {
3736     dictIterator *di;
3737     dictEntry *de;
3738     int in_progress = 0;
3739 
3740     di = dictGetIterator(master->slaves);
3741     while((de = dictNext(di)) != NULL) {
3742         sentinelRedisInstance *slave = dictGetVal(de);
3743 
3744         if (slave->flags & (SRI_RECONF_SENT|SRI_RECONF_INPROG))
3745             in_progress++;
3746     }
3747     dictReleaseIterator(di);
3748 
3749     di = dictGetIterator(master->slaves);
3750     while(in_progress < master->parallel_syncs &&
3751           (de = dictNext(di)) != NULL)
3752     {
3753         sentinelRedisInstance *slave = dictGetVal(de);
3754         int retval;
3755 
3756         /* Skip the promoted slave, and already configured slaves. */
3757         if (slave->flags & (SRI_PROMOTED|SRI_RECONF_DONE)) continue;
3758 
3759         /* If too much time elapsed without the slave moving forward to
3760          * the next state, consider it reconfigured even if it is not.
3761          * Sentinels will detect the slave as misconfigured and fix its
3762          * configuration later. */
3763         if ((slave->flags & SRI_RECONF_SENT) &&
3764             (mstime() - slave->slave_reconf_sent_time) >
3765             SENTINEL_SLAVE_RECONF_TIMEOUT)
3766         {
3767             sentinelEvent(REDIS_NOTICE,"-slave-reconf-sent-timeout",slave,"%@");
3768             slave->flags &= ~SRI_RECONF_SENT;
3769             slave->flags |= SRI_RECONF_DONE;
3770         }
3771 
3772         /* Nothing to do for instances that are disconnected or already
3773          * in RECONF_SENT state. */
3774         if (slave->flags & (SRI_DISCONNECTED|SRI_RECONF_SENT|SRI_RECONF_INPROG))
3775             continue;
3776 
3777         /* Send SLAVEOF <new master>. */
3778         retval = sentinelSendSlaveOf(slave,
3779                 master->promoted_slave->addr->ip,
3780                 master->promoted_slave->addr->port);
3781         if (retval == REDIS_OK) {
3782             slave->flags |= SRI_RECONF_SENT;
3783             slave->slave_reconf_sent_time = mstime();
3784             sentinelEvent(REDIS_NOTICE,"+slave-reconf-sent",slave,"%@");
3785             in_progress++;
3786         }
3787     }
3788     dictReleaseIterator(di);
3789 
3790     /* Check if all the slaves are reconfigured and handle timeout. */
3791     sentinelFailoverDetectEnd(master);
3792 }
3793 
3794 /* This function is called when the slave is in
3795  * SENTINEL_FAILOVER_STATE_UPDATE_CONFIG state. In this state we need
3796  * to remove it from the master table and add the promoted slave instead. */
3797 void sentinelFailoverSwitchToPromotedSlave(sentinelRedisInstance *master) {
3798     sentinelRedisInstance *ref = master->promoted_slave ?
3799                                  master->promoted_slave : master;
3800 
3801     sentinelEvent(REDIS_WARNING,"+switch-master",master,"%s %s %d %s %d",
3802         master->name, master->addr->ip, master->addr->port,
3803         ref->addr->ip, ref->addr->port);
3804 
3805     sentinelResetMasterAndChangeAddress(master,ref->addr->ip,ref->addr->port);
3806 }
3807 
3808 void sentinelFailoverStateMachine(sentinelRedisInstance *ri) {
3809     redisAssert(ri->flags & SRI_MASTER);
3810 
3811     if (!(ri->flags & SRI_FAILOVER_IN_PROGRESS)) return;
3812 
3813     switch(ri->failover_state) {
3814         case SENTINEL_FAILOVER_STATE_WAIT_START:
3815             sentinelFailoverWaitStart(ri);
3816             break;
3817         case SENTINEL_FAILOVER_STATE_SELECT_SLAVE:
3818             sentinelFailoverSelectSlave(ri);
3819             break;
3820         case SENTINEL_FAILOVER_STATE_SEND_SLAVEOF_NOONE:
3821             sentinelFailoverSendSlaveOfNoOne(ri);
3822             break;
3823         case SENTINEL_FAILOVER_STATE_WAIT_PROMOTION:
3824             sentinelFailoverWaitPromotion(ri);
3825             break;
3826         case SENTINEL_FAILOVER_STATE_RECONF_SLAVES:
3827             sentinelFailoverReconfNextSlave(ri);
3828             break;
3829     }
3830 }
3831 
3832 /* Abort a failover in progress:
3833  *
3834  * This function can only be called before the promoted slave acknowledged
3835  * the slave -> master switch. Otherwise the failover can't be aborted and
3836  * will reach its end (possibly by timeout). */
3837 void sentinelAbortFailover(sentinelRedisInstance *ri) {
3838     redisAssert(ri->flags & SRI_FAILOVER_IN_PROGRESS);
3839     redisAssert(ri->failover_state <= SENTINEL_FAILOVER_STATE_WAIT_PROMOTION);
3840 
3841     ri->flags &= ~(SRI_FAILOVER_IN_PROGRESS|SRI_FORCE_FAILOVER);
3842     ri->failover_state = SENTINEL_FAILOVER_STATE_NONE;
3843     ri->failover_state_change_time = mstime();
3844     if (ri->promoted_slave) {
3845         ri->promoted_slave->flags &= ~SRI_PROMOTED;
3846         ri->promoted_slave = NULL;
3847     }
3848 }
3849 
3850 /* ======================== SENTINEL timer handler ==========================
3851  * This is the "main" our Sentinel, being sentinel completely non blocking
3852  * in design. The function is called every second.
3853  * -------------------------------------------------------------------------- */
3854 
3855 /* Perform scheduled operations for the specified Redis instance. */
3856 void sentinelHandleRedisInstance(sentinelRedisInstance *ri) {
3857     /* ========== MONITORING HALF ============ */
3858     /* Every kind of instance */
3859     sentinelReconnectInstance(ri);
3860     sentinelSendPeriodicCommands(ri);
3861 
3862     /* ============== ACTING HALF ============= */
3863     /* We don't proceed with the acting half if we are in TILT mode.
3864      * TILT happens when we find something odd with the time, like a
3865      * sudden change in the clock. */
3866     if (sentinel.tilt) {
3867         if (mstime()-sentinel.tilt_start_time < SENTINEL_TILT_PERIOD) return;
3868         sentinel.tilt = 0;
3869         sentinelEvent(REDIS_WARNING,"-tilt",NULL,"#tilt mode exited");
3870     }
3871 
3872     /* Every kind of instance */
3873     sentinelCheckSubjectivelyDown(ri);
3874 
3875     /* Masters and slaves */
3876     if (ri->flags & (SRI_MASTER|SRI_SLAVE)) {
3877         /* Nothing so far. */
3878     }
3879 
3880     /* Only masters */
3881     if (ri->flags & SRI_MASTER) {
3882         sentinelCheckObjectivelyDown(ri);
3883         if (sentinelStartFailoverIfNeeded(ri))
3884             sentinelAskMasterStateToOtherSentinels(ri,SENTINEL_ASK_FORCED);
3885         sentinelFailoverStateMachine(ri);
3886         sentinelAskMasterStateToOtherSentinels(ri,SENTINEL_NO_FLAGS);
3887     }
3888 }
3889 
3890 /* Perform scheduled operations for all the instances in the dictionary.
3891  * Recursively call the function against dictionaries of slaves. */
3892 void sentinelHandleDictOfRedisInstances(dict *instances) {
3893     dictIterator *di;
3894     dictEntry *de;
3895     sentinelRedisInstance *switch_to_promoted = NULL;
3896 
3897     /* There are a number of things we need to perform against every master. */
3898     di = dictGetIterator(instances);
3899     while((de = dictNext(di)) != NULL) {
3900         sentinelRedisInstance *ri = dictGetVal(de);
3901 
3902         sentinelHandleRedisInstance(ri);
3903         if (ri->flags & SRI_MASTER) {
3904             sentinelHandleDictOfRedisInstances(ri->slaves);
3905             sentinelHandleDictOfRedisInstances(ri->sentinels);
3906             if (ri->failover_state == SENTINEL_FAILOVER_STATE_UPDATE_CONFIG) {
3907                 switch_to_promoted = ri;
3908             }
3909         }
3910     }
3911     if (switch_to_promoted)
3912         sentinelFailoverSwitchToPromotedSlave(switch_to_promoted);
3913     dictReleaseIterator(di);
3914 }
3915 
3916 /* This function checks if we need to enter the TITL mode.
3917  *
3918  * The TILT mode is entered if we detect that between two invocations of the
3919  * timer interrupt, a negative amount of time, or too much time has passed.
3920  * Note that we expect that more or less just 100 milliseconds will pass
3921  * if everything is fine. However we'll see a negative number or a
3922  * difference bigger than SENTINEL_TILT_TRIGGER milliseconds if one of the
3923  * following conditions happen:
3924  *
3925  * 1) The Sentiel process for some time is blocked, for every kind of
3926  * random reason: the load is huge, the computer was frozen for some time
3927  * in I/O or alike, the process was stopped by a signal. Everything.
3928  * 2) The system clock was altered significantly.
3929  *
3930  * Under both this conditions we'll see everything as timed out and failing
3931  * without good reasons. Instead we enter the TILT mode and wait
3932  * for SENTINEL_TILT_PERIOD to elapse before starting to act again.
3933  *
3934  * During TILT time we still collect information, we just do not act. */
3935 void sentinelCheckTiltCondition(void) {
3936     mstime_t now = mstime();
3937     mstime_t delta = now - sentinel.previous_time;
3938 
3939     if (delta < 0 || delta > SENTINEL_TILT_TRIGGER) {
3940         sentinel.tilt = 1;
3941         sentinel.tilt_start_time = mstime();
3942         sentinelEvent(REDIS_WARNING,"+tilt",NULL,"#tilt mode entered");
3943     }
3944     sentinel.previous_time = mstime();
3945 }
3946 
3947 void sentinelTimer(void) {
3948     sentinelCheckTiltCondition();
3949     sentinelHandleDictOfRedisInstances(sentinel.masters);
3950     sentinelRunPendingScripts();
3951     sentinelCollectTerminatedScripts();
3952     sentinelKillTimedoutScripts();
3953 
3954     /* We continuously change the frequency of the Redis "timer interrupt"
3955      * in order to desynchronize every Sentinel from every other.
3956      * This non-determinism avoids that Sentinels started at the same time
3957      * exactly continue to stay synchronized asking to be voted at the
3958      * same time again and again (resulting in nobody likely winning the
3959      * election because of split brain voting). */
3960     server.hz = REDIS_DEFAULT_HZ + rand() % REDIS_DEFAULT_HZ;
3961 }
3962 
3963