惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
Google Developers Blog
Google DeepMind News
Google DeepMind News
Hugging Face - Blog
Hugging Face - Blog
D
Docker
F
Fortinet All Blogs
博客园 - 三生石上(FineUI控件)
Project Zero
Project Zero
Engineering at Meta
Engineering at Meta
J
Java Code Geeks
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Simon Willison's Weblog
Simon Willison's Weblog
S
Security Affairs
NISL@THU
NISL@THU
T
Tor Project blog
A
About on SuperTechFans
宝玉的分享
宝玉的分享
腾讯CDC
S
Schneier on Security
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
P
Privacy & Cybersecurity Law Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Stack Overflow Blog
Stack Overflow Blog
P
Privacy International News Feed
雷峰网
雷峰网
C
Cyber Attacks, Cyber Crime and Cyber Security
Vercel News
Vercel News
Cisco Talos Blog
Cisco Talos Blog
D
DataBreaches.Net
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Google Online Security Blog
Google Online Security Blog
Recorded Future
Recorded Future
L
LINUX DO - 热门话题
Microsoft Security Blog
Microsoft Security Blog
Latest news
Latest news
C
Check Point Blog
有赞技术团队
有赞技术团队
T
The Exploit Database - CXSecurity.com
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
云风的 BLOG
云风的 BLOG
SecWiki News
SecWiki News
Application and Cybersecurity Blog
Application and Cybersecurity Blog
爱范儿
爱范儿
月光博客
月光博客
V
Vulnerabilities – Threatpost
T
Threat Research - Cisco Blogs
P
Palo Alto Networks Blog
T
The Blog of Author Tim Ferriss
C
Cisco Blogs
Webroot Blog
Webroot Blog
S
Security @ Cisco Blogs

祈雨的笔记

安全多方计算MPC spark原理解析 kueue执行源码分析 spark on k8s执行源码分析 spark-operator源码解析 系统压测遇到的缓存击穿问题 我的世界PC与安卓联机 蚂蚁金服流量投放平台的AIG改造 G1大对象致Old区占用率高 日志打印导致接口响应率下跌分析 Groovy加载类导致OOM分析 ERROR日志打印导致CPU满载 记OceanBase死锁超时 应用发版期间服务响应超时 Ark Serverless初探 系统优化复盘一二三 The user specified as a definer does not exist Kong网关初探 API网关选型调研 CPU火焰图常用工具 配置中心选型调研 root操作Nginx导致用户组错误 基于Proxifier使用代理 FastJSON字段智能匹配踩坑 Nacos初探 记一次Nginx服务器CPU满荷载故障 基于券系统分库分表的思考 limit不参与SQL成本计算致索引失效 Linux常用性能监控命令 golang低版本http2偶现400 hostname in certificate didn't match 常见对称加密原理以及应用 tcp_tw_recycle引起的TCP握手失败 记一次mysql执行DDL导致锁表 mysql磁盘占用查看 mysql对text字段update致磁盘增长 elasticsearch报错index read-only TIME_WAIT与Http的Keep-Alive 记一次TIME_WAIT导致连接数报警 记一次生产事故OOM问题排查 redis分布式锁RedissonLock的实现细节 webservice复杂加密签名(2)java调用 webservice复杂加密签名(1)SoapUI mysql延时关联 利用中间人拦截实现APP内H5窜改 MySQL表字符集不同导致关联查询索引失效 通过SSH隧道远程办公 数据落盘方案 BeanDefinitionRegistryPostProcessor扩展 mysql空间索引 HTTPS攻击 spring循环依赖过程解析 elasticsearch性能优化 mysql IS NULL 使用索引 mysql字符集utf8mb4失效踩坑 常用加密算法 xml与javaBean转换 mysql索引原理 redis之list源码分析 redis之key过期源码分析 redis之string源码分析 redis之hash源码分析 线程池之ThreadPoolExecutor mysql数据页结构 Using temporary与Using filesort mysql回表致索引失效 springboot(28)HTTP连接池 定时任务之ScheduledThreadPoolExecutor elasticsearch常用script聚合 elasticsearch实现like查询 elasticsearch实现乐观锁 elasticsearch准实时原理 springboot(27)自定义缓存读写机制CachingConfigurerSupport optimizer tracing arthas常用命令 HTTP和HTTPS详解 redis集群选举机制 kafka消息重试 一点压力测试的经验 kafka架构概念 explain分析sql语句字段的解释 JVM问题分析处理手册 logstash过滤器(2)date logstash过滤器(3)dissect logstash编码器(1)json logstash编码器(2)multiline logstash表达式 logstash输入(1)通用选项 logstash输入(3)file logstash过滤器(1)通用选项 logstash输入(2)stdin logstash安装 记一次前端vConsole导致JSON序列化错误排查 解决多个异步操作嵌套问题 fastjson反序列化失败autoType is not support RTMP串流服务 POI自动调整列宽错误 Nginx+Lua实现动态黑名单 使用curl命令模拟POST和GET请求 ResponseEntity下载文件
初探InnoDB MVCC源码实现
祈雨的笔记 · 2019-08-03 · via 祈雨的笔记

