prometheus 統計MySQL 自增主鍵的剩餘可用百分比
- 2019 年 10 月 4 日
- 筆記
最近生產環境一套資料庫因為瘋狂寫日誌數據,造成主鍵值溢出的情況出現,因此有必要將這個指標監控起來。
mysqld_exporter自帶的這個功能,下面是我使用的啟動參數:
nohup ./mysqld_exporter –config.my-cnf="./my.cnf" –web.listen-address=":9104" –collect.heartbeat –collect.auto_increment.columns –collect.binlog_size –collect.engine_innodb_status –collect.engine_tokudb_status –collect.slave_hosts –collect.slave_status –collect.info_schema.processlist –collect.info_schema.innodb_metrics > /dev/null 2>&1 &
紅色高亮的參數,就是用來採集到自增id的使用情況的。
實際上執行的類似這個SQL:
SELECT table_schema, table_name, column_name, AUTO_INCREMENT, POW(2, CASE data_type WHEN 'tinyint' THEN 7 WHEN 'smallint' THEN 15 WHEN 'mediumint' THEN 23 WHEN 'int' THEN 31 WHEN 'bigint' THEN 63 END+(column_type LIKE '% unsigned'))-1 AS max_int FROM information_schema.tables t JOIN information_schema.columns c USING (table_schema,table_name) WHERE c.extra = 'auto_increment' AND t.TABLE_SCHEMA NOT IN ('information_schema','mysql', 'sys','test','performance_schema') AND t.auto_increment IS NOT NULL ;

在prometheus的web介面,我們可以測試編寫如下的promql, 找出剩餘自增id可以率少於40%的實例的庫+表名
(mysql_info_schema_auto_increment_column_max{schema!~'test|mysql'} – mysql_info_schema_auto_increment_column{schema!~'test|mysql'})/mysql_info_schema_auto_increment_column_max{schema!~'test|mysql'}*100 < 40

取到數據後,我們可以在alertmanager裡面配置相關的告警,或者再grafana上面繪製圖,如下:
