摘要:本系列通过作者对Redis Sentinel源码的理解,详细说明Sentinel的代码实现方式。

Redis Sentinel 是Redis提供的高可用模型解决方案。Sentinel可以自动监测一个或多个Redis主备实例,并在主实例宕机的情况下自动实行主备倒换。本系列通过作者对Redis Sentinel源码的理解,详细说明Sentinel的代码实现方式。

Sentinel使用Redis内核相同的事件驱动代码框架, 但Sentinel有自己独特的初始化步骤。在这篇文章里,作者会介绍Sentinel与Redis服务器不同的初始化部分。

我们可以通过redis-sentinel <path-to-configfile> 或者 redis-server <path-to-configfile> --sentinel 这两种方式启动并运行Sentinel实例,这两种方式是等价的。在Redis server.c 的main函数中,我们会看到Redis如何判断用户指定以Sentinel方式运行的逻辑:

int main(int argc, char **argv) {
..........
server.sentinel_mode = checkForSentinelMode(argc,argv);
..........
}

其中checkForSentinelMode函数会监测以下两种条件:

1. 程序使用redis-sentinel可执行文件执行。

2. 程序参数列表中有--sentinel 标志。

以上任何一种条件成立则Redis会使用Sentinel的方式运行。

/* Returns 1 if there is --sentinel among the arguments or if 

 * argv[0] contains "redis-sentinel". */ 

int checkForSentinelMode(int argc, char **argv) { 

      int j; 

       if (strstr(argv[0],"redis-sentinel") != NULL) return 1; 

       for (j = 1; j < argc; j++)
if (!strcmp(argv[j],"--sentinel")) return 1; return 0; }

在Redis 判断是否以Sentinel的方式运行以后,我们会看到如下代码段:

