1/* Redis Sentinel implementation2 *3 * Copyright (c) 2009-Present, Redis Ltd.4 * All rights reserved.5 *6 * Licensed under your choice of (a) the Redis Source Available License 2.07 * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the8 * GNU Affero General Public License v3 (AGPLv3).9 */1011#include "server.h"12#include "hiredis.h"13#if USE_OPENSSL == 1 /* BUILD_YES */14#include "openssl/ssl.h"15#include "hiredis_ssl.h"16#include "tlshelpers.h"17#endif18#include "async.h"1920#include <ctype.h>21#include <arpa/inet.h>22#include <sys/socket.h>23#include <sys/wait.h>24#include <fcntl.h>2526extern char **environ;2728#if USE_OPENSSL == 1 /* BUILD_YES */29extern SSL_CTX *redis_tls_ctx;30extern SSL_CTX *redis_tls_client_ctx;31/* Peer identity helpers from tls.c (linked in with USE_OPENSSL == 1). */32extern int tlsSetVerifyName(SSL *ssl, const char *names);33extern int tlsSetVerifyIdentity(SSL *ssl, const char *name);34#endif3536#define REDIS_SENTINEL_PORT 263793738/* ======================== Sentinel global state =========================== */3940/* Address object, used to describe an ip:port pair. */41typedef struct sentinelAddr {42 char *hostname; /* Hostname OR address, as specified */43 char *ip; /* Always a resolved address */44 int port;45} sentinelAddr;4647/* A Sentinel Redis Instance object is monitoring. */48#define SRI_MASTER (1<<0)49#define SRI_SLAVE (1<<1)50#define SRI_SENTINEL (1<<2)51#define SRI_S_DOWN (1<<3) /* Subjectively down (no quorum). */52#define SRI_O_DOWN (1<<4) /* Objectively down (confirmed by others). */53#define SRI_MASTER_DOWN (1<<5) /* A Sentinel with this flag set thinks that54 its master is down. */55#define SRI_FAILOVER_IN_PROGRESS (1<<6) /* Failover is in progress for56 this master. */57#define SRI_PROMOTED (1<<7) /* Slave selected for promotion. */58#define SRI_RECONF_SENT (1<<8) /* SLAVEOF <newmaster> sent. */59#define SRI_RECONF_INPROG (1<<9) /* Slave synchronization in progress. */60#define SRI_RECONF_DONE (1<<10) /* Slave synchronized with new master. */61#define SRI_FORCE_FAILOVER (1<<11) /* Force failover with master up. */62#define SRI_SCRIPT_KILL_SENT (1<<12) /* SCRIPT KILL already sent on -BUSY */63#define SRI_MASTER_REBOOT (1<<13) /* Master was detected as rebooting */64/* Note: when adding new flags, please check the flags section in addReplySentinelRedisInstance. */6566/* Note: times are in milliseconds. */67#define SENTINEL_PING_PERIOD 10006869static mstime_t sentinel_info_period = 10000;70static mstime_t sentinel_ping_period = SENTINEL_PING_PERIOD;71static mstime_t sentinel_ask_period = 1000;72static mstime_t sentinel_publish_period = 2000;73static mstime_t sentinel_default_down_after = 30000;74static mstime_t sentinel_tilt_trigger = 2000;75static mstime_t sentinel_tilt_period = SENTINEL_PING_PERIOD * 30;76static mstime_t sentinel_slave_reconf_timeout = 10000;77static mstime_t sentinel_min_link_reconnect_period = 15000;78static mstime_t sentinel_election_timeout = 10000;79static mstime_t sentinel_script_max_runtime = 60000; /* 60 seconds max exec time. */80static mstime_t sentinel_script_retry_delay = 30000; /* 30 seconds between retries. */81static mstime_t sentinel_default_failover_timeout = 60*3*1000;8283#define SENTINEL_HELLO_CHANNEL "__sentinel__:hello"84#define SENTINEL_DEFAULT_SLAVE_PRIORITY 10085#define SENTINEL_DEFAULT_PARALLEL_SYNCS 186#define SENTINEL_MAX_PENDING_COMMANDS 1008788#define SENTINEL_MAX_DESYNC 100089#define SENTINEL_DEFAULT_DENY_SCRIPTS_RECONFIG 190#define SENTINEL_DEFAULT_RESOLVE_HOSTNAMES 091#define SENTINEL_DEFAULT_ANNOUNCE_HOSTNAMES 092#define SENTINEL_DEFAULT_TLS_VERIFY_HOSTNAMES 193#define SENTINEL_TLS_IDENTITY_WARN_PERIOD 60000 /* Rate limit for identity-mismatch warnings, ms. */9495/* Failover machine different states. */96#define SENTINEL_FAILOVER_STATE_NONE 0 /* No failover in progress. */97#define SENTINEL_FAILOVER_STATE_WAIT_START 1 /* Wait for failover_start_time*/98#define SENTINEL_FAILOVER_STATE_SELECT_SLAVE 2 /* Select slave to promote */99#define SENTINEL_FAILOVER_STATE_SEND_SLAVEOF_NOONE 3 /* Slave -> Master */100#define SENTINEL_FAILOVER_STATE_WAIT_PROMOTION 4 /* Wait slave to change role */101#define SENTINEL_FAILOVER_STATE_RECONF_SLAVES 5 /* SLAVEOF newmaster */102#define SENTINEL_FAILOVER_STATE_UPDATE_CONFIG 6 /* Monitor promoted slave. */103104#define SENTINEL_MASTER_LINK_STATUS_UP 0105#define SENTINEL_MASTER_LINK_STATUS_DOWN 1106107/* Generic flags that can be used with different functions.108 * They use higher bits to avoid colliding with the function specific109 * flags. */110#define SENTINEL_NO_FLAGS 0111#define SENTINEL_GENERATE_EVENT (1<<16)112#define SENTINEL_LEADER (1<<17)113#define SENTINEL_OBSERVER (1<<18)114115/* Script execution flags and limits. */116#define SENTINEL_SCRIPT_NONE 0117#define SENTINEL_SCRIPT_RUNNING 1118#define SENTINEL_SCRIPT_MAX_QUEUE 256119#define SENTINEL_SCRIPT_MAX_RUNNING 16120#define SENTINEL_SCRIPT_MAX_RETRY 10121122/* SENTINEL SIMULATE-FAILURE command flags. */123#define SENTINEL_SIMFAILURE_NONE 0124#define SENTINEL_SIMFAILURE_CRASH_AFTER_ELECTION (1<<0)125#define SENTINEL_SIMFAILURE_CRASH_AFTER_PROMOTION (1<<1)126127/* The link to a sentinelRedisInstance. When we have the same set of Sentinels128 * monitoring many masters, we have different instances representing the129 * same Sentinels, one per master, and we need to share the hiredis connections130 * among them. Otherwise if 5 Sentinels are monitoring 100 masters we create131 * 500 outgoing connections instead of 5.132 *133 * So this structure represents a reference counted link in terms of the two134 * hiredis connections for commands and Pub/Sub, and the fields needed for135 * failure detection, since the ping/pong time are now local to the link: if136 * the link is available, the instance is available. This way we don't just137 * have 5 connections instead of 500, we also send 5 pings instead of 500.138 *139 * Links are shared only for Sentinels: master and slave instances have140 * a link with refcount = 1, always. */141typedef struct instanceLink {142 int refcount; /* Number of sentinelRedisInstance owners. */143 int disconnected; /* Non-zero if we need to reconnect cc or pc. */144 int pending_commands; /* Number of commands sent waiting for a reply. */145 redisAsyncContext *cc; /* Hiredis context for commands. */146 redisAsyncContext *pc; /* Hiredis context for Pub / Sub. */147 mstime_t cc_conn_time; /* cc connection time. */148 mstime_t pc_conn_time; /* pc connection time. */149 mstime_t pc_last_activity; /* Last time we received any message. */150 mstime_t last_avail_time; /* Last time the instance replied to ping with151 a reply we consider valid. */152 mstime_t act_ping_time; /* Time at which the last pending ping (no pong153 received after it) was sent. This field is154 set to 0 when a pong is received, and set again155 to the current time if the value is 0 and a new156 ping is sent. */157 mstime_t last_ping_time; /* Time at which we sent the last ping. This is158 only used to avoid sending too many pings159 during failure. Idle time is computed using160 the act_ping_time field. */161 mstime_t last_pong_time; /* Last time the instance replied to ping,162 whatever the reply was. That's used to check163 if the link is idle and must be reconnected. */164 mstime_t last_reconn_time; /* Last reconnection attempt performed when165 the link was down. */166 mstime_t last_tls_identity_warn; /* Last time a TLS identity mismatch was167 logged for this link (rate limiting). */168 int tls_identity_err; /* X509 error recorded by sentinelTLSVerifyCallback()169 when a certificate on this link failed the identity170 check, 0 if none. Reported through a live instance,171 and reset, by sentinelReportTLSIdentityMismatch(). */172} instanceLink;173174typedef struct sentinelRedisInstance {175 int flags; /* See SRI_... defines */176 char *name; /* Master name from the point of view of this sentinel. */177 char *runid; /* Run ID of this instance, or unique ID if is a Sentinel.*/178 uint64_t config_epoch; /* Configuration epoch. */179 sentinelAddr *addr; /* Master host. */180 instanceLink *link; /* Link to the instance, may be shared for Sentinels. */181 mstime_t last_pub_time; /* Last time we sent hello via Pub/Sub. */182 mstime_t last_hello_time; /* Only used if SRI_SENTINEL is set. Last time183 we received a hello from this Sentinel184 via Pub/Sub. */185 mstime_t last_master_down_reply_time; /* Time of last reply to186 SENTINEL is-master-down command. */187 mstime_t s_down_since_time; /* Subjectively down since time. */188 mstime_t o_down_since_time; /* Objectively down since time. */189 mstime_t down_after_period; /* Consider it down after that period. */190 mstime_t master_reboot_down_after_period; /* Consider master down after that period. */191 mstime_t master_reboot_since_time; /* master reboot time since time. */192 mstime_t info_refresh; /* Time at which we received INFO output from it. */193 dict *renamed_commands; /* Commands renamed in this instance:194 Sentinel will use the alternative commands195 mapped on this table to send things like196 SLAVEOF, CONFIG, INFO, ... */197198 /* Role and the first time we observed it.199 * This is useful in order to delay replacing what the instance reports200 * with our own configuration. We need to always wait some time in order201 * to give a chance to the leader to report the new configuration before202 * we do silly things. */203 int role_reported;204 mstime_t role_reported_time;205 mstime_t slave_conf_change_time; /* Last time slave master addr changed. */206207 /* Master specific. */208 dict *sentinels; /* Other sentinels monitoring the same master. */209 dict *slaves; /* Slaves for this master instance. */210 unsigned int quorum;/* Number of sentinels that need to agree on failure. */211 int parallel_syncs; /* How many slaves to reconfigure at same time. */212 char *auth_pass; /* Password to use for AUTH against master & replica. */213 char *auth_user; /* Username for ACLs AUTH against master & replica. */214215 /* Slave specific. */216 mstime_t master_link_down_time; /* Slave replication link down time. */217 int slave_priority; /* Slave priority according to its INFO output. */218 int replica_announced; /* Replica announcing according to its INFO output. */219 mstime_t slave_reconf_sent_time; /* Time at which we sent SLAVE OF <new> */220 struct sentinelRedisInstance *master; /* Master instance if it's slave. */221 char *slave_master_host; /* Master host as reported by INFO */222 int slave_master_port; /* Master port as reported by INFO */223 int slave_master_link_status; /* Master link status as reported by INFO */224 unsigned long long slave_repl_offset; /* Slave replication offset. */225 /* Failover */226 char *leader; /* If this is a master instance, this is the runid of227 the Sentinel that should perform the failover. If228 this is a Sentinel, this is the runid of the Sentinel229 that this Sentinel voted as leader. */230 uint64_t leader_epoch; /* Epoch of the 'leader' field. */231 uint64_t failover_epoch; /* Epoch of the currently started failover. */232 int failover_state; /* See SENTINEL_FAILOVER_STATE_* defines. */233 mstime_t failover_state_change_time;234 mstime_t failover_start_time; /* Last failover attempt start time. */235 mstime_t failover_timeout; /* Max time to refresh failover state. */236 mstime_t failover_delay_logged; /* For what failover_start_time value we237 logged the failover delay. */238 struct sentinelRedisInstance *promoted_slave; /* Promoted slave instance. */239 /* Scripts executed to notify admin or reconfigure clients: when they240 * are set to NULL no script is executed. */241 char *notification_script;242 char *client_reconfig_script;243 sds info; /* cached INFO output */244} sentinelRedisInstance;245246/* Main state. */247struct sentinelState {248 char myid[CONFIG_RUN_ID_SIZE+1]; /* This sentinel ID. */249 uint64_t current_epoch; /* Current epoch. */250 dict *masters; /* Dictionary of master sentinelRedisInstances.251 Key is the instance name, value is the252 sentinelRedisInstance structure pointer. */253 int tilt; /* Are we in TILT mode? */254 int total_tilt; /* Number of tilt. */255 int running_scripts; /* Number of scripts in execution right now. */256 mstime_t tilt_start_time; /* When TITL started. */257 mstime_t previous_time; /* Last time we ran the time handler. */258 list *scripts_queue; /* Queue of user scripts to execute. */259 char *announce_ip; /* IP addr that is gossiped to other sentinels if260 not NULL. */261 int announce_port; /* Port that is gossiped to other sentinels if262 non zero. */263 unsigned long simfailure_flags; /* Failures simulation. */264 int deny_scripts_reconfig; /* Allow SENTINEL SET ... to change script265 paths at runtime? */266 char *sentinel_auth_pass; /* Password to use for AUTH against other sentinel */267 char *sentinel_auth_user; /* Username for ACLs AUTH against other sentinel. */268 int resolve_hostnames; /* Support use of hostnames, assuming DNS is well configured. */269 int announce_hostnames; /* Announce hostnames instead of IPs when we have them. */270 int tls_verify_hostnames; /* Verify that each instance's TLS certificate271 carries the address we connect to. */272} sentinel;273274/* A script execution job. */275typedef struct sentinelScriptJob {276 int flags; /* Script job flags: SENTINEL_SCRIPT_* */277 int retry_num; /* Number of times we tried to execute it. */278 char **argv; /* Arguments to call the script. */279 mstime_t start_time; /* Script execution time if the script is running,280 otherwise 0 if we are allowed to retry the281 execution at any time. If the script is not282 running and it's not 0, it means: do not run283 before the specified time. */284 pid_t pid; /* Script execution pid. */285} sentinelScriptJob;286287/* ======================= hiredis ae.c adapters =============================288 * Note: this implementation is taken from hiredis/adapters/ae.h, however289 * we have our modified copy for Sentinel in order to use our allocator290 * and to have full control over how the adapter works. */291292typedef struct redisAeEvents {293 redisAsyncContext *context;294 aeEventLoop *loop;295 int fd;296 int reading, writing;297} redisAeEvents;298299static void redisAeReadEvent(aeEventLoop *el, int fd, void *privdata, int mask) {300 ((void)el); ((void)fd); ((void)mask);301302 redisAeEvents *e = (redisAeEvents*)privdata;303 redisAsyncHandleRead(e->context);304}305306static void redisAeWriteEvent(aeEventLoop *el, int fd, void *privdata, int mask) {307 ((void)el); ((void)fd); ((void)mask);308309 redisAeEvents *e = (redisAeEvents*)privdata;310 redisAsyncHandleWrite(e->context);311}312313static void redisAeAddRead(void *privdata) {314 redisAeEvents *e = (redisAeEvents*)privdata;315 aeEventLoop *loop = e->loop;316 if (!e->reading) {317 e->reading = 1;318 aeCreateFileEvent(loop,e->fd,AE_READABLE,redisAeReadEvent,e);319 }320}321322static void redisAeDelRead(void *privdata) {323 redisAeEvents *e = (redisAeEvents*)privdata;324 aeEventLoop *loop = e->loop;325 if (e->reading) {326 e->reading = 0;327 aeDeleteFileEvent(loop,e->fd,AE_READABLE);328 }329}330331static void redisAeAddWrite(void *privdata) {332 redisAeEvents *e = (redisAeEvents*)privdata;333 aeEventLoop *loop = e->loop;334 if (!e->writing) {335 e->writing = 1;336 aeCreateFileEvent(loop,e->fd,AE_WRITABLE,redisAeWriteEvent,e);337 }338}339340static void redisAeDelWrite(void *privdata) {341 redisAeEvents *e = (redisAeEvents*)privdata;342 aeEventLoop *loop = e->loop;343 if (e->writing) {344 e->writing = 0;345 aeDeleteFileEvent(loop,e->fd,AE_WRITABLE);346 }347}348349static void redisAeCleanup(void *privdata) {350 redisAeEvents *e = (redisAeEvents*)privdata;351 redisAeDelRead(privdata);352 redisAeDelWrite(privdata);353 zfree(e);354}355356static int redisAeAttach(aeEventLoop *loop, redisAsyncContext *ac) {357 redisContext *c = &(ac->c);358 redisAeEvents *e;359360 /* Nothing should be attached when something is already attached */361 if (ac->ev.data != NULL)362 return C_ERR;363364 /* Create container for context and r/w events */365 e = (redisAeEvents*)zmalloc(sizeof(*e));366 e->context = ac;367 e->loop = loop;368 e->fd = c->fd;369 e->reading = e->writing = 0;370371 /* Register functions to start/stop listening for events */372 ac->ev.addRead = redisAeAddRead;373 ac->ev.delRead = redisAeDelRead;374 ac->ev.addWrite = redisAeAddWrite;375 ac->ev.delWrite = redisAeDelWrite;376 ac->ev.cleanup = redisAeCleanup;377 ac->ev.data = e;378379 return C_OK;380}381382/* ============================= Prototypes ================================= */383384void sentinelLinkEstablishedCallback(const redisAsyncContext *c, int status);385void sentinelDisconnectCallback(const redisAsyncContext *c, int status);386void sentinelReceiveHelloMessages(redisAsyncContext *c, void *reply, void *privdata);387sentinelRedisInstance *sentinelGetMasterByName(char *name);388char *sentinelGetSubjectiveLeader(sentinelRedisInstance *master);389char *sentinelGetObjectiveLeader(sentinelRedisInstance *master);390void instanceLinkConnectionError(const redisAsyncContext *c);391const char *sentinelRedisInstanceTypeStr(sentinelRedisInstance *ri);392void sentinelAbortFailover(sentinelRedisInstance *ri);393void sentinelEvent(int level, char *type, sentinelRedisInstance *ri, const char *fmt, ...);394sentinelRedisInstance *sentinelSelectSlave(sentinelRedisInstance *master);395void sentinelScheduleScriptExecution(char *path, ...);396void sentinelStartFailover(sentinelRedisInstance *master);397void sentinelDiscardReplyCallback(redisAsyncContext *c, void *reply, void *privdata);398int sentinelSendSlaveOf(sentinelRedisInstance *ri, const sentinelAddr *addr);399char *sentinelVoteLeader(sentinelRedisInstance *master, uint64_t req_epoch, char *req_runid, uint64_t *leader_epoch);400int sentinelFlushConfig(void);401void sentinelGenerateInitialMonitorEvents(void);402int sentinelSendPing(sentinelRedisInstance *ri);403int sentinelForceHelloUpdateForMaster(sentinelRedisInstance *master);404sentinelRedisInstance *getSentinelRedisInstanceByAddrAndRunID(dict *instances, char *ip, int port, char *runid);405void sentinelSimFailureCrash(void);406407/* ========================= Dictionary types =============================== */408409void releaseSentinelRedisInstance(sentinelRedisInstance *ri);410411void dictInstancesValDestructor (dict *d, void *obj) {412 UNUSED(d);413 releaseSentinelRedisInstance(obj);414}415416/* Instance name (sds) -> instance (sentinelRedisInstance pointer)417 *418 * also used for: sentinelRedisInstance->sentinels dictionary that maps419 * sentinels ip:port to last seen time in Pub/Sub hello message. */420dictType instancesDictType = {421 dictSdsHash, /* hash function */422 NULL, /* key dup */423 NULL, /* val dup */424 dictSdsKeyCompare, /* key compare */425 NULL, /* key destructor */426 dictInstancesValDestructor,/* val destructor */427 NULL /* allow to expand */428};429430/* Instance runid (sds) -> votes (long casted to void*)431 *432 * This is useful into sentinelGetObjectiveLeader() function in order to433 * count the votes and understand who is the leader. */434dictType leaderVotesDictType = {435 dictSdsHash, /* hash function */436 NULL, /* key dup */437 NULL, /* val dup */438 dictSdsKeyCompare, /* key compare */439 NULL, /* key destructor */440 NULL, /* val destructor */441 NULL /* allow to expand */442};443444/* Instance renamed commands table. */445dictType renamedCommandsDictType = {446 dictSdsCaseHash, /* hash function */447 NULL, /* key dup */448 NULL, /* val dup */449 dictSdsKeyCaseCompare, /* key compare */450 dictSdsDestructor, /* key destructor */451 dictSdsDestructor, /* val destructor */452 NULL /* allow to expand */453};454455/* =========================== Initialization =============================== */456457void sentinelSetCommand(client *c);458void sentinelConfigGetCommand(client *c);459void sentinelConfigSetCommand(client *c);460461/* this array is used for sentinel config lookup, which need to be loaded462 * before monitoring masters config to avoid dependency issues */463const char *preMonitorCfgName[] = { 464 "announce-ip",465 "announce-port",466 "deny-scripts-reconfig",467 "sentinel-user",468 "sentinel-pass",469 "current-epoch",470 "myid",471 "resolve-hostnames",472 "announce-hostnames",473 "tls-verify-hostnames"474};475476/* Returns 1 if the string contains control characters (0x00-0x1F or 0x7F),477 * which must be rejected to prevent config injection via newlines/etc. */478int sentinelStringContainsControlChars(sds s) {479 for (size_t i = 0; i < sdslen(s); i++) {480 unsigned char c = (unsigned char)s[i];481 if (c < 0x20 || c == 0x7F) return 1;482 }483 return 0;484}485486/* Append an sds value to dest, quoting it with sdscatrepr only if the value487 * contains characters that need escaping (spaces, quotes, control chars, etc.).488 * Simple values are appended as-is, preserving the traditional config format. */489static sds sentinelSdscatConfigArg(sds dest, sds value) {490 if (sdsneedsrepr(value))491 return sdscatrepr(dest, value, sdslen(value));492 return sdscatsds(dest, value);493}494495/* This function overwrites a few normal Redis config default with Sentinel496 * specific defaults. */497void initSentinelConfig(void) {498 server.port = REDIS_SENTINEL_PORT;499 server.protected_mode = 0; /* Sentinel must be exposed. */500}501502void freeSentinelLoadQueueEntry(void *item);503504/* Perform the Sentinel mode initialization. */505void initSentinel(void) {506 /* Initialize various data structures. */507 sentinel.current_epoch = 0;508 sentinel.masters = dictCreate(&instancesDictType);509 sentinel.tilt = 0;510 sentinel.tilt_start_time = 0;511 sentinel.total_tilt = 0;512 sentinel.previous_time = mstime();513 sentinel.running_scripts = 0;514 sentinel.scripts_queue = listCreate();515 sentinel.announce_ip = NULL;516 sentinel.announce_port = 0;517 sentinel.simfailure_flags = SENTINEL_SIMFAILURE_NONE;518 sentinel.deny_scripts_reconfig = SENTINEL_DEFAULT_DENY_SCRIPTS_RECONFIG;519 sentinel.sentinel_auth_pass = NULL;520 sentinel.sentinel_auth_user = NULL;521 sentinel.resolve_hostnames = SENTINEL_DEFAULT_RESOLVE_HOSTNAMES;522 sentinel.announce_hostnames = SENTINEL_DEFAULT_ANNOUNCE_HOSTNAMES;523 sentinel.tls_verify_hostnames = SENTINEL_DEFAULT_TLS_VERIFY_HOSTNAMES;524 memset(sentinel.myid,0,sizeof(sentinel.myid));525 server.sentinel_config = NULL;526}527528/* This function is for checking whether sentinel config file has been set,529 * also checking whether we have write permissions. */530void sentinelCheckConfigFile(void) {531 if (server.configfile == NULL) {532 serverLog(LL_WARNING,533 "Sentinel needs config file on disk to save state. Exiting...");534 exit(1);535 } else if (access(server.configfile,W_OK) == -1) {536 serverLog(LL_WARNING,537 "Sentinel config file %s is not writable: %s. Exiting...",538 server.configfile,strerror(errno));539 exit(1);540 }541}542543/* This function gets called when the server is in Sentinel mode, started,544 * loaded the configuration, and is ready for normal operations. */545void sentinelIsRunning(void) {546 int j;547548 /* If this Sentinel has yet no ID set in the configuration file, we549 * pick a random one and persist the config on disk. From now on this550 * will be this Sentinel ID across restarts. */551 for (j = 0; j < CONFIG_RUN_ID_SIZE; j++)552 if (sentinel.myid[j] != 0) break;553554 if (j == CONFIG_RUN_ID_SIZE) {555 /* Pick ID and persist the config. */556 getRandomHexChars(sentinel.myid,CONFIG_RUN_ID_SIZE);557 sentinelFlushConfig();558 }559560 /* Log its ID to make debugging of issues simpler. */561 serverLog(LL_NOTICE,"Sentinel ID is %s", sentinel.myid);562563 /* We want to generate a +monitor event for every configured master564 * at startup. */565 sentinelGenerateInitialMonitorEvents();566}567568/* ============================== sentinelAddr ============================== */569570/* Create a sentinelAddr object and return it on success.571 * On error NULL is returned and errno is set to:572 * ENOENT: Can't resolve the hostname, unless accept_unresolved is non-zero.573 * EINVAL: Invalid port number.574 */575sentinelAddr *createSentinelAddr(char *hostname, int port, int is_accept_unresolved) {576 char ip[NET_IP_STR_LEN];577 sentinelAddr *sa;578579 if (port < 0 || port > 65535) {580 errno = EINVAL;581 return NULL;582 }583 if (anetResolve(NULL,hostname,ip,sizeof(ip),584 sentinel.resolve_hostnames ? ANET_NONE : ANET_IP_ONLY) == ANET_ERR) {585 serverLog(LL_WARNING, "Failed to resolve hostname '%s'", hostname);586 if (sentinel.resolve_hostnames && is_accept_unresolved) {587 ip[0] = '\0';588 }589 else {590 errno = ENOENT;591 return NULL;592 }593 }594 sa = zmalloc(sizeof(*sa));595 sa->hostname = sdsnew(hostname);596 sa->ip = sdsnew(ip);597 sa->port = port;598 return sa;599}600601/* Return a duplicate of the source address. */602sentinelAddr *dupSentinelAddr(sentinelAddr *src) {603 sentinelAddr *sa;604605 sa = zmalloc(sizeof(*sa));606 sa->hostname = sdsnew(src->hostname);607 sa->ip = sdsnew(src->ip);608 sa->port = src->port;609 return sa;610}611612/* Free a Sentinel address. Can't fail. */613void releaseSentinelAddr(sentinelAddr *sa) {614 sdsfree(sa->hostname);615 sdsfree(sa->ip);616 zfree(sa);617}618619/* Return non-zero if the two addresses are equal, either by address620 * or by hostname if they could not have been resolved.621 */622int sentinelAddrOrHostnameEqual(sentinelAddr *a, sentinelAddr *b) {623 return a->port == b->port &&624 (!strcmp(a->ip, b->ip) ||625 !strcasecmp(a->hostname, b->hostname));626}627628/* Return non-zero if a hostname matches an address. */629int sentinelAddrEqualsHostname(sentinelAddr *a, char *hostname) {630 char ip[NET_IP_STR_LEN];631632 /* Try resolve the hostname and compare it to the address */633 if (anetResolve(NULL, hostname, ip, sizeof(ip),634 sentinel.resolve_hostnames ? ANET_NONE : ANET_IP_ONLY) == ANET_ERR) {635636 /* If failed resolve then compare based on hostnames. That is our best effort as637 * long as the server is unavailable for some reason. It is fine since Redis 638 * instance cannot have multiple hostnames for a given setup */639 return !strcasecmp(sentinel.resolve_hostnames ? a->hostname : a->ip, hostname);640 }641 /* Compare based on address */642 return !strcasecmp(a->ip, ip);643}644645const char *announceSentinelAddr(const sentinelAddr *a) {646 return sentinel.announce_hostnames ? a->hostname : a->ip;647}648649/* Return an allocated sds with hostname/address:port. IPv6650 * addresses are bracketed the same way anetFormatAddr() does.651 */652sds announceSentinelAddrAndPort(const sentinelAddr *a) {653 const char *addr = announceSentinelAddr(a);654 if (strchr(addr, ':') != NULL)655 return sdscatprintf(sdsempty(), "[%s]:%d", addr, a->port);656 else657 return sdscatprintf(sdsempty(), "%s:%d", addr, a->port);658}659660/* =========================== Events notification ========================== */661662/* Send an event to log, pub/sub, user notification script.663 *664 * 'level' is the log level for logging. Only LL_WARNING events will trigger665 * the execution of the user notification script.666 *667 * 'type' is the message type, also used as a pub/sub channel name.668 *669 * 'ri', is the redis instance target of this event if applicable, and is670 * used to obtain the path of the notification script to execute.671 *672 * The remaining arguments are printf-alike.673 * If the format specifier starts with the two characters "%@" then ri is674 * not NULL, and the message is prefixed with an instance identifier in the675 * following format:676 *677 * <instance type> <instance name> <ip> <port>678 *679 * If the instance type is not master, than the additional string is680 * added to specify the originating master:681 *682 * @ <master name> <master ip> <master port>683 *684 * Any other specifier after "%@" is processed by printf itself.685 */686void sentinelEvent(int level, char *type, sentinelRedisInstance *ri,687 const char *fmt, ...) {688 va_list ap;689 char msg[LOG_MAX_LEN];690 robj *channel, *payload;691692 /* Handle %@ */693 if (fmt[0] == '%' && fmt[1] == '@') {694 sentinelRedisInstance *master = (ri->flags & SRI_MASTER) ?695 NULL : ri->master;696697 if (master) {698 snprintf(msg, sizeof(msg), "%s %s %s %d @ %s %s %d",699 sentinelRedisInstanceTypeStr(ri),700 ri->name, announceSentinelAddr(ri->addr), ri->addr->port,701 master->name, announceSentinelAddr(master->addr), master->addr->port);702 } else {703 snprintf(msg, sizeof(msg), "%s %s %s %d",704 sentinelRedisInstanceTypeStr(ri),705 ri->name, announceSentinelAddr(ri->addr), ri->addr->port);706 }707 fmt += 2;708 } else {709 msg[0] = '\0';710 }711712 /* Use vsprintf for the rest of the formatting if any. */713 if (fmt[0] != '\0') {714 va_start(ap, fmt);715 vsnprintf(msg+strlen(msg), sizeof(msg)-strlen(msg), fmt, ap);716 va_end(ap);717 }718719 /* Log the message if the log level allows it to be logged. */720 if (level >= server.verbosity)721 serverLog(level,"%s %s",type,msg);722723 /* Publish the message via Pub/Sub if it's not a debugging one. */724 if (level != LL_DEBUG) {725 channel = createStringObject(type,strlen(type));726 payload = createStringObject(msg,strlen(msg));727 pubsubPublishMessage(channel,payload,0);728 decrRefCount(channel);729 decrRefCount(payload);730 }731732 /* Call the notification script if applicable. */733 if (level == LL_WARNING && ri != NULL) {734 sentinelRedisInstance *master = (ri->flags & SRI_MASTER) ?735 ri : ri->master;736 if (master && master->notification_script) {737 sentinelScheduleScriptExecution(master->notification_script,738 type,msg,NULL);739 }740 }741}742743/* This function is called only at startup and is used to generate a744 * +monitor event for every configured master. The same events are also745 * generated when a master to monitor is added at runtime via the746 * SENTINEL MONITOR command. */747void sentinelGenerateInitialMonitorEvents(void) {748 dictIterator di;749 dictEntry *de;750751 dictInitIterator(&di, sentinel.masters);752 while((de = dictNext(&di)) != NULL) {753 sentinelRedisInstance *ri = dictGetVal(de);754 sentinelEvent(LL_WARNING,"+monitor",ri,"%@ quorum %d",ri->quorum);755 }756 dictResetIterator(&di);757}758759/* ============================ script execution ============================ */760761/* Release a script job structure and all the associated data. */762void sentinelReleaseScriptJob(sentinelScriptJob *sj) {763 int j = 0;764765 while(sj->argv[j]) sdsfree(sj->argv[j++]);766 zfree(sj->argv);767 zfree(sj);768}769770#define SENTINEL_SCRIPT_MAX_ARGS 16771void sentinelScheduleScriptExecution(char *path, ...) {772 va_list ap;773 char *argv[SENTINEL_SCRIPT_MAX_ARGS+1];774 int argc = 1;775 sentinelScriptJob *sj;776777 va_start(ap, path);778 while(argc < SENTINEL_SCRIPT_MAX_ARGS) {779 argv[argc] = va_arg(ap,char*);780 if (!argv[argc]) break;781 argv[argc] = sdsnew(argv[argc]); /* Copy the string. */782 argc++;783 }784 va_end(ap);785 argv[0] = sdsnew(path);786787 sj = zmalloc(sizeof(*sj));788 sj->flags = SENTINEL_SCRIPT_NONE;789 sj->retry_num = 0;790 sj->argv = zmalloc(sizeof(char*)*(argc+1));791 sj->start_time = 0;792 sj->pid = 0;793 memcpy(sj->argv,argv,sizeof(char*)*(argc+1));794795 listAddNodeTail(sentinel.scripts_queue,sj);796797 /* Remove the oldest non running script if we already hit the limit. */798 if (listLength(sentinel.scripts_queue) > SENTINEL_SCRIPT_MAX_QUEUE) {799 listNode *ln;800 listIter li;801802 listRewind(sentinel.scripts_queue,&li);803 while ((ln = listNext(&li)) != NULL) {804 sj = ln->value;805806 if (sj->flags & SENTINEL_SCRIPT_RUNNING) continue;807 /* The first node is the oldest as we add on tail. */808 listDelNode(sentinel.scripts_queue,ln);809 sentinelReleaseScriptJob(sj);810 break;811 }812 serverAssert(listLength(sentinel.scripts_queue) <=813 SENTINEL_SCRIPT_MAX_QUEUE);814 }815}816817/* Lookup a script in the scripts queue via pid, and returns the list node818 * (so that we can easily remove it from the queue if needed). */819listNode *sentinelGetScriptListNodeByPid(pid_t pid) {820 listNode *ln;821 listIter li;822823 listRewind(sentinel.scripts_queue,&li);824 while ((ln = listNext(&li)) != NULL) {825 sentinelScriptJob *sj = ln->value;826827 if ((sj->flags & SENTINEL_SCRIPT_RUNNING) && sj->pid == pid)828 return ln;829 }830 return NULL;831}832833/* Run pending scripts if we are not already at max number of running834 * scripts. */835void sentinelRunPendingScripts(void) {836 listNode *ln;837 listIter li;838 mstime_t now = mstime();839840 /* Find jobs that are not running and run them, from the top to the841 * tail of the queue, so we run older jobs first. */842 listRewind(sentinel.scripts_queue,&li);843 while (sentinel.running_scripts < SENTINEL_SCRIPT_MAX_RUNNING &&844 (ln = listNext(&li)) != NULL)845 {846 sentinelScriptJob *sj = ln->value;847 pid_t pid;848849 /* Skip if already running. */850 if (sj->flags & SENTINEL_SCRIPT_RUNNING) continue;851852 /* Skip if it's a retry, but not enough time has elapsed. */853 if (sj->start_time && sj->start_time > now) continue;854855 sj->flags |= SENTINEL_SCRIPT_RUNNING;856 sj->start_time = mstime();857 sj->retry_num++;858 pid = fork();859860 if (pid == -1) {861 /* Parent (fork error).862 * We report fork errors as signal 99, in order to unify the863 * reporting with other kind of errors. */864 sentinelEvent(LL_WARNING,"-script-error",NULL,865 "%s %d %d", sj->argv[0], 99, 0);866 sj->flags &= ~SENTINEL_SCRIPT_RUNNING;867 sj->pid = 0;868 } else if (pid == 0) {869 /* Child */870 connTypeCleanupAll();871 execve(sj->argv[0],sj->argv,environ);872 /* If we are here an error occurred. */873 _exit(2); /* Don't retry execution. */874 } else {875 sentinel.running_scripts++;876 sj->pid = pid;877 sentinelEvent(LL_DEBUG,"+script-child",NULL,"%ld",(long)pid);878 }879 }880}881882/* How much to delay the execution of a script that we need to retry after883 * an error?884 *885 * We double the retry delay for every further retry we do. So for instance886 * if RETRY_DELAY is set to 30 seconds and the max number of retries is 10887 * starting from the second attempt to execute the script the delays are:888 * 30 sec, 60 sec, 2 min, 4 min, 8 min, 16 min, 32 min, 64 min, 128 min. */889mstime_t sentinelScriptRetryDelay(int retry_num) {890 mstime_t delay = sentinel_script_retry_delay;891892 while (retry_num-- > 1) delay *= 2;893 return delay;894}895896/* Check for scripts that terminated, and remove them from the queue if the897 * script terminated successfully. If instead the script was terminated by898 * a signal, or returned exit code "1", it is scheduled to run again if899 * the max number of retries did not already elapsed. */900void sentinelCollectTerminatedScripts(void) {901 int statloc;902 pid_t pid;903904 while ((pid = waitpid(-1, &statloc, WNOHANG)) > 0) {905 int exitcode = WEXITSTATUS(statloc);906 int bysignal = 0;907 listNode *ln;908 sentinelScriptJob *sj;909910 if (WIFSIGNALED(statloc)) bysignal = WTERMSIG(statloc);911 sentinelEvent(LL_DEBUG,"-script-child",NULL,"%ld %d %d",912 (long)pid, exitcode, bysignal);913914 ln = sentinelGetScriptListNodeByPid(pid);915 if (ln == NULL) {916 serverLog(LL_WARNING,"waitpid() returned a pid (%ld) we can't find in our scripts execution queue!", (long)pid);917 continue;918 }919 sj = ln->value;920921 /* If the script was terminated by a signal or returns an922 * exit code of "1" (that means: please retry), we reschedule it923 * if the max number of retries is not already reached. */924 if ((bysignal || exitcode == 1) &&925 sj->retry_num != SENTINEL_SCRIPT_MAX_RETRY)926 {927 sj->flags &= ~SENTINEL_SCRIPT_RUNNING;928 sj->pid = 0;929 sj->start_time = mstime() +930 sentinelScriptRetryDelay(sj->retry_num);931 } else {932 /* Otherwise let's remove the script, but log the event if the933 * execution did not terminated in the best of the ways. */934 if (bysignal || exitcode != 0) {935 sentinelEvent(LL_WARNING,"-script-error",NULL,936 "%s %d %d", sj->argv[0], bysignal, exitcode);937 }938 listDelNode(sentinel.scripts_queue,ln);939 sentinelReleaseScriptJob(sj);940 }941 sentinel.running_scripts--;942 }943}944945/* Kill scripts in timeout, they'll be collected by the946 * sentinelCollectTerminatedScripts() function. */947void sentinelKillTimedoutScripts(void) {948 listNode *ln;949 listIter li;950 mstime_t now = mstime();951952 listRewind(sentinel.scripts_queue,&li);953 while ((ln = listNext(&li)) != NULL) {954 sentinelScriptJob *sj = ln->value;955956 if (sj->flags & SENTINEL_SCRIPT_RUNNING &&957 (now - sj->start_time) > sentinel_script_max_runtime)958 {959 sentinelEvent(LL_WARNING,"-script-timeout",NULL,"%s %ld",960 sj->argv[0], (long)sj->pid);961 kill(sj->pid,SIGKILL);962 }963 }964}965966/* Implements SENTINEL PENDING-SCRIPTS command. */967void sentinelPendingScriptsCommand(client *c) {968 listNode *ln;969 listIter li;970971 addReplyArrayLen(c,listLength(sentinel.scripts_queue));972 listRewind(sentinel.scripts_queue,&li);973 while ((ln = listNext(&li)) != NULL) {974 sentinelScriptJob *sj = ln->value;975 int j = 0;976977 addReplyMapLen(c,5);978979 addReplyBulkCString(c,"argv");980 while (sj->argv[j]) j++;981 addReplyArrayLen(c,j);982 j = 0;983 while (sj->argv[j]) addReplyBulkCString(c,sj->argv[j++]);984985 addReplyBulkCString(c,"flags");986 addReplyBulkCString(c,987 (sj->flags & SENTINEL_SCRIPT_RUNNING) ? "running" : "scheduled");988989 addReplyBulkCString(c,"pid");990 addReplyBulkLongLong(c,sj->pid);991992 if (sj->flags & SENTINEL_SCRIPT_RUNNING) {993 addReplyBulkCString(c,"run-time");994 addReplyBulkLongLong(c,mstime() - sj->start_time);995 } else {996 mstime_t delay = sj->start_time ? (sj->start_time-mstime()) : 0;997 if (delay < 0) delay = 0;998 addReplyBulkCString(c,"run-delay");999 addReplyBulkLongLong(c,delay);1000 }10011002 addReplyBulkCString(c,"retry-num");1003 addReplyBulkLongLong(c,sj->retry_num);1004 }1005}10061007/* This function calls, if any, the client reconfiguration script with the1008 * following parameters:1009 *1010 * <master-name> <role> <state> <from-ip> <from-port> <to-ip> <to-port>1011 *1012 * It is called every time a failover is performed.1013 *1014 * <state> is currently always "start".1015 * <role> is either "leader" or "observer".1016 *1017 * from/to fields are respectively master -> promoted slave addresses for1018 * "start" and "end". */1019void sentinelCallClientReconfScript(sentinelRedisInstance *master, int role, char *state, sentinelAddr *from, sentinelAddr *to) {1020 char fromport[32], toport[32];10211022 if (master->client_reconfig_script == NULL) return;1023 ll2string(fromport,sizeof(fromport),from->port);1024 ll2string(toport,sizeof(toport),to->port);1025 sentinelScheduleScriptExecution(master->client_reconfig_script,1026 master->name,1027 (role == SENTINEL_LEADER) ? "leader" : "observer",1028 state, announceSentinelAddr(from), fromport,1029 announceSentinelAddr(to), toport, NULL);1030}10311032/* =============================== instanceLink ============================= */10331034/* Create a not yet connected link object. */1035instanceLink *createInstanceLink(void) {1036 instanceLink *link = zmalloc(sizeof(*link));10371038 link->refcount = 1;1039 link->disconnected = 1;1040 link->pending_commands = 0;1041 link->cc = NULL;1042 link->pc = NULL;1043 link->cc_conn_time = 0;1044 link->pc_conn_time = 0;1045 link->last_reconn_time = 0;1046 link->last_tls_identity_warn = 0;1047 link->tls_identity_err = 0;1048 link->pc_last_activity = 0;1049 /* We set the act_ping_time to "now" even if we actually don't have yet1050 * a connection with the node, nor we sent a ping.1051 * This is useful to detect a timeout in case we'll not be able to connect1052 * with the node at all. */1053 link->act_ping_time = mstime();1054 link->last_ping_time = 0;1055 link->last_avail_time = mstime();1056 link->last_pong_time = mstime();1057 return link;1058}10591060/* Disconnect a hiredis connection in the context of an instance link. */1061void instanceLinkCloseConnection(instanceLink *link, redisAsyncContext *c) {1062 if (c == NULL) return;10631064 if (link->cc == c) {1065 link->cc = NULL;1066 link->pending_commands = 0;1067 }1068 if (link->pc == c) link->pc = NULL;1069 c->data = NULL;1070 link->disconnected = 1;1071 redisAsyncFree(c);1072}10731074/* Decrement the refcount of a link object, if it drops to zero, actually1075 * free it and return NULL. Otherwise don't do anything and return the pointer1076 * to the object.1077 *1078 * If we are not going to free the link and ri is not NULL, we rebind all the1079 * pending requests in link->cc (hiredis connection for commands) to a1080 * callback that will just ignore them. This is useful to avoid processing1081 * replies for an instance that no longer exists. */1082instanceLink *releaseInstanceLink(instanceLink *link, sentinelRedisInstance *ri)1083{1084 serverAssert(link->refcount > 0);1085 link->refcount--;1086 if (link->refcount != 0) {1087 if (ri && ri->link->cc) {1088 /* This instance may have pending callbacks in the hiredis async1089 * context, having as 'privdata' the instance that we are going to1090 * free. Let's rewrite the callback list, directly exploiting1091 * hiredis internal data structures, in order to bind them with1092 * a callback that will ignore the reply at all. */1093 redisCallback *cb;1094 redisCallbackList *callbacks = &link->cc->replies;10951096 cb = callbacks->head;1097 while(cb) {1098 if (cb->privdata == ri) {1099 cb->fn = sentinelDiscardReplyCallback;1100 cb->privdata = NULL; /* Not strictly needed. */1101 }1102 cb = cb->next;1103 }1104 }1105 return link; /* Other active users. */1106 }11071108 instanceLinkCloseConnection(link,link->cc);1109 instanceLinkCloseConnection(link,link->pc);1110 zfree(link);1111 return NULL;1112}11131114/* This function will attempt to share the instance link we already have1115 * for the same Sentinel in the context of a different master, with the1116 * instance we are passing as argument.1117 *1118 * This way multiple Sentinel objects that refer all to the same physical1119 * Sentinel instance but in the context of different masters will use1120 * a single connection, will send a single PING per second for failure1121 * detection and so forth.1122 *1123 * Return C_OK if a matching Sentinel was found in the context of a1124 * different master and sharing was performed. Otherwise C_ERR1125 * is returned. */1126int sentinelTryConnectionSharing(sentinelRedisInstance *ri) {1127 serverAssert(ri->flags & SRI_SENTINEL);1128 dictIterator di;1129 dictEntry *de;11301131 if (ri->runid == NULL) return C_ERR; /* No way to identify it. */1132 if (ri->link->refcount > 1) return C_ERR; /* Already shared. */11331134 dictInitIterator(&di, sentinel.masters);1135 while((de = dictNext(&di)) != NULL) {1136 sentinelRedisInstance *master = dictGetVal(de), *match;1137 /* We want to share with the same physical Sentinel referenced1138 * in other masters, so skip our master. */1139 if (master == ri->master) continue;1140 match = getSentinelRedisInstanceByAddrAndRunID(master->sentinels,1141 NULL,0,ri->runid);1142 if (match == NULL) continue; /* No match. */1143 if (match == ri) continue; /* Should never happen but... safer. */11441145 /* We identified a matching Sentinel, great! Let's free our link1146 * and use the one of the matching Sentinel. */1147 releaseInstanceLink(ri->link,NULL);1148 ri->link = match->link;1149 match->link->refcount++;1150 dictResetIterator(&di);1151 return C_OK;1152 }1153 dictResetIterator(&di);1154 return C_ERR;1155}11561157/* Disconnect the relevant master and its replicas. */1158void dropInstanceConnections(sentinelRedisInstance *ri) {1159 serverAssert(ri->flags & SRI_MASTER);11601161 /* Disconnect with the master. */1162 instanceLinkCloseConnection(ri->link, ri->link->cc);1163 instanceLinkCloseConnection(ri->link, ri->link->pc);1164 1165 /* Disconnect with all replicas. */1166 dictIterator di;1167 dictEntry *de;1168 sentinelRedisInstance *repl_ri;11691170 dictInitIterator(&di, ri->slaves);1171 while ((de = dictNext(&di)) != NULL) {1172 repl_ri = dictGetVal(de);1173 instanceLinkCloseConnection(repl_ri->link, repl_ri->link->cc);1174 instanceLinkCloseConnection(repl_ri->link, repl_ri->link->pc);1175 }1176 dictResetIterator(&di);1177}11781179/* Drop all connections to other sentinels. Returns the number of connections1180 * dropped.*/1181int sentinelDropConnections(void) {1182 dictIterator di;1183 dictEntry *de;1184 int dropped = 0;11851186 dictInitIterator(&di, sentinel.masters);1187 while ((de = dictNext(&di)) != NULL) {1188 dictIterator sdi;1189 dictEntry *sde;11901191 sentinelRedisInstance *ri = dictGetVal(de);1192 dictInitIterator(&sdi, ri->sentinels);1193 while ((sde = dictNext(&sdi)) != NULL) {1194 sentinelRedisInstance *si = dictGetVal(sde);1195 if (!si->link->disconnected) {1196 instanceLinkCloseConnection(si->link, si->link->pc);1197 instanceLinkCloseConnection(si->link, si->link->cc);1198 dropped++;1199 }1200 }1201 dictResetIterator(&sdi);1202 }1203 dictResetIterator(&di);12041205 return dropped;1206}12071208/* When we detect a Sentinel to switch address (reporting a different IP/port1209 * pair in Hello messages), let's update all the matching Sentinels in the1210 * context of other masters as well and disconnect the links, so that everybody1211 * will be updated.1212 *1213 * Return the number of updated Sentinel addresses. */1214int sentinelUpdateSentinelAddressInAllMasters(sentinelRedisInstance *ri) {1215 serverAssert(ri->flags & SRI_SENTINEL);1216 dictIterator di;1217 dictEntry *de;1218 int reconfigured = 0;12191220 dictInitIterator(&di, sentinel.masters);1221 while((de = dictNext(&di)) != NULL) {1222 sentinelRedisInstance *master = dictGetVal(de), *match;1223 match = getSentinelRedisInstanceByAddrAndRunID(master->sentinels,1224 NULL,0,ri->runid);1225 /* If there is no match, this master does not know about this1226 * Sentinel, try with the next one. */1227 if (match == NULL) continue;12281229 /* Disconnect the old links if connected. */1230 if (match->link->cc != NULL)1231 instanceLinkCloseConnection(match->link,match->link->cc);1232 if (match->link->pc != NULL)1233 instanceLinkCloseConnection(match->link,match->link->pc);12341235 if (match == ri) continue; /* Address already updated for it. */12361237 /* Update the address of the matching Sentinel by copying the address1238 * of the Sentinel object that received the address update. */1239 releaseSentinelAddr(match->addr);1240 match->addr = dupSentinelAddr(ri->addr);1241 reconfigured++;1242 }1243 dictResetIterator(&di);1244 if (reconfigured)1245 sentinelEvent(LL_NOTICE,"+sentinel-address-update", ri,1246 "%@ %d additional matching instances", reconfigured);1247 return reconfigured;1248}12491250/* This function is called when a hiredis connection reported an error.1251 * We set it to NULL and mark the link as disconnected so that it will be1252 * reconnected again.1253 *1254 * Note: we don't free the hiredis context as hiredis will do it for us1255 * for async connections. */1256void instanceLinkConnectionError(const redisAsyncContext *c) {1257 instanceLink *link = c->data;1258 int pubsub;12591260 if (!link) return;12611262 pubsub = (link->pc == c);1263 if (pubsub)1264 link->pc = NULL;1265 else1266 link->cc = NULL;1267 link->disconnected = 1;1268}12691270/* Hiredis connection established / disconnected callbacks. We need them1271 * just to cleanup our link state. */1272void sentinelLinkEstablishedCallback(const redisAsyncContext *c, int status) {1273 if (status != C_OK) instanceLinkConnectionError(c);1274}12751276void sentinelDisconnectCallback(const redisAsyncContext *c, int status) {1277 UNUSED(status);1278 instanceLinkConnectionError(c);1279}12801281/* ========================== sentinelRedisInstance ========================= */12821283/* Create a redis instance, the following fields must be populated by the1284 * caller if needed:1285 * runid: set to NULL but will be populated once INFO output is received.1286 * info_refresh: is set to 0 to mean that we never received INFO so far.1287 *1288 * If SRI_MASTER is set into initial flags the instance is added to1289 * sentinel.masters table.1290 *1291 * if SRI_SLAVE or SRI_SENTINEL is set then 'master' must be not NULL and the1292 * instance is added into master->slaves or master->sentinels table.1293 *1294 * If the instance is a slave, the name parameter is ignored and is created1295 * automatically as ip/hostname:port.1296 *1297 * The function fails if hostname can't be resolved or port is out of range.1298 * When this happens NULL is returned and errno is set accordingly to the1299 * createSentinelAddr() function.1300 *1301 * The function may also fail and return NULL with errno set to EBUSY if1302 * a master with the same name, a slave with the same address, or a sentinel1303 * with the same ID already exists. */13041305sentinelRedisInstance *createSentinelRedisInstance(char *name, int flags, char *hostname, int port, int quorum, sentinelRedisInstance *master) {1306 sentinelRedisInstance *ri;1307 sentinelAddr *addr;1308 dict *table = NULL;1309 sds sdsname;13101311 serverAssert(flags & (SRI_MASTER|SRI_SLAVE|SRI_SENTINEL));1312 serverAssert((flags & SRI_MASTER) || master != NULL);13131314 /* Check address validity. */1315 addr = createSentinelAddr(hostname,port,1);1316 if (addr == NULL) return NULL;13171318 /* For slaves use ip/host:port as name. */1319 if (flags & SRI_SLAVE)1320 sdsname = announceSentinelAddrAndPort(addr);1321 else1322 sdsname = sdsnew(name);13231324 /* Make sure the entry is not duplicated. This may happen when the same1325 * name for a master is used multiple times inside the configuration or1326 * if we try to add multiple times a slave or sentinel with same ip/port1327 * to a master. */1328 if (flags & SRI_MASTER) table = sentinel.masters;1329 else if (flags & SRI_SLAVE) table = master->slaves;1330 else if (flags & SRI_SENTINEL) table = master->sentinels;1331 if (dictFind(table,sdsname)) {1332 releaseSentinelAddr(addr);1333 sdsfree(sdsname);1334 errno = EBUSY;1335 return NULL;1336 }13371338 /* Create the instance object. */1339 ri = zmalloc(sizeof(*ri));1340 /* Note that all the instances are started in the disconnected state,1341 * the event loop will take care of connecting them. */1342 ri->flags = flags;1343 ri->name = sdsname;1344 ri->runid = NULL;1345 ri->config_epoch = 0;1346 ri->addr = addr;1347 ri->link = createInstanceLink();1348 ri->last_pub_time = mstime();1349 ri->last_hello_time = mstime();1350 ri->last_master_down_reply_time = mstime();1351 ri->s_down_since_time = 0;1352 ri->o_down_since_time = 0;1353 ri->down_after_period = master ? master->down_after_period : sentinel_default_down_after;1354 ri->master_reboot_down_after_period = 0;1355 ri->master_link_down_time = 0;1356 ri->auth_pass = NULL;1357 ri->auth_user = NULL;1358 ri->slave_priority = SENTINEL_DEFAULT_SLAVE_PRIORITY;1359 ri->replica_announced = 1;1360 ri->slave_reconf_sent_time = 0;1361 ri->slave_master_host = NULL;1362 ri->slave_master_port = 0;1363 ri->slave_master_link_status = SENTINEL_MASTER_LINK_STATUS_DOWN;1364 ri->slave_repl_offset = 0;1365 ri->sentinels = dictCreate(&instancesDictType);1366 ri->quorum = quorum;1367 ri->parallel_syncs = SENTINEL_DEFAULT_PARALLEL_SYNCS;1368 ri->master = master;1369 ri->slaves = dictCreate(&instancesDictType);1370 ri->info_refresh = 0;1371 ri->renamed_commands = dictCreate(&renamedCommandsDictType);13721373 /* Failover state. */1374 ri->leader = NULL;1375 ri->leader_epoch = 0;1376 ri->failover_epoch = 0;1377 ri->failover_state = SENTINEL_FAILOVER_STATE_NONE;1378 ri->failover_state_change_time = 0;1379 ri->failover_start_time = 0;1380 ri->failover_timeout = sentinel_default_failover_timeout;1381 ri->failover_delay_logged = 0;1382 ri->promoted_slave = NULL;1383 ri->notification_script = NULL;1384 ri->client_reconfig_script = NULL;1385 ri->info = NULL;13861387 /* Role */1388 ri->role_reported = ri->flags & (SRI_MASTER|SRI_SLAVE);1389 ri->role_reported_time = mstime();1390 ri->slave_conf_change_time = mstime();13911392 /* Add into the right table. */1393 dictAdd(table, ri->name, ri);1394 return ri;1395}13961397/* Release this instance and all its slaves, sentinels, hiredis connections.1398 * This function does not take care of unlinking the instance from the main1399 * masters table (if it is a master) or from its master sentinels/slaves table1400 * if it is a slave or sentinel. */1401void releaseSentinelRedisInstance(sentinelRedisInstance *ri) {1402 /* Release all its slaves or sentinels if any. */1403 dictRelease(ri->sentinels);1404 dictRelease(ri->slaves);14051406 /* Disconnect the instance. */1407 releaseInstanceLink(ri->link,ri);14081409 /* Free other resources. */1410 sdsfree(ri->name);1411 sdsfree(ri->runid);1412 sdsfree(ri->notification_script);1413 sdsfree(ri->client_reconfig_script);1414 sdsfree(ri->slave_master_host);1415 sdsfree(ri->leader);1416 sdsfree(ri->auth_pass);1417 sdsfree(ri->auth_user);1418 sdsfree(ri->info);1419 releaseSentinelAddr(ri->addr);1420 dictRelease(ri->renamed_commands);14211422 /* Clear state into the master if needed. */1423 if ((ri->flags & SRI_SLAVE) && (ri->flags & SRI_PROMOTED) && ri->master)1424 ri->master->promoted_slave = NULL;14251426 zfree(ri);1427}14281429/* Lookup a slave in a master Redis instance, by ip and port. */1430sentinelRedisInstance *sentinelRedisInstanceLookupSlave(1431 sentinelRedisInstance *ri, char *slave_addr, int port)1432{1433 sds key;1434 sentinelRedisInstance *slave;1435 sentinelAddr *addr;14361437 serverAssert(ri->flags & SRI_MASTER);14381439 /* We need to handle a slave_addr that is potentially a hostname.1440 * If that is the case, depending on configuration we either resolve1441 * it and use the IP address or fail.1442 */1443 addr = createSentinelAddr(slave_addr, port, 0);1444 if (!addr) return NULL;1445 key = announceSentinelAddrAndPort(addr);1446 releaseSentinelAddr(addr);14471448 slave = dictFetchValue(ri->slaves,key);1449 sdsfree(key);1450 return slave;1451}14521453/* Return the name of the type of the instance as a string. */1454const char *sentinelRedisInstanceTypeStr(sentinelRedisInstance *ri) {1455 if (ri->flags & SRI_MASTER) return "master";1456 else if (ri->flags & SRI_SLAVE) return "slave";1457 else if (ri->flags & SRI_SENTINEL) return "sentinel";1458 else return "unknown";1459}14601461/* This function remove the Sentinel with the specified ID from the1462 * specified master.1463 *1464 * If "runid" is NULL the function returns ASAP.1465 *1466 * This function is useful because on Sentinels address switch, we want to1467 * remove our old entry and add a new one for the same ID but with the new1468 * address.1469 *1470 * The function returns 1 if the matching Sentinel was removed, otherwise1471 * 0 if there was no Sentinel with this ID. */1472int removeMatchingSentinelFromMaster(sentinelRedisInstance *master, char *runid) {1473 dictIterator di;1474 dictEntry *de;1475 int removed = 0;14761477 if (runid == NULL) return 0;14781479 dictInitSafeIterator(&di, master->sentinels);1480 while((de = dictNext(&di)) != NULL) {1481 sentinelRedisInstance *ri = dictGetVal(de);14821483 if (ri->runid && strcmp(ri->runid,runid) == 0) {1484 dictDelete(master->sentinels,ri->name);1485 removed++;1486 }1487 }1488 dictResetIterator(&di);1489 return removed;1490}14911492/* Search an instance with the same runid, ip and port into a dictionary1493 * of instances. Return NULL if not found, otherwise return the instance1494 * pointer.1495 *1496 * runid or addr can be NULL. In such a case the search is performed only1497 * by the non-NULL field. */1498sentinelRedisInstance *getSentinelRedisInstanceByAddrAndRunID(dict *instances, char *addr, int port, char *runid) {1499 dictIterator di;1500 dictEntry *de;1501 sentinelRedisInstance *instance = NULL;1502 sentinelAddr *ri_addr = NULL;15031504 serverAssert(addr || runid); /* User must pass at least one search param. */1505 if (addr != NULL) {1506 /* Try to resolve addr. If hostnames are used, we're accepting an ri_addr1507 * that contains an hostname only and can still be matched based on that.1508 */1509 ri_addr = createSentinelAddr(addr,port,1);1510 if (!ri_addr) return NULL;1511 }1512 dictInitIterator(&di, instances);1513 while((de = dictNext(&di)) != NULL) {1514 sentinelRedisInstance *ri = dictGetVal(de);15151516 if (runid && !ri->runid) continue;1517 if ((runid == NULL || strcmp(ri->runid, runid) == 0) &&1518 (addr == NULL || sentinelAddrOrHostnameEqual(ri->addr, ri_addr)))1519 {1520 instance = ri;1521 break;1522 }1523 }1524 dictResetIterator(&di);1525 if (ri_addr != NULL)1526 releaseSentinelAddr(ri_addr);15271528 return instance;1529}15301531/* Master lookup by name */1532sentinelRedisInstance *sentinelGetMasterByName(char *name) {1533 sentinelRedisInstance *ri;1534 sds sdsname = sdsnew(name);15351536 ri = dictFetchValue(sentinel.masters,sdsname);1537 sdsfree(sdsname);1538 return ri;1539}15401541/* Reset the state of a monitored master:1542 * 1) Remove all slaves.1543 * 2) Remove all sentinels.1544 * 3) Remove most of the flags resulting from runtime operations.1545 * 4) Reset timers to their default value. For example after a reset it will be1546 * possible to failover again the same master ASAP, without waiting the1547 * failover timeout delay.1548 * 5) In the process of doing this undo the failover if in progress.1549 * 6) Disconnect the connections with the master (will reconnect automatically).1550 */15511552#define SENTINEL_RESET_NO_SENTINELS (1<<0)1553void sentinelResetMaster(sentinelRedisInstance *ri, int flags) {1554 serverAssert(ri->flags & SRI_MASTER);1555 dictRelease(ri->slaves);1556 ri->slaves = dictCreate(&instancesDictType);1557 if (!(flags & SENTINEL_RESET_NO_SENTINELS)) {1558 dictRelease(ri->sentinels);1559 ri->sentinels = dictCreate(&instancesDictType);1560 }1561 instanceLinkCloseConnection(ri->link,ri->link->cc);1562 instanceLinkCloseConnection(ri->link,ri->link->pc);1563 ri->flags &= SRI_MASTER;1564 if (ri->leader) {1565 sdsfree(ri->leader);1566 ri->leader = NULL;1567 }1568 ri->failover_state = SENTINEL_FAILOVER_STATE_NONE;1569 ri->failover_state_change_time = 0;1570 ri->failover_start_time = 0; /* We can failover again ASAP. */1571 ri->promoted_slave = NULL;1572 sdsfree(ri->runid);1573 sdsfree(ri->slave_master_host);1574 ri->runid = NULL;1575 ri->slave_master_host = NULL;1576 ri->link->act_ping_time = mstime();1577 ri->link->last_ping_time = 0;1578 ri->link->last_avail_time = mstime();1579 ri->link->last_pong_time = mstime();1580 ri->role_reported_time = mstime();1581 ri->role_reported = SRI_MASTER;1582 if (flags & SENTINEL_GENERATE_EVENT)1583 sentinelEvent(LL_WARNING,"+reset-master",ri,"%@");1584}15851586/* Call sentinelResetMaster() on every master with a name matching the specified1587 * pattern. */1588int sentinelResetMastersByPattern(char *pattern, int flags) {1589 dictIterator di;1590 dictEntry *de;1591 int reset = 0;15921593 dictInitIterator(&di, sentinel.masters);1594 while((de = dictNext(&di)) != NULL) {1595 sentinelRedisInstance *ri = dictGetVal(de);15961597 if (ri->name) {1598 if (stringmatch(pattern,ri->name,0)) {1599 sentinelResetMaster(ri,flags);1600 reset++;1601 }1602 }1603 }1604 dictResetIterator(&di);1605 return reset;1606}16071608/* Reset the specified master with sentinelResetMaster(), and also change1609 * the ip:port address, but take the name of the instance unmodified.1610 *1611 * This is used to handle the +switch-master event.1612 *1613 * The function returns C_ERR if the address can't be resolved for some1614 * reason. Otherwise C_OK is returned. */1615int sentinelResetMasterAndChangeAddress(sentinelRedisInstance *master, char *hostname, int port) {1616 sentinelAddr *oldaddr, *newaddr;1617 sentinelAddr **slaves = NULL;1618 int numslaves = 0, j;1619 dictIterator di;1620 dictEntry *de;16211622 newaddr = createSentinelAddr(hostname,port,0);1623 if (newaddr == NULL) return C_ERR;16241625 /* There can be only 0 or 1 slave that has the newaddr.1626 * and It can add old master 1 more slave. 1627 * so It allocates dictSize(master->slaves) + 1 */1628 slaves = zmalloc(sizeof(sentinelAddr*)*(dictSize(master->slaves) + 1));1629 1630 /* Don't include the one having the address we are switching to. */1631 dictInitIterator(&di, master->slaves);1632 while((de = dictNext(&di)) != NULL) {1633 sentinelRedisInstance *slave = dictGetVal(de);16341635 if (sentinelAddrOrHostnameEqual(slave->addr,newaddr)) continue;1636 slaves[numslaves++] = dupSentinelAddr(slave->addr);1637 }1638 dictResetIterator(&di);16391640 /* If we are switching to a different address, include the old address1641 * as a slave as well, so that we'll be able to sense / reconfigure1642 * the old master. */1643 if (!sentinelAddrOrHostnameEqual(newaddr,master->addr)) {1644 slaves[numslaves++] = dupSentinelAddr(master->addr);1645 }16461647 /* Reset and switch address. */1648 sentinelResetMaster(master,SENTINEL_RESET_NO_SENTINELS);1649 oldaddr = master->addr;1650 master->addr = newaddr;1651 master->o_down_since_time = 0;1652 master->s_down_since_time = 0;16531654 /* Add slaves back. */1655 for (j = 0; j < numslaves; j++) {1656 sentinelRedisInstance *slave;16571658 slave = createSentinelRedisInstance(NULL,SRI_SLAVE,slaves[j]->hostname,1659 slaves[j]->port, master->quorum, master);1660 releaseSentinelAddr(slaves[j]);1661 if (slave) sentinelEvent(LL_NOTICE,"+slave",slave,"%@");1662 }1663 zfree(slaves);16641665 /* Release the old address at the end so we are safe even if the function1666 * gets the master->addr->ip and master->addr->port as arguments. */1667 releaseSentinelAddr(oldaddr);1668 sentinelFlushConfig();1669 return C_OK;1670}16711672/* Return non-zero if there was no SDOWN or ODOWN error associated to this1673 * instance in the latest 'ms' milliseconds. */1674int sentinelRedisInstanceNoDownFor(sentinelRedisInstance *ri, mstime_t ms) {1675 mstime_t most_recent;16761677 most_recent = ri->s_down_since_time;1678 if (ri->o_down_since_time > most_recent)1679 most_recent = ri->o_down_since_time;1680 return most_recent == 0 || (mstime() - most_recent) > ms;1681}16821683/* Return the current master address, that is, its address or the address1684 * of the promoted slave if already operational. */1685sentinelAddr *sentinelGetCurrentMasterAddress(sentinelRedisInstance *master) {1686 /* If we are failing over the master, and the state is already1687 * SENTINEL_FAILOVER_STATE_RECONF_SLAVES or greater, it means that we1688 * already have the new configuration epoch in the master, and the1689 * slave acknowledged the configuration switch. Advertise the new1690 * address. */1691 if ((master->flags & SRI_FAILOVER_IN_PROGRESS) &&1692 master->promoted_slave &&1693 master->failover_state >= SENTINEL_FAILOVER_STATE_RECONF_SLAVES)1694 {1695 return master->promoted_slave->addr;1696 } else {1697 return master->addr;1698 }1699}17001701/* This function sets the down_after_period field value in 'master' to all1702 * the slaves and sentinel instances connected to this master. */1703void sentinelPropagateDownAfterPeriod(sentinelRedisInstance *master) {1704 dictIterator di;1705 dictEntry *de;1706 int j;1707 dict *d[] = {master->slaves, master->sentinels, NULL};17081709 for (j = 0; d[j]; j++) {1710 dictInitIterator(&di, d[j]);1711 while((de = dictNext(&di)) != NULL) {1712 sentinelRedisInstance *ri = dictGetVal(de);1713 ri->down_after_period = master->down_after_period;1714 }1715 dictResetIterator(&di);1716 }1717}17181719/* This function is used in order to send commands to Redis instances: the1720 * commands we send from Sentinel may be renamed, a common case is a master1721 * with CONFIG and SLAVEOF commands renamed for security concerns. In that1722 * case we check the ri->renamed_command table (or if the instance is a slave,1723 * we check the one of the master), and map the command that we should send1724 * to the set of renamed commands. However, if the command was not renamed,1725 * we just return "command" itself. */1726char *sentinelInstanceMapCommand(sentinelRedisInstance *ri, char *command) {1727 sds sc = sdsnew(command);1728 if (ri->master) ri = ri->master;1729 char *retval = dictFetchValue(ri->renamed_commands, sc);1730 sdsfree(sc);1731 return retval ? retval : command;1732}17331734/* ============================ Config handling ============================= */17351736/* Generalise handling create instance error. Use SRI_MASTER, SRI_SLAVE or1737 * SRI_SENTINEL as a role value. */1738const char *sentinelCheckCreateInstanceErrors(int role) {1739 switch(errno) {1740 case EBUSY:1741 switch (role) {1742 case SRI_MASTER:1743 return "Duplicate master name.";1744 case SRI_SLAVE:1745 return "Duplicate hostname and port for replica.";1746 case SRI_SENTINEL:1747 return "Duplicate runid for sentinel.";1748 default:1749 serverAssert(0);1750 break;1751 }1752 break;1753 case ENOENT:1754 return "Can't resolve instance hostname.";1755 case EINVAL:1756 return "Invalid port number.";1757 default:1758 return "Unknown Error for creating instances.";1759 }1760}17611762/* init function for server.sentinel_config */1763void initializeSentinelConfig(void) {1764 server.sentinel_config = zmalloc(sizeof(struct sentinelConfig));1765 server.sentinel_config->monitor_cfg = listCreate();1766 server.sentinel_config->pre_monitor_cfg = listCreate();1767 server.sentinel_config->post_monitor_cfg = listCreate();1768 listSetFreeMethod(server.sentinel_config->monitor_cfg,freeSentinelLoadQueueEntry);1769 listSetFreeMethod(server.sentinel_config->pre_monitor_cfg,freeSentinelLoadQueueEntry);1770 listSetFreeMethod(server.sentinel_config->post_monitor_cfg,freeSentinelLoadQueueEntry);1771}17721773/* destroy function for server.sentinel_config */1774void freeSentinelConfig(void) {1775 /* release these three config queues since we will not use it anymore */1776 listRelease(server.sentinel_config->pre_monitor_cfg);1777 listRelease(server.sentinel_config->monitor_cfg);1778 listRelease(server.sentinel_config->post_monitor_cfg);1779 zfree(server.sentinel_config);1780 server.sentinel_config = NULL;1781}17821783/* Search config name in pre monitor config name array, return 1 if found,1784 * 0 if not found. */1785int searchPreMonitorCfgName(const char *name) {1786 for (unsigned int i = 0; i < sizeof(preMonitorCfgName)/sizeof(preMonitorCfgName[0]); i++) {1787 if (!strcasecmp(preMonitorCfgName[i],name)) return 1;1788 }1789 return 0;1790}17911792/* free method for sentinelLoadQueueEntry when release the list */1793void freeSentinelLoadQueueEntry(void *item) {1794 struct sentinelLoadQueueEntry *entry = item;1795 sdsfreesplitres(entry->argv,entry->argc);1796 sdsfree(entry->line);1797 zfree(entry);1798}17991800/* This function is used for queuing sentinel configuration, the main1801 * purpose of this function is to delay parsing the sentinel config option1802 * in order to avoid the order dependent issue from the config. */1803void queueSentinelConfig(sds *argv, int argc, int linenum, sds line) {1804 int i;1805 struct sentinelLoadQueueEntry *entry;18061807 /* initialize sentinel_config for the first call */1808 if (server.sentinel_config == NULL) initializeSentinelConfig();18091810 entry = zmalloc(sizeof(struct sentinelLoadQueueEntry));1811 entry->argv = zmalloc(sizeof(char*)*argc);1812 entry->argc = argc;1813 entry->linenum = linenum;1814 entry->line = sdsdup(line);1815 for (i = 0; i < argc; i++) {1816 entry->argv[i] = sdsdup(argv[i]);1817 }1818 /* Separate config lines with pre monitor config, monitor config and1819 * post monitor config, in order to parsing config dependencies1820 * correctly. */1821 if (!strcasecmp(argv[0],"monitor")) {1822 listAddNodeTail(server.sentinel_config->monitor_cfg,entry);1823 } else if (searchPreMonitorCfgName(argv[0])) {1824 listAddNodeTail(server.sentinel_config->pre_monitor_cfg,entry);1825 } else{1826 listAddNodeTail(server.sentinel_config->post_monitor_cfg,entry);1827 }1828}18291830/* This function is used for loading the sentinel configuration from1831 * pre_monitor_cfg, monitor_cfg and post_monitor_cfg list */1832void loadSentinelConfigFromQueue(void) {1833 const char *err = NULL;1834 listIter li;1835 listNode *ln;1836 int linenum = 0;1837 sds line = NULL;1838 unsigned int j;18391840 /* if there is no sentinel_config entry, we can return immediately */1841 if (server.sentinel_config == NULL) return;18421843 list *sentinel_configs[3] = {1844 server.sentinel_config->pre_monitor_cfg,1845 server.sentinel_config->monitor_cfg,1846 server.sentinel_config->post_monitor_cfg1847 };1848 /* loading from pre monitor config queue first to avoid dependency issues1849 * loading from monitor config queue1850 * loading from the post monitor config queue */1851 for (j = 0; j < sizeof(sentinel_configs) / sizeof(sentinel_configs[0]); j++) {1852 listRewind(sentinel_configs[j],&li);1853 while((ln = listNext(&li))) {1854 struct sentinelLoadQueueEntry *entry = ln->value;1855 err = sentinelHandleConfiguration(entry->argv,entry->argc);1856 if (err) {1857 linenum = entry->linenum;1858 line = entry->line;1859 goto loaderr;1860 }1861 }1862 }18631864 /* free sentinel_config when config loading is finished */1865 freeSentinelConfig();1866 return;18671868loaderr:1869 fprintf(stderr, "\n*** FATAL CONFIG FILE ERROR (Redis %s) ***\n",1870 REDIS_VERSION);1871 fprintf(stderr, "Reading the configuration file, at line %d\n", linenum);1872 fprintf(stderr, ">>> '%s'\n", line);1873 fprintf(stderr, "%s\n", err);1874 exit(1);1875}18761877const char *sentinelHandleConfiguration(char **argv, int argc) {18781879 sentinelRedisInstance *ri;18801881 if (!strcasecmp(argv[0],"monitor") && argc == 5) {1882 /* monitor <name> <host> <port> <quorum> */1883 int quorum = atoi(argv[4]);18841885 if (quorum <= 0) return "Quorum must be 1 or greater.";1886 if (createSentinelRedisInstance(argv[1],SRI_MASTER,argv[2],1887 atoi(argv[3]),quorum,NULL) == NULL)1888 {1889 return sentinelCheckCreateInstanceErrors(SRI_MASTER);1890 }1891 } else if (!strcasecmp(argv[0],"down-after-milliseconds") && argc == 3) {1892 /* down-after-milliseconds <name> <milliseconds> */1893 ri = sentinelGetMasterByName(argv[1]);1894 if (!ri) return "No such master with specified name.";1895 ri->down_after_period = atoi(argv[2]);1896 if (ri->down_after_period <= 0)1897 return "negative or zero time parameter.";1898 sentinelPropagateDownAfterPeriod(ri);1899 } else if (!strcasecmp(argv[0],"failover-timeout") && argc == 3) {1900 /* failover-timeout <name> <milliseconds> */1901 ri = sentinelGetMasterByName(argv[1]);1902 if (!ri) return "No such master with specified name.";1903 ri->failover_timeout = atoi(argv[2]);1904 if (ri->failover_timeout <= 0)1905 return "negative or zero time parameter.";1906 } else if (!strcasecmp(argv[0],"parallel-syncs") && argc == 3) {1907 /* parallel-syncs <name> <milliseconds> */1908 ri = sentinelGetMasterByName(argv[1]);1909 if (!ri) return "No such master with specified name.";1910 ri->parallel_syncs = atoi(argv[2]);1911 } else if (!strcasecmp(argv[0],"notification-script") && argc == 3) {1912 /* notification-script <name> <path> */1913 ri = sentinelGetMasterByName(argv[1]);1914 if (!ri) return "No such master with specified name.";1915 if (access(argv[2],X_OK) == -1)1916 return "Notification script seems non existing or non executable.";1917 ri->notification_script = sdsnew(argv[2]);1918 } else if (!strcasecmp(argv[0],"client-reconfig-script") && argc == 3) {1919 /* client-reconfig-script <name> <path> */1920 ri = sentinelGetMasterByName(argv[1]);1921 if (!ri) return "No such master with specified name.";1922 if (access(argv[2],X_OK) == -1)1923 return "Client reconfiguration script seems non existing or "1924 "non executable.";1925 ri->client_reconfig_script = sdsnew(argv[2]);1926 } else if (!strcasecmp(argv[0],"auth-pass") && argc == 3) {1927 /* auth-pass <name> <password> */1928 ri = sentinelGetMasterByName(argv[1]);1929 if (!ri) return "No such master with specified name.";1930 ri->auth_pass = sdsnew(argv[2]);1931 } else if (!strcasecmp(argv[0],"auth-user") && argc == 3) {1932 /* auth-user <name> <username> */1933 ri = sentinelGetMasterByName(argv[1]);1934 if (!ri) return "No such master with specified name.";1935 ri->auth_user = sdsnew(argv[2]);1936 } else if (!strcasecmp(argv[0],"current-epoch") && argc == 2) {1937 /* current-epoch <epoch> */1938 unsigned long long current_epoch = strtoull(argv[1],NULL,10);1939 if (current_epoch > sentinel.current_epoch)1940 sentinel.current_epoch = current_epoch;1941 } else if (!strcasecmp(argv[0],"myid") && argc == 2) {1942 if (strlen(argv[1]) != CONFIG_RUN_ID_SIZE)1943 return "Malformed Sentinel id in myid option.";1944 memcpy(sentinel.myid,argv[1],CONFIG_RUN_ID_SIZE);1945 } else if (!strcasecmp(argv[0],"config-epoch") && argc == 3) {1946 /* config-epoch <name> <epoch> */1947 ri = sentinelGetMasterByName(argv[1]);1948 if (!ri) return "No such master with specified name.";1949 ri->config_epoch = strtoull(argv[2],NULL,10);1950 /* The following update of current_epoch is not really useful as1951 * now the current epoch is persisted on the config file, but1952 * we leave this check here for redundancy. */1953 if (ri->config_epoch > sentinel.current_epoch)1954 sentinel.current_epoch = ri->config_epoch;1955 } else if (!strcasecmp(argv[0],"leader-epoch") && argc == 3) {1956 /* leader-epoch <name> <epoch> */1957 ri = sentinelGetMasterByName(argv[1]);1958 if (!ri) return "No such master with specified name.";1959 ri->leader_epoch = strtoull(argv[2],NULL,10);1960 } else if ((!strcasecmp(argv[0],"known-slave") ||1961 !strcasecmp(argv[0],"known-replica")) && argc == 4)1962 {1963 sentinelRedisInstance *slave;19641965 /* known-replica <name> <ip> <port> */1966 ri = sentinelGetMasterByName(argv[1]);1967 if (!ri) return "No such master with specified name.";1968 if ((slave = createSentinelRedisInstance(NULL,SRI_SLAVE,argv[2],1969 atoi(argv[3]), ri->quorum, ri)) == NULL)1970 {1971 return sentinelCheckCreateInstanceErrors(SRI_SLAVE);1972 }1973 } else if (!strcasecmp(argv[0],"known-sentinel") &&1974 (argc == 4 || argc == 5)) {1975 sentinelRedisInstance *si;19761977 if (argc == 5) { /* Ignore the old form without runid. */1978 /* known-sentinel <name> <ip> <port> [runid] */1979 ri = sentinelGetMasterByName(argv[1]);1980 if (!ri) return "No such master with specified name.";1981 if ((si = createSentinelRedisInstance(argv[4],SRI_SENTINEL,argv[2],1982 atoi(argv[3]), ri->quorum, ri)) == NULL)1983 {1984 return sentinelCheckCreateInstanceErrors(SRI_SENTINEL);1985 }1986 si->runid = sdsnew(argv[4]);1987 sentinelTryConnectionSharing(si);1988 }1989 } else if (!strcasecmp(argv[0],"rename-command") && argc == 4) {1990 /* rename-command <name> <command> <renamed-command> */1991 ri = sentinelGetMasterByName(argv[1]);1992 if (!ri) return "No such master with specified name.";1993 sds oldcmd = sdsnew(argv[2]);1994 sds newcmd = sdsnew(argv[3]);1995 if (dictAdd(ri->renamed_commands,oldcmd,newcmd) != DICT_OK) {1996 sdsfree(oldcmd);1997 sdsfree(newcmd);1998 return "Same command renamed multiple times with rename-command.";1999 }2000 } else if (!strcasecmp(argv[0],"announce-ip") && argc == 2) {
Findings
✓ No findings reported for this file.