MySQL 表中非主鍵列溢出狀況監控

今天,又掉坑了。 以前踩到過MySQL主鍵溢出的狀況,經過prometheus監控起來了,具體見這篇MySQL主鍵溢出覆盤html


此次遇到的坑,更加的隱蔽。 是一個log表裏面的一個int signed類型的列寫滿了。快速的解決方法固然仍是隻能切新表來救急了,而後搬遷老表的部分歷史數據到熱表。 mysql


亡羊補牢,處理完故障後,趕忙寫腳本把生產的其餘表都捋一遍。sql


下面是我暫時用的一個檢測腳本,還不太完善,湊合shell

分2個文件(1個sql文件,1個shell腳本)
數據庫

check.sql 內容以下:bash

SELECT 
cast( 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 decimal(30,0))  as max_int,
' - ',
concat ('(', concat('select ','max(',COLUMN_NAME,')',' from ',TABLE_SCHEMA,'.',TABLE_NAME),')') 
from 
information_schema.COLUMNS 
where 
TABLE_SCHEMA NOT IN ('information_schema','sys','test','mysql','performance_schema') 
AND 
 DATA_TYPE IN ('int' ) ;


直接到數據庫裏面執行,效果相似這樣:session

image.png



check.sh 內容以下:
dom

#!/bin/bash
# 監測int類型的當可用空間少500w的時候,提醒作DDL操做 
# 設置 session級別的 max_execution_time爲2秒,防止沒有索引的大的拖慢數據庫,可是這樣可能漏判部分列,須要注意下
# 注意:我這裏bigint類型的沒有檢查,若是須要請修改 check.sql where條件中的DATA_TYPE加上 bigint的檢查

source /etc/profile
set -u

mkdir $(date +%F) -pv

# step1 檢測
for host in {'192.168.1.100','192.168.1.110','192.168.1.120','192.168.1.130'}; do

mysql -udts -pdts -h${host} -BN < check.sql   2>/dev/null > sql.log
wait

echo "說明: |  當前列容許的最大值  |  巡檢用的SQL     " >> $(date +%F)/$host.log

while read line; do
   ret=$(mysql -udts -pdts -h${host} -BNe "set session max_execution_time=2000;select $line" 2>/dev/null)
   echo ${ret}
   if [[ "${ret}" == "NULL" ]]; then
    continue
   fi
   if [ ${ret} -lt 5000000 ] ; then 
      echo "$line 剩餘空間 ${ret}, 該表可用水位不足500W,建議作DDL修改成bigint類型" >> $(date +%F)/$host.log
    
   fi
done <  ./sql.log

done

# step2 將檢查的內容打包發郵件(這裏可能須要根據本身生產的狀況改改)
tar czf $(date +%F).tar.gz $(date +%F)
sendemail -s 192.168.1.200  -f post@domain.com -t ergou@domain.com -a $(date +%F).tar.gz -u "$(date +%F) int水位線巡檢日誌"  -o message-content-type=html -o message-charset=utf8 -m "內容詳見附件"

# step3 清理每日生成的以日期命名的目錄和tar.gz文件,這裏我就不貼命令


再配個天天上午10點的cronjob便可,ide


最終天天收到郵件裏面內容大體相似以下:post

image.png

相關文章
相關標籤/搜索