MySQL · 源码分析 · SHUTDOWN过程

本文涉及的产品
RDS MySQL DuckDB 分析主实例,集群系列 4核8GB
RDS AI 助手,专业版
简介: ORACLE 中的SHUTDOWNMySQL SHUTDOWN LEVEL 暂时只有一种,源码中留了 LEVEL 的坑还没填在此借用 Oracle 的 SHUTDOWN LEVEL 分析Oracle SHUTDOWN LEVEL 共有四种:ABORT、IMMEDIATE、NORMAL、TRANSACTIONALABORT立即结束所有SQL 回滚未提交事务 断开所有用户连

ORACLE 中的SHUTDOWN

MySQL SHUTDOWN LEVEL 暂时只有一种,源码中留了 LEVEL 的坑还没填

在此借用 Oracle 的 SHUTDOWN LEVEL 分析

Oracle SHUTDOWN LEVEL 共有四种:ABORT、IMMEDIATE、NORMAL、TRANSACTIONAL

ABORT
  • 立即结束所有SQL
  • 回滚未提交事务
  • 断开所有用户连接
  • 下次启动实例时,需要recovery
IMMEDIATE
  • 允许正在运行的SQL执行完毕
  • 回滚未提交事务
  • 断开所有用户连接
NORMAL
  • 不允许建立新连接
  • 等待当前连接断开
  • 下次启动实例时,不需要recovery
TRANSACTIONAL
  • 等待事务提交或结束
  • 不允许新建连接
  • 事务提交或结束后断开连接

MySQL 中的 SHUTDOWN 实际相当于 Oracle 中的 SHUTDOWN IMMEDIATE,重启实例时无需recovery,但回滚事务的过程可能耗时很长

MySQL SHUTDOWN过程分析

  • mysql_shutdown 发送SHUTDOWN命令
  • dispatch_command() 接受到 COM_SHUTDOWN command,调用kill_mysql()
  • kill_mysql()创建 kill_server_thread
  • kill_server_thread 调用 kill_server()
  • kill_server()
    • close_connections()
      • 关闭端口
      • 断开连接
      • 回滚事务(可能耗时很长)
    • unireg_end
      • clean_up
        • innobase_shutdown_for_mysql
        • delete_pid_file

InnoDB shutdown 速度取决于参数 innodb_fast_shutdown

  • 0: 最慢,需等待purge完成,change buffer merge完成
  • 1: default, 不需要等待purge完成和change buffer merge完成
  • 2: 不等待后台删除表完成,row_drop_tables_for_mysql_in_background 不等刷脏页,如果设置了innodb_buffer_pool_dump_at_shutdown,不需要去buffer dump.
  case COM_SHUTDOWN: // 接受到SHUTDOWN命令
  {
    if (packet_length < 1)
    {    
      my_error(ER_MALFORMED_PACKET, MYF(0));
      break;
    }    
    status_var_increment(thd->status_var.com_other);
    if (check_global_access(thd,SHUTDOWN_ACL)) // 检查权限
      break; /* purecov: inspected */
    /*   
      If the client is < 4.1.3, it is going to send us no argument; then
      packet_length is 0, packet[0] is the end 0 of the packet. Note that
      SHUTDOWN_DEFAULT is 0. If client is >= 4.1.3, the shutdown level is in
      packet[0].
    */
    enum mysql_enum_shutdown_level level; // 留的坑,default以外的LEVEL都没实现
    if (!thd->is_valid_time())
      level= SHUTDOWN_DEFAULT;                                                                                                                                                                              
    else 
      level= (enum mysql_enum_shutdown_level) (uchar) packet[0];
    if (level == SHUTDOWN_DEFAULT)
      level= SHUTDOWN_WAIT_ALL_BUFFERS; // soon default will be configurable
    else if (level != SHUTDOWN_WAIT_ALL_BUFFERS)
    {    
      my_error(ER_NOT_SUPPORTED_YET, MYF(0), "this shutdown level");
      break;
    }    
    DBUG_PRINT("quit",("Got shutdown command for level %u", level));
    general_log_print(thd, command, NullS); // 记录general_log
    my_eof(thd);
    kill_mysql(); // 调用kill_mysql()函数,函数内部创建 kill_server_thread 线程
    error=TRUE;
    break;
  }
  

kill_server() 先调用 close_connections(),再调用 unireg_end()