int main(int argc, char **argv) {
struct timeval tv;
int j; ............
/* We need to init sentinel right now as parsing the configuration file
* in sentinel mode will have the effect of populating the sentinel
* data structures with master nodes to monitor. */
if (server.sentinel_mode) {
initSentinelConfig();
initSentinel();
}
............

在initSentinelConfig函数中,会使用Sentinel特定的端口(默认为26379)来替代Redis的默认端口(6379)。另外,在Sentinel模式下,需要禁用服务器运行保护模式。

/* This function overwrites a few normal Redis config default with Sentinel
* specific defaults. */
void initSentinelConfig(void) {
server.port = REDIS_SENTINEL_PORT;
server.protected_mode = 0; /* Sentinel must be exposed. */
}

与此同时,initSentinel函数会做如下操作:

/* Perform the Sentinel mode initialization. */
void initSentinel(void) {
unsigned int j; /* Remove usual Redis commands from the command table, then just add
* the SENTINEL command. */
dictEmpty(server.commands,NULL);
for (j = 0; j < sizeof(sentinelcmds)/sizeof(sentinelcmds[0]); j++) {
int retval;
struct redisCommand *cmd = sentinelcmds+j; retval = dictAdd(server.commands, sdsnew(cmd->name), cmd);
serverAssert(retval == DICT_OK); {"punsubscribe",punsubscribeCommand,-1,"",0,NULL,0,0,0,0,0},
{"publish",sentinelPublishCommand,3,"",0,NULL,0,0,0,0,0},
{"info",sentinelInfoCommand,-1,"",0,NULL,0,0,0,0,0},
{"role",sentinelRoleCommand,1,"ok-loading",0,NULL,0,0,0,0,0},
{"client",clientCommand,-2,"read-only no-script",0,NULL,0,0,0,0,0},
{"shutdown",shutdownCommand,-1,"",0,NULL,0,0,0,0,0},
{"auth",authCommand,2,"no-auth no-script ok-loading ok-stale fast",0,NULL,0,0,0,0,0},
{"hello",helloCommand,-2,"no-auth no-script fast",0,NULL,0,0,0,0,0}
};

2.初始化Sentinel主状态结构,Sentinel主状态的定义及注释如下。

/* Main state. */ 

struct sentinelState { 

 char myid[CONFIG_RUN_ID_SIZE+1]; /* This sentinel ID. */ 

 uint64_t current_epoch; /* Current epoch. */ 

 dict *masters; /* Dictionary of master sentinelRedisInstances. 

 Key is the instance name, value is the 

 sentinelRedisInstance structure pointer. */ 

 int tilt; /* Are we in TILT mode? */ 

 int running_scripts; /* Number of scripts in execution right now. */ 

 mstime_t tilt_start_time; /* When TITL started. */ 

 mstime_t previous_time; /* Last time we ran the time handler. */ 

 list *scripts_queue; /* Queue of user scripts to execute. */ 

 char *announce_ip; /* IP addr that is gossiped to other sentinels if 

 not NULL. */ 

 int announce_port; /* Port that is gossiped to other sentinels if 

 non zero. */ 

  unsigned long simfailure_flags; /* Failures simulation. */ 

 int deny_scripts_reconfig; /* Allow SENTINEL SET ... to change script 

 paths at runtime? */ 

} sentinel; 

其中masters字典指针中的每个值都对应着一个Sentinel检测的主实例。

在读取配置信息后,Redis服务器主函数会调用sentinelIsRunning函数, 做以下几个工作:

1. 检查配置文件是否被设置,并且检查程序对配置文件是否有写权限,因为如果Sentinel状态改变的话,会不断将自己当前状态记录在配置文件中。

2. 如果在配置文件中指定运行ID,Sentinel 会使用这个ID作为运行ID,相反地,如果没有指定运行ID,Sentinel会生成一个ID用来作为Sentinel的运行ID。

3. 对所有的Sentinel监测实例产生初始监测事件。

/* This function gets called when the server is in Sentinel mode, started,
* loaded the configuration, and is ready for normal operations. */
void sentinelIsRunning(void) {
int j; if (server.configfile == NULL) {
serverLog(LL_WARNING,
"Sentinel started without a config file. Exiting...");
exit(1);
} else if (access(server.configfile,W_OK) == -1) {
serverLog(LL_WARNING,
"Sentinel config file %s is not writable: %s. Exiting...",
server.configfile,strerror(errno));
exit(1);
} /* If this Sentinel has yet no ID set in the configuration file, we
* pick a random one and persist the config on disk. From now on this
* will be this Sentinel ID across restarts. */
for (j = 0; j < CONFIG_RUN_ID_SIZE; j++)
if (sentinel.myid[j] != 0) break; if (j == CONFIG_RUN_ID_SIZE) {
/* Pick ID and persist the config. */
getRandomHexChars(sentinel.myid,CONFIG_RUN_ID_SIZE);
sentinelFlushConfig();
} /* Log its ID to make debugging of issues simpler. */
serverLog(LL_WARNING,"Sentinel ID is %s", sentinel.myid); /* We want to generate a +monitor event for every configured master
* at startup. */
sentinelGenerateInitialMonitorEvents();
}

参考资料:

https://github.com/antirez/redis

https://redis.io/topics/sentinel

Redis设计与实现第二版 黄健宏著

本文分享自华为云社区《Redis Sentinel 源码分析(1)Sentinel的初始化》,原文作者:中间件小哥 。

点击关注,第一时间了解华为云新鲜技术~

一文带你探究Sentinel的独特初始化的更多相关文章

  1. JDBC、ORM、JPA、Spring Data JPA,傻傻分不清楚?一文带你厘清个中曲直,给你个选择SpringDataJPA的理由!

    序言 Spring Data JPA作为Spring Data中对于关系型数据库支持的一种框架技术,属于ORM的一种,通过得当的使用,可以大大简化开发过程中对于数据操作的复杂度. 本文档隶属于< ...

  2. Istio是啥?一文带你彻底了解!

    原标题:Istio是啥?一文带你彻底了解! " 如果你比较关注新兴技术的话,那么很可能在不同的地方听说过 Istio,并且知道它和 Service Mesh 有着牵扯. 这篇文章可以作为了解 ...

  3. 一文带您了解5G的价值与应用

    一文带您了解5G的价值与应用 5G最有趣的一点是:大多数产品都是先有明确应用场景而后千呼万唤始出来.而5G则不同,即将到来的5G不仅再一次印证了科学技术是第一生产力还给不少用户带来了迷茫——我们为什么 ...

  4. 一文带你了解elasticsearch

    一文带你了解elasticsearch cxf2102100人评论160人阅读2019-07-02 21:31:36   elasticsearch es基本概念 es术语介绍 文档Document ...

  5. 【转帖】Istio是啥?一文带你彻底了解!

    Istio是啥?一文带你彻底了解! http://www.sohu.com/a/270131876_463994 原始位置来源: https://cizixs.com 如果你比较关注新兴技术的话,那么 ...

  6. 一文带你了解 C# DLR 的世界

    一文带你了解 C# DLR 的世界 在很久之前,我写了一片文章dynamic结合匿名类型 匿名对象传参,里面我以为DLR内部是用反射实现的.因为那时候是心中想当然的认为只有反射能够在运行时解析对象的成 ...

  7. 一文带你看清HTTP所有概念(转)

    一文带你看清HTTP所有概念   上一篇文章我们大致讲解了一下 HTTP 的基本特征和使用,大家反响很不错,那么本篇文章我们就来深究一下 HTTP 的特性.我们接着上篇文章没有说完的 HTTP 标头继 ...

  8. 一文带你了解js数据储存及深复制(深拷贝)与浅复制(浅拷贝)

    背景 在日常开发中,偶尔会遇到需要复制对象的情况,需要进行对象的复制. 由于现在流行标题党,所以,一文带你了解js数据储存及深复制(深拷贝)与浅复制(浅拷贝) 理解 首先就需要理解 js 中的数据类型 ...

  9. 【项目实践】一文带你搞定Spring Security + JWT

    以项目驱动学习,以实践检验真知 前言 关于认证和授权,R之前已经写了两篇文章: [项目实践]在用安全框架前,我想先让你手撸一个登陆认证 [项目实践]一文带你搞定页面权限.按钮权限以及数据权限 在这两篇 ...

随机推荐

  1. JS复习之深浅拷贝

    一.复习导论(数据类型相关) 想掌握JS的深浅拷贝,首先来回顾一下JS的数据类型,JS中数据类型分为基本数据类型和引用数据类型. 基本数据类型是指存放在栈中的简单数据段,数据大小确定,内存空间大小可以 ...

  2. C++ 虚函数表与多态 —— 多态的简单用法

    首先看下边的代码,先创建一个父类,然后在来一个继承父类的子类,两个类中都有自己的 play() 方法,在代码的第35-37行,创建一个父类指针,然后将子类地址引用赋值给父类,这时调用 P 指针的 pl ...

  3. Day2 之 元组tuple

    tuple 元组    也是有序列表 ,与list非常相似,但是tuple一旦初始化就不能修改.        name = ('a','b',1,2,3,True)            tuple ...

  4. pip下载超时问题详解

    前言 pip下载的安装包都是在国外的pipy服务器上面,又因国内某种墙的策略,导致速度非常的慢,甚至无法访问. 于是国内很多的企业和爱好者纷纷搭建自己的服务器,定时从pypi上拉起所有的镜像文件.然后 ...

  5. Java后端使用socketio,实现小程序答题pk功能

    在使用socket.io跟前端通信过程中,出现了一系列问题,现做下记录. 一.功能需求是,在小程序端,用户可相互邀请,进入房间后进行答题PK.实现方法是,用户点击邀请好友,建立连接,查询当前是否有房间 ...

  6. python 连接数据库操作

    import mysql #打开数据库连接(用户名,密码,数据库名) db = mysql.connect("localhost","testuser",&qu ...

  7. vue第十六单元(element-ui vue-lazyload 等常用插件)

    第十六单元(element-ui vue-lazyload 等常用插件) #课程目标 1.掌握插件的引入方式 2.精通UI框架 3.掌握前端常见的几种效果实现 #知识点 一.elementUI的使用 ...

  8. 给小白整理的一篇Python知识点

    1.基本概念 1.1 四种类型 python中数有四种类型:整数.长整数.浮点数和复数. python中数有四种类型:整数.长整数.浮点数和复数. 整数, 如 1 长整数 是比较大的整数 浮点数 如 ...

  9. 转载:从输入 URL 到页面加载完的过程中都发生了什么事情?

    原帖地址:http://www.guokr.com/question/554991/ 1)把URL分割成几个部分:协议.网络地址.资源路径.其中网络地址指示该连接网络上哪一台计算机,可以是域名或者IP ...

  10. Java安全之Shiro 550反序列化漏洞分析

    Java安全之Shiro 550反序列化漏洞分析 首发自安全客:Java安全之Shiro 550反序列化漏洞分析 0x00 前言 在近些时间基本都能在一些渗透或者是攻防演练中看到Shiro的身影,也是 ...