当前位置: 代码网 > it编程>数据库>Mysql > MySQL 优化利器 SHOW PROFILE 的实现原理及细节展示

MySQL 优化利器 SHOW PROFILE 的实现原理及细节展示

2024年12月24日 Mysql 我要评论
背景最近碰到一个 case,通过可传输表空间的方式导入一个 4gb 大小的表,耗时 13 分钟。通过profile定位,发现大部分耗时竟然是在system lock阶段。mysql> set p

背景

最近碰到一个 case,通过可传输表空间的方式导入一个 4gb 大小的表,耗时 13 分钟。

通过profile定位,发现大部分耗时竟然是在system lock阶段。

mysql> set profiling=1;
query ok, 0 rows affected, 1 warning (0.00 sec)
mysql> alter table sbtest2 import tablespace;
query ok, 0 rows affected (13 min 8.99 sec)
mysql> show profile for query 1;
+--------------------------------+------------+
| status                         | duration   |
+--------------------------------+------------+
| starting                       |   0.000119 |
| executing hook on transaction  |   0.000004 |
| starting                       |   0.000055 |
| checking permissions           |   0.000010 |
| discard_or_import_tablespace   |   0.000007 |
| opening tables                 |   0.000156 |
| system lock                    | 788.966338 |
| end                            |   0.007391 |
| waiting for handler commit     |   0.000041 |
| waiting for handler commit     |   0.011179 |
| query end                      |   0.000022 |
| closing tables                 |   0.000019 |
| waiting for handler commit     |   0.000031 |
| freeing items                  |   0.000035 |
| cleaning up                    |   0.000043 |
+--------------------------------+------------+
15 rows in set, 1 warning (0.03 sec)

不仅如此,sql 在执行的过程中,show processlist中的状态显示的也是system lock

mysql> show processlist;
+----+-----------------+-----------+--------+---------+------+------------------------+---------------------------------------+
| id | user            | host      | db     | command | time | state                  | info                                  |
+----+-----------------+-----------+--------+---------+------+------------------------+---------------------------------------+
|  5 | event_scheduler | localhost | null   | daemon  |  818 | waiting on empty queue | null                                  |
| 10 | root            | localhost | sbtest | query   |  648 | system lock            | alter table sbtest2 import tablespace |
| 14 | root            | localhost | null   | query   |    0 | init                   | show processlist                      |
+----+-----------------+-----------+--------+---------+------+------------------------+---------------------------------------+
3 rows in set, 1 warning (0.00 sec)

这个状态其实有很大的误导性。

接下来我们从show profile的基本用法出发,从源码角度分析它的实现原理。

最后在分析的基础上,看看 case 中的表空间导入操作为什么大部分耗时是在system lock阶段。

show profile 的基本用法

下面通过一个示例来看看show profile的用法。

# 开启 profiling
mysql> set profiling=1;
query ok, 0 rows affected, 1 warning (0.00 sec)
# 执行需要分析的 sql
mysql> select count(*) from slowtech.t1;
+----------+
| count(*) |
+----------+
|  1048576 |
+----------+
1 row in set (1.09 sec)
# 通过 show profiles 查看 sql 对应的 query_id
mysql> show profiles;
+----------+------------+----------------------------------+
| query_id | duration   | query                            |
+----------+------------+----------------------------------+
|        1 | 1.09378600 | select count(*) from slowtech.t1 |
+----------+------------+----------------------------------+
1 row in set, 1 warning (0.00 sec)
# 查看该 sql 各个阶段的执行耗时情况,其中,1 是该 sql 对应的 query_id
mysql> show profile for query 1;
+--------------------------------+----------+
| status                         | duration |
+--------------------------------+----------+
| starting                       | 0.000157 |
| executing hook on transaction  | 0.000009 |
| starting                       | 0.000020 |
| checking permissions           | 0.000012 |
| opening tables                 | 0.000076 |
| init                           | 0.000011 |
| system lock                    | 0.000026 |
| optimizing                     | 0.000013 |
| statistics                     | 0.000033 |
| preparing                      | 0.000032 |
| executing                      | 1.093124 |
| end                            | 0.000025 |
| query end                      | 0.000013 |
| waiting for handler commit     | 0.000078 |
| closing tables                 | 0.000048 |
| freeing items                  | 0.000076 |
| cleaning up                    | 0.000037 |
+--------------------------------+----------+
17 rows in set, 1 warning (0.01 sec)

