概述
One of our customers recently asked whether it is possible to identify, from the MySQL side, the query that is causing high CPU usage on his system. The usage of simple OS tools to find the culprit has been a widely used technique for a long time by PostgreSQL and Oracle DBAs, but it didn’t work for MySQL as historically we’ve lacked the instrumentation to match an OS thread with an internal processlist thread – until recently.
Percona added support to map processlist ids to OS thread ids through column TID of the information_schema.processlist table starting on Percona Server for MySQL 5.6.27. With the release of 5.7, MySQL followed with its own implementation by extending the PERFORMANCE_SCHEMA.THREADS table and adding a new column named THREAD_OS_ID, which Percona Server for MySQL adopted in place of its own, as it usually does remain as close to upstream as possible.
The following approach is useful for cases where there is a query overloading one particular CPU while other cores are performing normally. For cases where it is a general CPU usage issue, different methods can be used, such as the one in this other blog post Reducing High CPU on MySQL: A Case Study.
How can we use this new column to find out which session is using the most CPU resources in my database?
1、定位cpu飙升的MySQL具体线程
top -H -p <mysqld进程id> 或者 pidstat -t -p <mysqld进程id> 1 5
2、根据具体PID,定位问题SQL
SELECT
b.HOST,
b.db,
b.USER,
a.THREAD_OS_ID "os_id",
b.id "processlist_id",
b.command,
b.time,
b.state,
a.PROCESSLIST_INFO,
b.info "sql"
FROM
PERFORMANCE_SCHEMA.threads a,
information_schema.PROCESSLIST b
WHERE
b.id = a.processlist_id
AND a.THREAD_OS_ID = <具体线程id>;