Redis设计与实现 笔记 第十五章 复制

复制

在 Redis 中,可以用一台服务器来复制另一台服务器的数据,复制的服务器称为从服务器,被复制的服务器称为主服务器.

这一概念也就是我们时常会看到的主从服务器概念,主从服务器可以用来负载均衡,进行定时的备份,用来保持数据库的安全性和维持高效.

Redis 通过

SLAVEOF ip port

进行主从服务器的配置.

进行主从配置之后,从服务器将完全和主服务器一样,保持完全的一致性.

主服务器在接收到对应的命令时,也会分发给从服务器.

15.1 旧版复制功能的实现

Redis 复制功能分为同步和命令传播两个操作.
同步指的是将主服务器所有的数据同步至从服务器
命令传播用于在主服务器被修改后,主从数据库不一致时,进行命令的后续传播,来达到一致性的目的

15.1.1 同步

当客户端发注 SLAVEOF 命令时,要求复制主数据库的内容审, 从服务器需要向主服务器发送 SYNC 命令来执行:
1): 从服务器向主服务器发送 SYNC 命令.
2): 收到 SYNC 命令的主服务器 执行 BGSAVE 命令,生成 RDB 文件,并使用一个缓冲区记录所有在RDB生成之后的命令.
3): 主服务器 RDB 文件生成完毕之后会将这个文件发送给从服务器,从服务器进行一个数据的恢复
4): 再将生成后的命令发给从服务器,完成同步状态

15.1.2 命令传播

当主从服务器同步完成之后,主服务器再接受到命令,会转发一份至从服务器,从而达到两个服务器的一致.
当从服务器接收到非主服务器的修改命令后,会不执行.

15.2 旧版复制功能的缺陷

旧版的功能在断线后的复制上有一定的缺陷:

在断线之后,旧版会重新执行一次复制功能,即使只是断线一小会,但是,整个RDB都会被重新生成,重新同步,虽然这样也能恢复一致的状态,但是没有效率.

考虑这样一个情况,当服务器中有1000W条数据时,从服务断线了1秒,中间只修改了2条数据,那当从服务器重连之后, 主服务器需要将1000W多条数据重新生成RDB进行一个同步,只为了2条不同的数据.做法完全不合理

SYNC 命令是一个非常耗费资源的操作, 主服务器收到 SYNC 命令之后,会使用 BGSAVE 来进行一个 RDB 文件的生成,是非常消耗 CPU,内存,IO的.

15.3 新版复制功能的实现

通过对旧版功能复制的分析,我们可以得出结论, 当从服务器短暂断线之后,我们还是直接进行全同步,这样是不合理的.
所以, 新版复制在原先的基础上多出了一个部分重同步功能.
也就是将同步操作分为了 全同步和部分同步.

其中全同步与原先方案一致.
在部分同步时候将作出一些优化.
首先, PSYNC 表示需要执行一次部分同步,主服务器收到 PSYNC 命令时,会将从服务器和主服务器之间的差异命令进行一个同步,这样就大大提高了效率.

15.4 部分同步的实现

部分同步由以下三部分组成:
1): 主服务器的复制偏移量和从服务器的复制偏移量
2): 主服务器的复制积压缓冲器.
3): 服务器的运行ID

15.4.1 复制偏移量
// 从服务器上记录的主服务器的复制偏移量
long long reploff;      /* replication offset if this is our master */

//主服务器上的复制偏移量
// 全局复制偏移量(一个累计值)
long long master_repl_offset;   /* Global replication offset */


通过偏移量,类似于版本号的概念,来确定主从服务器各自所处的状态.

偏移量由主服务器控制,每进行一次传播就进行+1操作
每次传播,从服务器也会将记录的偏移量更新成一致

15.4.2 主服务器的复制积压缓冲器

通过偏移量,我们可以找到从服务器缺失的命令条数,接下来我们就需要能找到缺失的命令内容.
内容的维护是通过一个固定长度先进先出的队列完成的.

// backlog 本身
char *repl_backlog;             /* Replication backlog for partial syncs */
// backlog 的长度
long long repl_backlog_size;    /* Backlog circular buffer size */
// backlog 中数据的长度
long long repl_backlog_histlen; /* Backlog actual data length */
// backlog 的当前索引
long long repl_backlog_idx;     /* Backlog circular buffer current offset */
// backlog 中可以被还原的第一个字节的偏移量
long long repl_backlog_off;     /* Replication offset of first byte in the
                                   backlog buffer. */