如果指定 all 还会输出更详细的统计信息,包括 cpu、上下文切换、磁盘io、ipc(进程间通信)发送/接受的消息数量、页面故障次数、交换次数等。

需要注意的是,这里的统计信息是针对整个进程的,不是单个 sql 的。如果在执行上述 sql 的同时还有其它 sql 在执行,那么这些数据就不能用来评估该 sql 的资源使用情况。

mysql> show profile all for query 1\g
...
*************************** 11. row ***************************
             status: executing
           duration: 0.825417
           cpu_user: 1.486951
         cpu_system: 0.007982
  context_voluntary: 0
context_involuntary: 553
       block_ops_in: 0
      block_ops_out: 0
      messages_sent: 0
  messages_received: 0
  page_faults_major: 0
  page_faults_minor: 24
              swaps: 0
    source_function: executeiteratorquery
        source_file: sql_union.cc
        source_line: 1678
...
17 rows in set, 1 warning (0.00 sec)

show profile 的实现原理

show profile 主要是在sql_profile.cc中实现的。它的实现主要分为两部分:

  • 数据的采集。
  • 数据的计算。

下面我们分别从这两个维度来看看 show profile 的实现原理。

数据的采集

数据的采集实际上是通过“埋点”实现的。不同阶段对应的“埋点”地址可通过show profile source查看。

mysql> show profile source for query 1;
+--------------------------------+----------+-------------------------+----------------------+-------------+
| status                         | duration | source_function         | source_file          | source_line |
+--------------------------------+----------+-------------------------+----------------------+-------------+
| starting                       | 0.000157 | null                    | null                 |        null |
| executing hook on transaction  | 0.000009 | launch_hook_trans_begin | rpl_handler.cc       |        1484 |
| starting                       | 0.000020 | launch_hook_trans_begin | rpl_handler.cc       |        1486 |
| checking permissions           | 0.000012 | check_access            | sql_authorization.cc |        2173 |
| opening tables                 | 0.000076 | open_tables             | sql_base.cc          |        5911 |
| init                           | 0.000011 | execute                 | sql_select.cc        |         760 |
| system lock                    | 0.000026 | mysql_lock_tables       | lock.cc              |         332 |
| optimizing                     | 0.000013 | optimize                | sql_optimizer.cc     |         379 |
| statistics                     | 0.000033 | optimize                | sql_optimizer.cc     |         721 |
| preparing                      | 0.000032 | optimize                | sql_optimizer.cc     |         806 |
| executing                      | 1.093124 | executeiteratorquery    | sql_union.cc         |        1677 |
| end                            | 0.000025 | execute                 | sql_select.cc        |         796 |
| query end                      | 0.000013 | mysql_execute_command   | sql_parse.cc         |        4896 |
| waiting for handler commit     | 0.000078 | ha_commit_trans         | handler.cc           |        1636 |
| closing tables                 | 0.000048 | mysql_execute_command   | sql_parse.cc         |        4960 |
| freeing items                  | 0.000076 | dispatch_sql_command    | sql_parse.cc         |        5434 |
| cleaning up                    | 0.000037 | dispatch_command        | sql_parse.cc         |        2478 |
+--------------------------------+----------+-------------------------+----------------------+-------------+
17 rows in set, 1 warning (0.00 sec)

executing为例,它对应的“埋点”地址是sql_union.cc文件的第 1677 行,该行对应的代码是:

  thd_stage_info(thd, stage_executing);

其它的“埋点”地址也类似,调用的都是thd_stage_info,唯一不一样的是 stage 的名称。

thd_stage_info 主要会做两件事情:

  • 采集数据。
  • 将采集到的数据添加到队列中。

下面我们结合代码看看具体的实现细节。

void query_profile::new_status(const char *status_arg, const char *function_arg,
                               const char *file_arg, unsigned int line_arg) {
  prof_measurement *prof;
  ...
  // 初始化 prof_measurement,初始化的过程中会采集数据。
  if ((function_arg != nullptr) && (file_arg != nullptr))
    prof = new prof_measurement(this, status_arg, function_arg,
                                base_name(file_arg), line_arg);
  else
    prof = new prof_measurement(this, status_arg);
  // m_seq 是阶段的序号,对应 information_schema.profiling 中的 seq。
  prof->m_seq = m_seq_counter++; 
  // time_usecs 是采集到的系统当前时间。
  m_end_time_usecs = prof->time_usecs; 
  // 将采集到的数据添加到队列中,这个队列在查询时会用到。
  entries.push_back(prof); 
  ...
}

