Troubleshooting
对crash的数据库进行故障分析并不是一件快乐的事情,尤其是 MySQL 的日志中没有提供 crash 原因的情形。比如当 MySQL 内存耗尽。在 2012年 Peter Zaitsev 写了一篇文章 分析MySQL如何使用内存
该文章中有很多有用的技巧。使用新版本的 MySQL (5.7+) 和 performance_schema,我们能够更轻松地解决 MySQL 内存分配问题。
在本文中,我将向您展示如何使用 P_S。
首先,MySQL由于内存不足而崩溃的主要情况有3种:
以下是我们可以开始的内容(假设它是 Linux 服务器):
现在我们可以通过MySQL运行机制以便查找潜在的内存泄漏因素。MySQL 在很多地方分配内存,尤其是:
Performance_schema
功能
show engine performance_schema status 并查看最后一行。Com_prepare_sql
;show global status like 'Com_dealloc_sql'
好消息是从 5.7 开始,我们可以基于 performance_schema
查询内存使用情况。如何使用呢?
UPDATE setup_instruments SET ENABLED = 'YES' WHERE NAME LIKE 'memory/%';
select event_name, current_alloc, high_alloc from sys.memory_global_by_current_bytes where current_count > 0;
举个例子, https://bugs.mysql.com/bug.php?id=86821 ,这篇文章展示了 mysql为触发器分配了过多的内存。
mysql> select event_name, current_alloc, high_alloc from memory_global_by_current_bytes where current_count > 0;
+--------------------------------------------------------------------------------+---------------+-------------+
| event_name | current_alloc | high_alloc |
+--------------------------------------------------------------------------------+---------------+-------------+
| memory/innodb/buf_buf_pool | 7.29 GiB | 7.29 GiB |
| memory/sql/sp_head::main_mem_root | 3.21 GiB | 3.62 GiB |
...
虽然 buf_buf_pool
占用了7G ,但是系统依然为存储过程对象分配3G内存,显然分配的内存太大了。根据文档描述 sp_head 代表这个存储程序的一个实例,它可能是任何类型(存储过程、函数、触发器、事件)。在上述情况下,这个mysql有潜在的内存泄漏。
注意:
其实官方并不承认 存储过程对象导致内存使用量持续增加是个bug。官方给的建议是调整参数
table_open_cache_instances
。
另外我们可以通过如下语句 查看具体是哪个模块在消耗大量内存。
mysql> select substring_index(
-> substring_index(event_name, '/', 2),
-> '/',
-> -1
-> ) as event_type,
-> round(sum(CURRENT_NUMBER_OF_BYTES_USED)/1024/1024, 2) as MB_CURRENTLY_USED
-> from performance_schema.memory_summary_global_by_event_name
-> group by event_type
-> having MB_CURRENTLY_USED>0;
+--------------------+-------------------+
| event_type | MB_CURRENTLY_USED |
+--------------------+-------------------+
| innodb | 0.61 |
| memory | 0.21 |
| performance_schema | 106.26 |
| sql | 0.79 |
+--------------------+-------------------+
4 rows in set (0.00 sec)
文章给出一个MySQL内存泄漏的排查方法和思路。浏览原文请点击阅读原文。