// backlog 的过期时间
time_t repl_backlog_time_limit; /* Time without slaves after the backlog
                                   gets released. */

通过这些数据结构,就可以拿出部分同步的内容,进行部分同步操作.

当然主服务器的记录条数是需要配置的,也不可能将所有的命令都进行一个保存操作,通过

repl-backlog-size

选项进行配置

15.4.3 服务器运行ID

当多个从服务器进行连接时,又同时 收到他们收到的 PSYNC 命令,该如何进行区分使用全同步和部分同步.

所以在发送 PSYNC 的时候需要传入一个 run ID, 主服务器在收到 runid后会进行一个记录,后续再收到,就知道需要进行全同步或部分同步.

但是个人觉得这好像好像不是必须的, PSYNC 传一个特殊值不就可以了,从服务器是知道自己是需要全同步或部分同步的,当一个全新的从服务器,他的偏移量不就是 0 吗,当主服务器手动 0 的偏移量,就可以确定进行全同步了. 应该是我没想想到特殊的场景.

后续补充,如果从服务器不小心切换了主服务器,那么单纯的用偏移量将无法进行判断,可能会造成错误的同步

15.5 PSYNC 命令的实现

了解 PSYNC 命令的完整细节:

从服务器发起的复制请求, 所以,分为两种情况
1): 如果从服务器之前没有进行同步,将发送

PSYNC ? -1

客户端接收到后会进行全同步

2): 如果从服务器之前进行过全同步,将发送

PSYNC <runid> <offset>

根据情况,主服务器可能会有以下三种回复结果:
1): 如果主服务器返回 +FULLRESYNC 则表示主服务器会进行完整同步
2): 如果主服务器返回 +CONTINUE 则表示主服务器会进行部分同步
3): 如果主服务器返回来 -ERR 回复,则表示主服务器版本低于 2.8, 无法进行 PSYNC 的识别,从服务器需要发送 SYNC 进行全同步

15.6 复制的实现

后续内容将同步详细描述复制的过程.

15.6.1 步骤1: 设置主服务器的地址和端口

当从服务器接受到 SLAVEOF 的命令时候,进行命令表中对应函数的调用.

void slaveofCommand(redisClient *c) {
    /* SLAVEOF is not allowed in cluster mode as replication is automatically
     * configured using the current address of the master node. */
    // 不允许在集群模式中使用
    if (server.cluster_enabled) {
        addReplyError(c,"SLAVEOF not allowed in cluster mode.");
        return;
    }

    /* The special host/port combination "NO" "ONE" turns the instance
     * into a master. Otherwise the new master address is set. */
    // SLAVEOF NO ONE 让从服务器转为主服务器
    if (!strcasecmp(c->argv[1]->ptr,"no") &&
        !strcasecmp(c->argv[2]->ptr,"one")) {
        if (server.masterhost) {
            // 让服务器取消复制,成为主服务器
            replicationUnsetMaster();
            redisLog(REDIS_NOTICE,"MASTER MODE enabled (user request)");
        }
    } else {
        long port;

        // 获取端口参数
        if ((getLongFromObjectOrReply(c, c->argv[2], &port, NULL) != REDIS_OK))
            return;

        /* Check if we are already attached to the specified slave */
        // 检查输入的 host 和 port 是否服务器目前的主服务器
        // 如果是的话,向客户端返回 +OK ,不做其他动作
        if (server.masterhost && !strcasecmp(server.masterhost,c->argv[1]->ptr)
            && server.masterport == port) {
            redisLog(REDIS_NOTICE,"SLAVE OF would result into synchronization with the master we are already connected with. No operation performed.");
            addReplySds(c,sdsnew("+OK Already connected to specified master\r\n"));
            return;
        }

        /* There was no previous master or the user specified a different one,
         * we can continue. */
        // 没有前任主服务器,或者客户端指定了新的主服务器
        // 开始执行复制操作
        replicationSetMaster(c->argv[1]->ptr, port);
        redisLog(REDIS_NOTICE,"SLAVE OF %s:%d enabled (user request)",
            server.masterhost, server.masterport);
    }
    addReply(c,shared.ok);
}

主要通过 replicationSetMaster 函数来配置主服务器的地址和端口

    /* Replication (slave) */
    // 主服务器的验证密码
    char *masterauth;               /* AUTH with this password with master */
    // 主服务器的地址
    char *masterhost;               /* Hostname of master */
    // 主服务器的端口
    int masterport;                 /* Port of master */