转载自博客园本文链接地址: 初探InnoDB MVCC源码实现

1. 背景

本文基于MySQL InnoDB源码对InnoDB中非锁定一致性读是如何实现的作一些简单的探究。

2. 基本概念

2.1 隐藏字段

在经典之作《高性能MySQL》的1.4节中提及了MySQL中MVCC的实现,原著中提及了

InnoDB implements MVCC by storing with each row two additional, hidden values that record when the row was created and when it was expired (or deleted). Rather than storing the actual times at which these events occurred, the row stores the system version number at the time each event occurred. This is a number that increments each time a transaction begins. Each transaction keeps its own record of the current system version, as of the time it began. Each query has to check each row’s version numbers against the transaction’s version.

我们知道InnoDB中聚簇索引包含了数据行的完整信息,《高性能MySQL》这里说的就是在InnoDB的聚簇索引中的行包含了行记录何时被创建以及何时被删除的信息。《高性能MySQL》这里的描述或许是为了方便读者理解。实际上聚簇索引中的行包含了两个隐藏的字段信息:

  • DATA_TRX_ID 6字节 最新一个对某记录增删改的事务id
  • DATA_ROLL_PTR 7字节 回滚指针

关于这里信息可以参考storage/innobase/include/data0type.h头文件。

而对于二级索引记录,是不包含上面这两个隐藏字段信息的,但对于二级索引,会在页中会记录一个PAGE_MAX_TRX_ID,表示对该页数据修改过的最大事务id。

关于这里的信息可以参考storage/innobase/include/page0page.h头文件。

2.2 Read View

Read View保存了某一时刻活跃读写事务的快照信息,用来判断某个一致性读是否可见其它事务对表的修改。

其被定义在read0types.h头文件中,下面来看一下其中部分字段:

1
2
3
4
5
6
7
8
9
10
11

trx_id_t m_low_limit_id;


trx_id_t m_up_limit_id;


trx_id_t m_creator_trx_id;


ids_t m_ids;

在InnoDB的事务定义(参考trx0trx.h头文件)中包含了一个字段用来表示该事务的Read View。

1
ReadView*   read_view;

在InnoDB进行进行一致性读时,会判断当前事务的Read View是否存在,如果不存在则get一个新的Read View(InnoDB对于Read View有复用的机制,所以如果不存在可以复用的Read View对象才会去显示地new一个新的出来)。下面是trx_assign_read_view方法实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
ReadView*
trx_assign_read_view(

trx_t* trx)
{
ut_ad(trx->state == TRX_STATE_ACTIVE);

if (srv_read_only_mode) {

ut_ad(trx->read_view == NULL);
return(NULL);

} else if (!MVCC::is_view_active(trx->read_view)) {
trx_sys->mvcc->view_open(trx->read_view, trx);
}

return(trx->read_view);
}

下面再来看一下Read View是如何初始化的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
void
ReadView::prepare(trx_id_t id)
{
ut_ad(mutex_own(&trx_sys->mutex));

m_creator_trx_id = id;


m_low_limit_no = m_low_limit_id = trx_sys->max_trx_id;


if (!trx_sys->rw_trx_ids.empty()) {
copy_trx_ids(trx_sys->rw_trx_ids);
} else {
m_ids.clear();
}



if (UT_LIST_GET_LEN(trx_sys->serialisation_list) > 0) {
const trx_t* trx;

trx = UT_LIST_GET_FIRST(trx_sys->serialisation_list);

if (trx->no < m_low_limit_no) {
m_low_limit_no = trx->no;
}
}
}