继续分析prof_measurement的初始化逻辑。

prof_measurement::prof_measurement(query_profile *profile_arg,
                                   const char *status_arg,
                                   const char *function_arg,
                                   const char *file_arg, unsigned int line_arg)
    : profile(profile_arg) {
  collect();
  set_label(status_arg, function_arg, file_arg, line_arg);
}
void prof_measurement::collect() {
  time_usecs = (double)my_getsystime() / 10.0; /* 1 sec was 1e7, now is 1e6 */
#ifdef have_getrusage
  getrusage(rusage_self, &rusage);
#elif defined(_win32)
  ...
#endif
}

prof_measurement 在初始化时会调用collect函数,collect()函数非常关键,它会做两件事情:

  • 通过my_getsystime()获取系统的当前时间。

  • 通过getrusage(rusage_self, &rusage)获取当前进程(注意是进程,不是当前 sql)的资源使用情况。

    getrusage是一个用于获取进程或线程资源使用情况的系统调用。它返回进程在执行期间所消耗的资源信息,包括 cpu 时间、内存使用、页面故障、上下文切换等信息。

prof_measurement 初始化完毕后,会将其添加到 entries 中。entries 是一个队列(queue<prof_measurement> entries)。这个队列,会在执行show profile for query n或者information_schema.profiling时用到。

说完数据的采集,接下来我们看看数据的计算,毕竟“埋点”收集的只是系统当前时间,而我们在show profile for query n中看到的duration 是一个时长。

数据的计算

当我们在执行show profile for query n时,实际上查询的是information_schema.profiling,此时,会调用profiling::fill_statistics_info来填充数据。

下面我们看看该函数的实现逻辑。