在最后进行连接状态的改变


    // 进入连接状态(重点)
    server.repl_state = REDIS_REPL_CONNECT;
    server.master_repl_offset = 0;
    server.repl_down_since = 0;
步骤2: 建立套接字连接

在 serverCron 的延伸函数中,进行服务器连接的尝试

    /* Check if we should connect to a MASTER */
    // 尝试连接主服务器
    if (server.repl_state == REDIS_REPL_CONNECT) {
        redisLog(REDIS_NOTICE,"Connecting to MASTER %s:%d",
            server.masterhost, server.masterport);
        if (connectWithMaster() == REDIS_OK) {
            redisLog(REDIS_NOTICE,"MASTER <-> SLAVE sync started");
        }
    }

连接上主服务器,并进行一个监听,继续修改连接状态

// 以非阻塞方式连接主服务器
int connectWithMaster(void) {
    int fd;

    // 连接主服务器
    fd = anetTcpNonBlockConnect(NULL,server.masterhost,server.masterport);
    if (fd == -1) {
        redisLog(REDIS_WARNING,"Unable to connect to MASTER: %s",
            strerror(errno));
        return REDIS_ERR;
    }

    // 监听主服务器 fd 的读和写事件,并绑定文件事件处理器
    if (aeCreateFileEvent(server.el,fd,AE_READABLE|AE_WRITABLE,syncWithMaster,NULL) ==
            AE_ERR)
    {
        close(fd);
        redisLog(REDIS_WARNING,"Can't create readable event for SYNC");
        return REDIS_ERR;
    }

    // 初始化统计变量
    server.repl_transfer_lastio = server.unixtime;
    server.repl_transfer_s = fd;

    // 将状态改为已连接
    server.repl_state = REDIS_REPL_CONNECTING;

    return REDIS_OK;
}

此时主从服务器的关系就很微妙了, 各自是对方的客户端,可以进行命令的传输

步骤3: 发送PING命令

在下一次循环中,向主服务器进行一个网络的再确认,可以通过该动作进行主服务目前读写状态的判断.

    /* If we were connecting, it's time to send a non blocking PING, we want to
     * make sure the master is able to reply before going into the actual
     * replication process where we have long timeouts in the order of
     * seconds (in the meantime the slave would block). */
    // 如果状态为 CONNECTING ,那么在进行初次同步之前,
    // 向主服务器发送一个非阻塞的 PONG 
    // 因为接下来的 RDB 文件发送非常耗时,所以我们想确认主服务器真的能访问
    if (server.repl_state == REDIS_REPL_CONNECTING) {
        redisLog(REDIS_NOTICE,"Non blocking connect for SYNC fired the event.");
        /* Delete the writable event so that the readable event remains
         * registered and we can wait for the PONG reply. */
        // 手动发送同步 PING ,暂时取消监听写事件
        aeDeleteFileEvent(server.el,fd,AE_WRITABLE);
        // 更新状态
        server.repl_state = REDIS_REPL_RECEIVE_PONG;
        /* Send the PING, don't check for errors at all, we have the timeout
         * that will take care about this. */
        // 同步发送 PING
        syncWrite(fd,"PING\r\n",6,100);

        // 返回,等待 PONG 到达
        return;
    }

客户端在收到 ping 命令后会回复一个 pong 给从服务器,表示当前读写状态无碍.

void pingCommand(redisClient *c) {
    addReply(c,shared.pong);
}

从服务器处理 pong 命令

    /* Receive the PONG command. */
    // 接收 PONG 命令
    if (server.repl_state == REDIS_REPL_RECEIVE_PONG) {
        char buf[1024];

        /* Delete the readable event, we no longer need it now that there is
         * the PING reply to read. */
        // 手动同步接收 PONG ,暂时取消监听读事件
        aeDeleteFileEvent(server.el,fd,AE_READABLE);

        /* Read the reply with explicit timeout. */
        // 尝试在指定时间限制内读取 PONG
        buf[0] = '\0';
        // 同步接收 PONG
        if (syncReadLine(fd,buf,sizeof(buf),
            server.repl_syncio_timeout*1000) == -1)
        {
            redisLog(REDIS_WARNING,
                "I/O error reading PING reply from master: %s",
                strerror(errno));
            goto error;
        }

    }
15.6.4 步骤4:身份验证

由于套接字创建的时,我们绑定了可读处理器,所以后续的处理会在下面函数上运行