void
ReadView::complete()
{

m_up_limit_id = !m_ids.empty() ? m_ids.front() : m_low_limit_id;

ut_ad(m_up_limit_id <= m_low_limit_id);

m_closed = false;
}

对于Read Committed的隔离级别,在一致性读语句结束后,会关闭掉Read View,而对于Repeatable Read的隔离级别,Read View在创建后会一直到事务结束时才被关闭。

Read View如何判断可见性

上面已经对Read View进行了大致介绍,下面就来看一下InnoDB是如何判断记录是否对当前事务可见的吧。这里的入口是storage/innobase/row/row0sel.ccrow_search_mvcc方法。

3.1 走聚簇索引的情况

假设sql查询走的是聚簇索引,则通过下面的lock_clust_rec_cons_read_sees方法来判断记录rec是否对当前事务可见。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
bool
lock_clust_rec_cons_read_sees(
const rec_t* rec,
dict_index_t* index,
const ulint* offsets,
ReadView* view)
{
ut_ad(dict_index_is_clust(index));
ut_ad(page_rec_is_user_rec(rec));
ut_ad(rec_offs_validate(rec, index, offsets));


if (srv_read_only_mode || dict_table_is_temporary(index->table)) {
ut_ad(view == 0 || dict_table_is_temporary(index->table));
return(true);
}



trx_id_t trx_id = row_get_rec_trx_id(rec, index, offsets);


return(view->changes_visible(t

下面再来看看ReadView::changes_visible方法的实现源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
bool changes_visible(
trx_id_t id,
const table_name_t& name) const
MY_ATTRIBUTE((warn_unused_result))
{
ut_ad(id > 0);


if (id < m_up_limit_id || id == m_creator_trx_id) {

return(true);
}

check_trx_id_sanity(id, name);


if (id >= m_low_limit_id) {

return(false);

} else if (m_ids.empty()) {

return(true);
}

const ids_t::value_type* p = m_ids.data();


return(!std::binary_search(p, p + m_ids.size(), id));
}

理一下这里判断的依据

  • 记录的事务id为m_creator_trx_id即当前事务的修改,一定可见。
  • 记录的事务id<m_up_limit_id,说明Read View在初始化的时候,修改此记录的事务已经提交了,因此可见。
  • 记录的事务id>=m_low_limit_id,说明Read View在初始化的时候,修改改记录的事务还没开启(准确说是还没被分配到事务id),因此不可见。

如果这里不满足的话,会走到row_sel_build_prev_vers_for_mysql->row_vers_build_for_consistent_read的调用,根据回滚段中的信息不断构建前一个版本信息直至当前事务可见。

3.2 走二级索引的情况

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
bool
lock_sec_rec_cons_read_sees(
const rec_t* rec,
const dict_index_t* index,
const ReadView* view)
{
ut_ad(page_rec_is_user_rec(rec));

if (recv_recovery_is_on()) {
return(false);
} else if (dict_table_is_temporary(index->table)) {
return(true);
}

trx_id_t max_trx_id = page_get_max_trx_id(page_align(rec));

ut_ad(max_trx_id > 0);

return(view->sees(max_trx_id));
}

下面是ReadView:sees的实现,可以看到其实就是判断是否PAGE_MAX_TRX_ID小于ReadView初始化时的最小事务id,也就是判断修改页上记录的最大事务id是否在快照生成的时候已经提交了,简单粗暴的很。

1
2
3
4
bool sees(trx_id_t id) const
{
return(id < m_up_limit_id);
}

因此这里lock_sec_rec_cons_read_sees方法如果返回true,那么是一定可见的,返回false的话未必不可见,但下一步就需要利用聚簇索引来获取可见版本的数据了。
在这之前InnoDB会先利用ICP(Index Push Down)根据索引信息来判断搜索条件是否满足,如果不满足那也没必要再去聚簇索引中取了;若ICP判断出符合条件,则会走到row_sel_get_clust_rec_for_mysql方法中去聚簇索引中取可见版本数据。

4. 总结

本文通过InnoDB源码,介绍了Read View的基本数据结构和概念以及InnoDB中是如何通过创建的Read View来判断可见性。实际上Read View就是一个活跃事务的快照,并且RC和RR隔离级别都复用了同样结构的Read View来判断可见性,不同的是Read View的生命周期根据相应的隔离级别而有所不同。对于不可见的修改,InnoDB通过undo信息重建之前版本的数据直至数据可见。

5. 参考

MySQL官方手册

数据库内核月报