static void __cdecl kill_server(int sig_ptr)
{
	......
	close_connections();
   	if (sig != MYSQL_KILL_SIGNAL &&
        sig != 0)                                      
      unireg_abort(1);        /* purecov: inspected */
    else
      unireg_end();

结束线程的主要逻辑在 mysqld.cc:close_connections() 中

  static void close_connections(void)

  	......
    
  /* 下面这段代码结束监听端口 */
  /* Abort listening to new connections */
  DBUG_PRINT("quit",("Closing sockets"));
  if (!opt_disable_networking )
  {
    if (mysql_socket_getfd(base_ip_sock) != INVALID_SOCKET)
    {
      (void) mysql_socket_shutdown(base_ip_sock, SHUT_RDWR);
      (void) mysql_socket_close(base_ip_sock);
      base_ip_sock= MYSQL_INVALID_SOCKET;
    }
    if (mysql_socket_getfd(extra_ip_sock) != INVALID_SOCKET)
    {
      (void) mysql_socket_shutdown(extra_ip_sock, SHUT_RDWR);
      (void) mysql_socket_close(extra_ip_sock);
      extra_ip_sock= MYSQL_INVALID_SOCKET;
    }
  }
  
  	......

  /* 第一遍遍历线程列表 */
  sql_print_information("Giving %d client threads a chance to die gracefully",
                        static_cast<int>(get_thread_count()));

  mysql_mutex_lock(&LOCK_thread_count);
  
  Thread_iterator it= global_thread_list->begin();
  for (; it != global_thread_list->end(); ++it)
  {
    THD *tmp= *it;
    DBUG_PRINT("quit",("Informing thread %ld that it's time to die",
                       tmp->thread_id));
    /* We skip slave threads & scheduler on this first loop through. */
    
    /* 跳过 slave 相关线程,到 end_server() 函数内处理 */
    if (tmp->slave_thread) 
      continue;
    if (tmp->get_command() == COM_BINLOG_DUMP ||
        tmp->get_command() == COM_BINLOG_DUMP_GTID)
    {
      ++dump_thread_count;
      continue;
    }
    
    /* 先标记为 KILL 给连接一个自我了断的机会 */
    tmp->killed= THD::KILL_CONNECTION;
    
    ......
    
  }
  mysql_mutex_unlock(&LOCK_thread_count);

  Events::deinit();

  sql_print_information("Shutting down slave threads");
  /* 此处断开 slave 相关线程 */
  end_slave();
  
  /* 第二遍遍历线程列表 */
  if (dump_thread_count)
  {                                                                                                                                                                                                         
    /*
      Replication dump thread should be terminated after the clients are
      terminated. Wait for few more seconds for other sessions to end.
     */
    while (get_thread_count() > dump_thread_count && dump_thread_kill_retries)
    {
      sleep(1);
      dump_thread_kill_retries--;
    }
    mysql_mutex_lock(&LOCK_thread_count);
    for (it= global_thread_list->begin(); it != global_thread_list->end(); ++it)
    {
      THD *tmp= *it;
      DBUG_PRINT("quit",("Informing dump thread %ld that it's time to die",
                         tmp->thread_id));
      if (tmp->get_command() == COM_BINLOG_DUMP ||
          tmp->get_command() == COM_BINLOG_DUMP_GTID)
      {
      	/* 关闭DUMP线程 */
        tmp->killed= THD::KILL_CONNECTION;
        
        ......
        
      }
    }
    mysql_mutex_unlock(&LOCK_thread_count);
  }
  
  ......
  
  /* 第三遍遍历线程列表 */
  for (it= global_thread_list->begin(); it != global_thread_list->end(); ++it)
  {
    THD *tmp= *it;
    if (tmp->vio_ok())
    {
      if (log_warnings)
        sql_print_warning(ER_DEFAULT(ER_FORCING_CLOSE),my_progname,
                          tmp->thread_id,
                          (tmp->main_security_ctx.user ?
                           tmp->main_security_ctx.user : ""));
      /* 关闭连接,不等待语句结束,但是要回滚未提交线程 */
      close_connection(tmp);
    }
  }
                                         

close_connection() 中调用 THD::disconnect() 断开连接
连接断开后开始回滚事务

bool do_command(THD *thd)
{
	......
	packet_length= my_net_read(net); // thd->disconnect() 后此处直接返回
	......                        
}

void do_handle_one_connection(THD *thd_arg)
{
	......
	while (thd_is_connection_alive(thd))
	{
  		if (do_command(thd)) //do_command 返回 error,跳出循环
  			break;
	}
    end_connection(thd);
 
end_thread:
    close_connection(thd);
    /* 此处调用one_thread_per_connection_end() */
    if (MYSQL_CALLBACK_ELSE(thd->scheduler, end_thread, (thd, 1), 0))
      return;                                 // Probably no-threads


	......
}

事务回滚调用链

trans_rollback(THD*) ()
THD::cleanup() ()
THD::release_resources() ()
one_thread_per_connection_end(THD*, bool) ()
do_handle_one_connection(THD*) ()
handle_one_connection ()

unireg_end 调用 clean_up()

void clean_up(bool print_message)
{
	/* 这里是一些释放内存和锁的操作 */	
 	......
 	
 	/*
 		这里调用 innobase_shutdown_for_mysql
 		purge all			(innodb_fast_shutdown = 0)
 		merge change buffer	(innodb_fast_shutdown = 0)
 		flush dirty page	(innodb_fast_shutdown = 0,1)
 		flush log buffer
 		都在这里面做 
 	*/
  plugin_shutdown();
  
  /* 这里是一些释放内存和锁的操作 */
  ......
  
  /* 
  	删除 pid 文件,删除后 mysqld_safe不会重启 mysqld,
  	不然会认为 mysqld crash,尝试重启
  */
  delete_pid_file(MYF(0));
  
  /* 这里是一些释放内存和锁的操作 */
  ......
                                                                                                                                                                                       

innodb shutdown 分析

innodb shutdown 的主要操作在 logs_empty_and_mark_files_at_shutdown() 中

  • 等待后台线程结束
    • srv_error_monitor_thread
    • srv_lock_timeout_thread
    • srv_monitor_thread
    • buf_dump_thread
    • dict_stats_thread
  • 等待所有事物结束 trx_sys_any_active_transactions
  • 等待后台线程结束
    • worker threads: srv_worker_thread
    • master thread: srv_master_thread
    • purge thread: srv_purge_coordinator_thread
  • 等待 buf_flush_lru_manager_thread 结束
  • 等待 buf_flush_page_cleaner_thread 结束
  • 等待 Pending checkpoint_writes, Pending log flush writes 结束
  • 等待 buffer pool pending io 结束
  • if (innodb_fast_shutdown == 2)
    • flush log buffer 后 return
  • log_make_checkpoint_at
    • flush buffer pool
    • write checkpoint
  • 将 lsn 落盘 fil_write_flushed_lsn_to_data_files()
  • 关闭所有文件

logs_empty_and_mark_files_at_shutdown() 结束后,innobase_shutdown_for_mysql() 再做一些资源清理工作即结束 shutdown 过程

相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
目录
相关文章
|
SQL 自然语言处理 关系型数据库
MySQL · 源码分析 · 词法分析及其性能优化
Table of Contents 1. 简介 2. 背景知识 3. 查找树的实现 3.1. 树的查找 3.2. 树的产生 4. 试试折半查找 5. 总结 简介 MySQL 支持标准的 SQL 语言,具体实现的时候必然要涉及到词法分析和语法分析。早期的程序可能会优先考虑手工实现词法分析和语法分析,现在大多数场合下都会采用工具来简化实现。MySQL、PostgreSQL 等
9132 0
|
人工智能 自然语言处理 搜索推荐
[AI Mem0 Platform] 快速开始,为您的AI应用注入长期记忆和个性化能力!
[AI Mem0 Platform] 快速开始,为您的AI应用注入长期记忆和个性化能力!
1187 0
|
Python
工序时间
工序时间是指在生产过程中,完成一个工序所需的时间。在制造业中,工序时间是一个重要的参数,它可以帮助企业了解生产效率、优化生产流程、制定生产计划等。
400 1
|
消息中间件 Kafka Shell
Docker安装kafka
Docker安装kafka
4206 0
|
MySQL 关系型数据库 内存技术
MySQL · 新特性分析 · CTE执行过程与实现原理
众所周知,Common table expression(CTE)是在大多数的关系型数据库里都存在的特性,包括ORACLE, SQLSERVER,POSTGRESQL等,唯独开源数据库老大MySQL缺失。CTE作为一个方便用户使用的功能,原本是可以利用普通的SQL语句替代的,但是对于复杂的CTE来说,要模拟出CTE的效果还是需要很大的功夫。如果考虑性能那就更是难上加难了。2013年Guilhem
4501 1
|
存储 关系型数据库 数据库
MySQL · 引擎特性 · Infobright 列存数据库
简介 系统架构 存储引擎 优化器和执行器 数据装载和卸载 领域知识 查询优化 简单场景的示例 小结 存储结构 Data Pack Knowledge Node 数据压缩 总结 简介 Infobright 是一个面向 OLAP 场景的开源列
4332 0
|
JSON 关系型数据库 MySQL
MySQL · 最佳实践 · 如何索引JSON字段
概述 MySQL从5.7.8起开始支持JSON字段,这极大的丰富了MySQL的数据类型。也方便了广大开发人员。但MySQL并没有提供对JSON对象中的字段进行索引的功能,至少没有直接对其字段进行索引的方法。
13615 0
|
关系型数据库 MySQL
MYSQL · 新特性 · MySQL 8.0对Parser所做的改进
背景介绍 众所周知,MySQL Parser是利用C/C++实现的开源yacc/lex组合,也就是 GNU bison/flex。Flex负责生成tokens, Bison负责语法解析。开始介绍MySQL 8.0的新特新之前,我们先简单了解一下通用的两种Parser。一种是Bottom-up parser,另外一种是Top-down parser。 Bottom-up parser Bottom
2703 0
|
关系型数据库 MySQL 索引
MySQL · 捉虫动态 · order by limit 造成优化器选择索引错误
问题描述 bug 触发条件如下: 优化器先选择了 where 条件中字段的索引,该索引过滤性较好; SQL 中必须有 order by limit 从而引导优化器尝试使用 order by 字段上的索引进行优化,最终因代价问题没有成功。 复现case 表结构 create table t
8387 0

相关产品

  • 云数据库 RDS MySQL 版