// 从服务器用于同步主服务器的回调函数
void syncWithMaster(aeEventLoop *el, int fd, void *privdata, int mask);


        /* We accept only two replies as valid, a positive +PONG reply
         * (we just check for "+") or an authentication error.
         * Note that older versions of Redis replied with "operation not
         * permitted" instead of using a proper error code, so we test
         * both. */
        // 接收到的数据只有两种可能:
        // 第一种是 +PONG ,第二种是因为未验证而出现的 -NOAUTH 错误
        if (buf[0] != '+' &&
            strncmp(buf,"-NOAUTH",7) != 0 &&
            strncmp(buf,"-ERR operation not permitted",28) != 0)
        {
            // 接收到未验证错误
            redisLog(REDIS_WARNING,"Error reply to PING from master: '%s'",buf);
            goto error;
        } else {
            // 接收到 PONG
            redisLog(REDIS_NOTICE,
                "Master replied to PING, replication can continue...");
        }

    /* AUTH with the master if required. */
    // 进行身份验证
    if(server.masterauth) {
        err = sendSynchronousCommand(fd,"AUTH",server.masterauth,NULL);
        if (err[0] == '-') {
            redisLog(REDIS_WARNING,"Unable to AUTH to MASTER: %s",err);
            sdsfree(err);
            goto error;
        }
        sdsfree(err);
    }

进行一个身份验证.
身法验证规则如下:
1): 如果从主服务器都没有进行身份验证的配置,将通过
2): 如果主服务器进行了身法验证的配置,但是从服务器没有提交自己的信息,将无法通过验证
3): 如果从服务器提交了自己的信息,但实际上主服务器没有进行配置,那么也无法通过

15.6.5 步骤5: 发送端口信息

在完成上述步骤之后,从服务器将进行端口信息的发送,主服务器收到命令之后,会将端口号记录在从服务器对应的客户端对象上 slave_listening_port 属性中

    /* Set the slave port, so that Master's INFO command can list the
     * slave listening port correctly. */
    // 将从服务器的端口发送给主服务器,
    // 使得主服务器的 INFO 命令可以显示从服务器正在监听的端口
    {
        sds port = sdsfromlonglong(server.port);
        err = sendSynchronousCommand(fd,"REPLCONF","listening-port",port,
                                         NULL);
        sdsfree(port);
        /* Ignore the error if any, not all the Redis versions support
         * REPLCONF listening-port. */
        if (err[0] == '-') {
            redisLog(REDIS_NOTICE,"(Non critical) Master does not understand REPLCONF listening-port: %s", err);
        }
        sdsfree(err);
    }
15.6.6 步骤6:同步

这里我们终于将进行一个同步动作,
由函数 slaveTryPartialResynchronization 来确定当前是进行部分同步还是全同步,再通过设置读取处理器来进行 同步文件的读取,

aeCreateFileEvent(server.el,fd, AE_READABLE,readSyncBulkPayload,NULL)
/* Try a partial resynchonization. If we don't have a cached master
     * slaveTryPartialResynchronization() will at least try to use PSYNC
     * to start a full resynchronization so that we get the master run id
     * and the global offset, to try a partial resync at the next
     * reconnection attempt. */
    // 根据返回的结果决定是执行部分 resync ,还是 full-resync
    psync_result = slaveTryPartialResynchronization(fd);

    // 可以执行部分 resync
    if (psync_result == PSYNC_CONTINUE) {
        redisLog(REDIS_NOTICE, "MASTER <-> SLAVE sync: Master accepted a Partial Resynchronization.");
        // 返回
        return;
    }

    /* Fall back to SYNC if needed. Otherwise psync_result == PSYNC_FULLRESYNC
     * and the server.repl_master_runid and repl_master_initial_offset are
     * already populated. */
    // 主服务器不支持 PSYNC ,发送 SYNC
    if (psync_result == PSYNC_NOT_SUPPORTED) {
        redisLog(REDIS_NOTICE,"Retrying with SYNC...");
        // 向主服务器发送 SYNC 命令
        if (syncWrite(fd,"SYNC\r\n",6,server.repl_syncio_timeout*1000) == -1) {
            redisLog(REDIS_WARNING,"I/O error writing to MASTER: %s",
                strerror(errno));
            goto error;
        }
    }

    // 如果执行到这里,
    // 那么 psync_result == PSYNC_FULLRESYNC 或 PSYNC_NOT_SUPPORTED

    /* Prepare a suitable temp file for bulk transfer */
    // 打开一个临时文件,用于写入和保存接下来从主服务器传来的 RDB 文件数据
    while(maxtries--) {
        snprintf(tmpfile,256,
            "temp-%d.%ld.rdb",(int)server.unixtime,(long int)getpid());
        dfd = open(tmpfile,O_CREAT|O_WRONLY|O_EXCL,0644);
        if (dfd != -1) break;
        sleep(1);
    }
    if (dfd == -1) {
        redisLog(REDIS_WARNING,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno));
        goto error;
    }

    /* Setup the non blocking download of the bulk file. */
    // 设置一个读事件处理器,来读取主服务器的 RDB 文件
    if (aeCreateFileEvent(server.el,fd, AE_READABLE,readSyncBulkPayload,NULL)
            == AE_ERR)
    {
        redisLog(REDIS_WARNING,
            "Can't create readable event for SYNC: %s (fd=%d)",
            strerror(errno),fd);
        goto error;
    }

    // 设置状态
    server.repl_state = REDIS_REPL_TRANSFER;

    // 更新统计信息
    server.repl_transfer_size = -1;
    server.repl_transfer_read = 0;
    server.repl_transfer_last_fsync_off = 0;
    server.repl_transfer_fd = dfd;
    server.repl_transfer_lastio = server.unixtime;
    server.repl_transfer_tmpfile = zstrdup(tmpfile);