int profiling::fill_statistics_info(thd *thd_arg, table_ref *tables) {
  dbug_trace;
  table *table = tables->table;
  ulonglong row_number = 0;
  query_profile *query;
  // 循环 history 队列,队列中的元素是 query_profile,每一个查询对应一个 query_profile。
  // 队列的大小由参数 profiling_history_size 决定,默认是 15。
  void *history_iterator;
  for (history_iterator = history.new_iterator(); history_iterator != nullptr;
       history_iterator = history.iterator_next(history_iterator)) {
    query = history.iterator_value(history_iterator);
    ulong seq;
    void *entry_iterator;
    prof_measurement *entry, *previous = nullptr;
    // 循环每个查询中的 entries,entries 存储了每个阶段的系统当前时间。
    for (entry_iterator = query->entries.new_iterator();
         entry_iterator != nullptr;
         entry_iterator = query->entries.iterator_next(entry_iterator),
        previous = entry, row_number++) {
      entry = query->entries.iterator_value(entry_iterator);
      seq = entry->m_seq;
      if (previous == nullptr) continue;
      if (thd_arg->lex->sql_command == sqlcom_show_profile) {
        if (thd_arg->lex->show_profile_query_id ==
            0) /* 0 == show final query */
        {
          if (query != last) continue;
        } else {
          // 如果记录中的 query_id 跟 show profile for query query_id 中的不一致,则继续判断下一条记录
          if (thd_arg->lex->show_profile_query_id != query->profiling_query_id) 
            continue;
        }
      }
      restore_record(table, s->default_values);
      // query->profiling_query_id 用来填充 information_schema.profiling 中的 query_id
      table->field[0]->store((ulonglong)query->profiling_query_id, true);
      // seq 用来填充 information_schema.profiling 中的 seq
      table->field[1]->store((ulonglong)seq,
                             true); 
      // status 用来填充 information_schema.profiling 中的 state
      // 注意,这里是上一条记录的 status,不是当前记录的 status
      table->field[2]->store(previous->status, strlen(previous->status),
                             system_charset_info);
      // 当前记录的 time_usecs 减去上一条记录的 time_usecs 的值,换算成秒,用来填充 information_schema.profiling 中的 duration
      my_decimal duration_decimal;
      double2my_decimal(
          e_dec_fatal_error,
          (entry->time_usecs - previous->time_usecs) / (1000.0 * 1000),
          &duration_decimal); 
      table->field[3]->store_decimal(&duration_decimal);
#ifdef have_getrusage
      my_decimal cpu_utime_decimal, cpu_stime_decimal;
      // 当前记录的 ru_utime 减去上一条记录的 ru_utime,用来填充 information_schema.profiling 中的 cpu_user
      double2my_decimal(
          e_dec_fatal_error,
          rusage_diff_usec(entry->rusage.ru_utime, previous->rusage.ru_utime) /
              (1000.0 * 1000),
          &cpu_utime_decimal);
      ...
      table->field[4]->store_decimal(&cpu_utime_decimal);
...
  return 0;
}

可以看到,information_schema.profiling中的第三列(state,对应 show profile for query n 中的 status)存储的是上一条记录的 status(阶段名),而第四列(duration)的值等于当前记录的采集时间(entry->time_usecs)减去上一条记录的采集时间(previous->time_usecs)。

所以,我们在show profile for query n中看到的 duration 实际上通过下一个阶段的采集时间减去当前阶段的采集时间得到的,并不是show profile source中函数(source_function)的执行时长。

这种实现方式在判断操作当前状态和分析各个阶段耗时时存在一定的误导性。

回到开头的 case。

表空间导入操作为什么大部分耗时是在 system lock 阶段?

表空间导入操作是在mysql_discard_or_import_tablespace函数中实现的。

下面是该函数简化后的代码。

bool sql_cmd_discard_import_tablespace::mysql_discard_or_import_tablespace(
    thd *thd, table_ref *table_list) {
  ... 
  thd_stage_info(thd, stage_discard_or_import_tablespace);
  ...
  if (open_and_lock_tables(thd, table_list, 0, &alter_prelocking_strategy)) {
    return true;
  }
  ...
  const bool discard =
      (m_alter_info->flags & alter_info::alter_discard_tablespace);
  error = table_list->table->file->ha_discard_or_import_tablespace(discard,
                                                                   table_def); 
  thd_stage_info(thd, stage_end);
  ...
  return true;
}

可以看到,该函数实际调用的是 thd_stage_info(thd, stage_discard_or_import_tablespace)。

只不过,在调用 thd_stage_info(thd, stage_discard_or_import_tablespace) 后,调用了 open_and_lock_tables。

而 open_and_lock_tables 最后会调用 thd_stage_info(thd, stage_system_lock)。

这也就是为什么上述函数中虽然调用了 thd_stage_info(thd, stage_discard_or_import_tablespace),但show profileshow processlist的输出中却显示system lock

但基于对耗时的分析,我们发现这么显示其实并不合理。

在开头的 case 中,虽然system lock阶段显示的耗时是 788.966338 秒,但实际上open_and_lock_tables这个函数只消耗了 0.000179 秒,真正的耗时是来自 table_list->table->file->ha_discard_or_import_tablespace,其执行时间长达 788.965481 秒。

为什么这个函数需要执行这么久呢?主要是表空间在导入的过程中会检查并更新表空间中的每个页,包括验证页是否损坏、更新表空间 id 和 lsn、处理 btree 页(如设置索引 id、清除 delete marked 记录等)、将页标记为脏页等。表越大,检查校验的时候会越久。

如此来看,针对表空间导入操作,将其状态显示为discard_or_import_tablespace更能反映操作的真实情况。

总结

  • show profile中显示的每个阶段的耗时,实际上是由下一个阶段的采集时间减去当前阶段的采集时间得出的。

    每个阶段的采集时间是通过在代码的不同路径中植入 thd_stage_info(thd, stage_xxx) 实现的,采集的是系统当前时间。

  • 这种实现方式在判断操作当前状态(通过 show processlist)和分析各个阶段耗时(通过 show profile )时存在一定的误导性,主要是因为预定义的阶段数量是有限的。

    在 mysql 8.4 中,共定义了 98 个阶段,具体的阶段名可在mysqld.cc中的all_server_stages数组找到。

  • 在表空间导入操作中,虽然大部分耗时显示为system lock阶段,但实际上,使用discard_or_import_tablespace来描述这一过程会更为准确。

参考资料

到此这篇关于mysql 优化利器 show profile 的实现原理的文章就介绍到这了,更多相关mysql  show profile内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com