15.6.7 命令传播

当完成同步之后,主服务器就会进入命令传播阶段,此时主服务器将自己执行的写命令发送给从服务器,而从服务器只要一直接受,就完成了一致性的需求

void call(redisClient *c, int flags) ;
void propagate(struct redisCommand *cmd, int dbid, robj **argv, int argc,
               int flags)
{
    // 传播到 AOF
    if (server.aof_state != REDIS_AOF_OFF && flags & REDIS_PROPAGATE_AOF)
        feedAppendOnlyFile(cmd,dbid,argv,argc);

    // 传播到 slave
    if (flags & REDIS_PROPAGATE_REPL)
        replicationFeedSlaves(server.slaves,dbid,argv,argc);
}
15.7 心跳检测

每秒都会用

REPLCONF ACK <offset>

来向主服务器发送命令

    /* Send ACK to master from time to time.
     * Note that we do not send periodic acks to masters that don't
     * support PSYNC and replication offsets. */
    // 定期向主服务器发送 ACK 命令
    // 不过如果主服务器带有 REDIS_PRE_PSYNC 的话就不发送
    // 因为带有该标识的版本为 < 2.8 的版本,这些版本不支持 ACK 命令
    if (server.masterhost && server.master &&
        !(server.master->flags & REDIS_PRE_PSYNC))
        replicationSendAck();

心跳检测的作用如下:
1): 检测主从服务器的网络连接状态
2): 辅助实现 min-slaves 选项
3): 检测命令丢失

15.7.1 检测主从服务器的网络连接状态

通过

INFO replication 

命令,我们可以查看 slave 中的 lag 值,一般情况下, lag 的值会在0和1之间,如果超过1秒,表示出现了问题.

15.7.2 辅助实现了 min-salves 配置选项
// 是否开启最小数量从服务器写入功能
int repl_min_slaves_to_write;   /* Min number of slaves to write. */
// 定义最小数量从服务器的最大延迟值
int repl_min_slaves_max_lag;    /* Max lag of <count> slaves to write. */

当进行下面设置时

min_slaves_to_write 3
min_slaves_max_lag  10

在服务器数量少于3个时,或者3个服务器延迟大于或等于10秒时,主服务器将拒绝执行命令

15.7.3 检测命令丢失

如果因为网络故障,主服务器没有同步命令到从服务器,通过心跳机制可以及时知晓和比较主从服务器偏移量,也可以及时检测到命令丢失情况.当发生丢失,将进行部分同步

15.8 总结

1): Redis 2.8 后才添加了部分同步功能
2): 部分同步通过复制偏移量,复制积压缓冲区,服务器运行ID三个部分实现
3): 在复制操作开始的时,从服务器会作为主服务器的客户端,并通过主服务器发送命令来执行复制步骤,而在复制操作的后期,主从服务器都互相称为对方的客户端.
4):主服务器通过命令传播来保持主从服务器的一致,从服务器会用心跳检测来进行命令丢失检测.

经过这么多章节的学习,以及代码的追踪已经对 Redis 的设计,以及代码的执行流程有一点的概念了,在进行本章学习和代码阅读时,能通过代码的跳转来进行自己的猜想并进行验证,也是件让人愉悦的事情.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值