maria-db-ops-toolkit
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "maria-db-ops-toolkit" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-7c8f593673d5a15353ad75b03f3c29c9a3383059772f1123dcfc96543458338e. Verify the upstream source and version against https://skillhub.cn/skills/user_f21d3e36/maria-db-ops-toolkit before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
skillhub.cn
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
MariaDB ops toolkit: an all-scenario operations toolkit for MariaDB 10.4–10.11 that integrates my.cnf tuning generation, backup/restore, binlog rollback, and troubleshooting.
Introduction source: third_party · user_f21d3e36 · 1.1.0 Reference
SkillPi interpretation
- Tasks
- Translation pending; see source documentation.
- Limits and differences
- ```
- Testing
- Not tested
Browse files
Frontmatter
name: MariaDB 生產環境運維工具箱
displayName: MariaDB 生產環境運維工具箱
slug: maria-db-ops-toolkit
version: 1.1.0
description: 整合 my.cnf 調優生成、備份還原、Binlog 回滾、故障排查於一體的 MariaDB 10.4-10.11 全場景運維工具
category: opsMariaDB 生產環境運維工具箱
整合調優配置生成、備份還原、Binlog 回滾、故障排查於一體的 MariaDB 10.4/10.5/10.6/10.11 LTS 全場景運維工具。
觸發條件
滿足以下任一場景時啟用此 skill:
- 用戶提供伺服器規格(記憶體、CPU 核數)並請求 my.cnf 配置
- 用戶提到備份、mysqldump、Binlog、數據回滾
- 用戶貼出錯誤日誌、描述連不上、啟動失敗、慢查詢、鎖表等故障現象
- 用戶使用以下關鍵詞:MariaDB、my.cnf、InnoDB、慢查詢、binlog、備份還原
第一部分:my.cnf 調優配置生成
步驟 1:收集用戶環境資訊
必填:
- 記憶體大小(GB)
- CPU 核數
- MariaDB 版本(10.4 / 10.5 / 10.6 / 10.11)
- 業務類型:
網站業務/報表讀庫/輕量 SaaS - 最大連接數(可估算,預設 300)
選填:
- 是否為主從架構
- 大表規模(超過 1 千萬行的表數量)
- 是否需要全文檢索
步驟 2:根據業務類型生成配置
網站業務(高並發、讀多寫少)
innodb-buffer-pool-size = 記憶體 × 70%
innodb-buffer-pool-instances = CPU 核數(最大 16)
innodb-read-io-thread = 4
innodb-write-io-thread = 4
max-connections = 用戶指定值
table-open-cache = 2000
table-definition-cache = 1000
thread-cache-size = max-connections × 0.1
sort-buffer-size = 2M
read-buffer-size = 1M
join-buffer-size = 2M
slow-query-log = 1
long-query-time = 1
log-slow-slave-statements = 1
報表讀庫(複雜查詢、大結果集)
innodb-buffer-pool-size = 記憶體 × 75%
max-connections = 100(降低並發壓力)
sort-buffer-size = 4M # 加大排序緩衝
read-buffer-size = 2M
join-buffer-size = 4M
tmp-table-size = 256M
max-heap-table-size = 256M
rpl-semi-sync-master-enabled = 1
rpl-semi-sync-slave-enabled = 1
輕量 SaaS(資源受限、多租戶)
innodb-buffer-pool-size = 記憶體 × 60%
max-connections = 200
innodb-flush-log-at-trx-commit = 2
sync-binlog = 0
innodb-flush-method = O_DIRECT
table-open-cache = 1000
步驟 3:配置說明與估算
每個參數必須附帶中文註釋,格式如下:
[mysqld]
# === 緩衝池配置(必選)===
innodb-buffer-pool-size = 11G # 記憶體 16G × 70%,建議預留 2G 給系統
innodb-buffer-pool-instances = 8 # 分割減少內部競爭,每實例至少 1G
# === 線程配置 ===
max-connections = 500 # 根據用戶指定,超出會報 "Too many connections"
thread-cache-size = 50 # 緩存斷開線程,減少創建銷毀開銷
# === 臨時表與排序 ===
tmp-table-size = 64M # 記憶體臨時表上限,超限寫入磁盤
max-heap-table-size = 64M
sort-buffer-size = 2M # 每連接每次排序分配,注意記憶體佔用
記憶體佔用估算公式:
最大記憶體佔用 ≈ innodb-buffer-pool-size
+ max-connections × (sort-buffer-size + read-buffer-size + join-buffer-size)
+ table-open-cache × 1KB
+ 2G(作業系統預留)
步驟 4:配置生效與重啟
# 測試配置語法(不重啟)
mysqld --defaults-file=/etc/mysql/my.cnf --validate-config
# 滾動重啟(生產環境首選)
mysql -e "SET GLOBAL innodb_buffer_pool_size = 的一半值;" # 先熱調整
systemctl restart mysql # 完整重啟
# 驗證生效
mysql -e "SHOW GLOBAL VARIABLES LIKE 'innodb-buffer-pool-size';"
mysql -e "SHOW GLOBAL VARIABLES LIKE 'max-connections';"
步驟 5:優化後狀態校驗 SQL
-- 緩衝池命中率,低於 95% 需關注
SELECT
ROUND(
(1 - (Innodb_buffer_pool_reads / Innodb_buffer_pool_read_requests)) * 100,
2
) AS buffer_pool_hit_ratio_pct
FROM performance_schema.global_status
WHERE Variable_name = 'Innodb_buffer_pool_read_requests';
-- 緩衝池使用概況
SELECT
POOL_ID,
POOL_SIZE,
FREE_PAGES,
DATA_PAGES,
(DATA_PAGES / POOL_SIZE) * 100 AS used_pct
FROM information_schema.INNODB_BUFFER_POOL_STATS
WHERE POOL_ID = 0;
-- 當前連接數與最大連接數 SHOW STATUS LIKE 'Threads_connected'; SHOW STATUS LIKE 'Max_used_connections';
-- 慢查詢統計 SHOW GLOBAL STATUS LIKE 'Slow_queries';
-- InnoDB 緩衝池頁面狀態 SHOW ENGINE INNODB STATUS\G
查看 Free pages、Database pages、Modified pages
-- 鎖等待事件(高並發必查) SELECT FROM information_schema.INNODB_LOCK_WAITS; SELECT FROM information_schema.INNODB_LOCKS;
## 第二部分:備份還原與 Binlog 回滾
### 步驟 1:一次性手動備份
**全庫備份:**
```bash
# 標準全備
mysqldump -u root -p \
--all-databases \
--single-transaction \
--routines \
--triggers \
--events \
--master-data=2 \
--flush-logs \
| gzip > /backup/mysql/full_backup_$(date +%Y%m%d_%H%M%S).sql.gz
# 單庫備份(更輕量)
mysqldump -u root -p --single-transaction db_name | gzip > /backup/mysql/db_name_$(date +%Y%m%d).sql.gz
# 單表備份(誤刪表搶救)
mysqldump -u root -p db_name table_name > /backup/mysql/db_name.table_name.sql
必做檢查:
# 確認 binlog 開啟
mysql -e "SHOW VARIABLES LIKE 'log_bin';"
# 查看 binlog 位置(恢復起點)
mysql -e "SHOW MASTER STATUS;"
# 備份完成後確認文件大小(空備份 = 悲劇)
ls -lh /backup/mysql/
步驟 2:7 天循環自動備份腳本
#!/bin/bash
# /opt/scripts/mysql-backup.sh
# crontab: 0 3 * * * /opt/scripts/mysql-backup.sh
#
# 安全建議:密碼不要寫在腳本中,建議使用 mysql_config_editor 創建登錄路徑:
# mysql_config_editor set --login-path=backup --host=localhost --user=root --password
# 然後使用:mysqldump --login-path=backup ...
# 以下示例保留密碼占位符,正式環境請替換為登錄路徑方式
BACKUP_DIR="/backup/mysql"
DATE=$(date +%Y%m%d)
RETENTION_DAYS=7
MYSQL_USER="root"
MYSQL_PASS="your_password"
mkdir -p ${BACKUP_DIR}
# 全量備份
mysqldump -u ${MYSQL_USER} -p${MYSQL_PASS} \
--all-databases \
--single-transaction \
--routines \
--triggers \
--events \
--master-data=2 \
--flush-logs \
| gzip > ${BACKUP_DIR}/full_backup_${DATE}.sql.gz
# 清理 7 天前舊備份
find ${BACKUP_DIR} -name "full_backup_*.sql.gz" -mtime +${RETENTION_DAYS} -delete
# 清理舊 binlog(保留近 3 天)
mysql -u ${MYSQL_USER} -p${MYSQL_PASS} -e "PURGE BINARY LOGS BEFORE DATE_SUB(NOW(), INTERVAL 3 DAY);"
echo "[$(date)] Backup completed" >> /var/log/mysql-backup.log
Crontab 部署:
# 每日凌晨 3 點執行
echo "0 3 * * * root /opt/scripts/mysql-backup.sh >> /var/log/mysql-backup.log 2>&1" >> /etc/crontab
# 驗證
crontab -l
systemctl restart crond
步驟 3:Binlog 按時間點回滾
-- 第一步:確認誤操作時間點(查詢日誌)
mysqlbinlog --base64-output=decode-rows -v /var/lib/mysql/mysql-bin.000001 \
| grep -A5 "DELETE FROM users" | head -20
-- 第二步:確認 binlog 格式與位置
SHOW BINLOG EVENTS IN 'mysql-bin.000001' LIMIT 20;
-- 第三步:生成回滾 SQL(不直接執行,先審核)
mysqlbinlog \
--start-datetime="2025-01-15 10:00:00" \
--stop-datetime="2025-01-15 10:30:00" \
--database=db_name \
/var/lib/mysql/mysql-bin.000001 \
| grep -v "^#" | grep -v "^SET" | grep -v "^DELIMITER" \
> /tmp/rollback.sql
-- 第四步:人工審核回滾 SQL(必須!)
head -50 /tmp/rollback.sql
-- 第五步:確認無誤後執行回滾
mysql -u root -p db_name < /tmp/rollback.sql
按 GTID 回滾(更精確,推薦方式):
# 找到事務 GTID
mysqlbinlog /var/lib/mysql/mysql-bin.000001 | grep -i "GTID"
# 查看當前 GTID 位置
mysql -u root -p -e "SELECT @@GLOBAL.gtid_binlog_pos;"
# 指定起始 GTID 恢復(推薦)
mysqlbinlog --gtid-legacy \
--start-gtid="1-100-500" \
mysql-bin.000002 | mysql -u root -p
# 注意:--gtid-only 與 --start-position 不可同時使用,請選擇其中一種方式
步驟 4:數據恢復操作流程
# 場景:誤刪整張表
# 1. 確認最後可用備份
ls -lt /backup/mysql/ | head -5
# 2. 停止寫入(防止覆蓋 binlog)
mysql -e "FLUSH TABLES WITH READ LOCK;"
# 3. 恢復到備份時間點
gunzip < /backup/mysql/full_backup_20250115.sql.gz | mysql -u root -p
# 4. 應用 binlog 到誤刪前一刻
mysqlbinlog \
--start-datetime="2025-01-15 00:00:00" \
--stop-datetime="2025-01-15 14:30:00" \
mysql-bin.000010 mysql-bin.000011 | mysql -u root -p
# 5. 驗證數據
mysql -e "SELECT COUNT(*) FROM db_name.table_name;"
第三部分:常見故障排查
故障一:3306 端口無法訪問
# 排查順序
# 1. 確認端口監聽
ss -tlnp | grep 3306
# 2. 確認防火牆
iptables -L -n | grep 3306
firewall-cmd --list-ports
# 3. 確認綁定地址(禁止 bind-address = 127.0.0.1)
mysql -e "SHOW VARIABLES LIKE 'bind-address';"
# 4. 授權遠程訪問
mysql -e "GRANT ALL ON *.* TO 'root'@'%' IDENTIFIED BY 'password';"
mysql -e "FLUSH PRIVILEGES;"
# 5. 測試遠程連接
mysql -h 192.168.1.100 -u root -p -e "SELECT 1;"
故障二:啟動失敗 / InnoDB 崩潰恢復
# 1. 查看錯誤日誌
tail -100 /var/log/mysql/error.log
# 2. 常見原因:磁盤滿
df -h
# 解決:清理日誌、備份遷移
truncate -s 0 /var/lib/mysql/slow-query.log
truncate -s 0 /var/lib/mysql/general.log
# 3. 常見原因:配置錯誤
mysqld --defaults-file=/etc/mysql/my.cnf --validate-config
# 4. InnoDB 損壞強制恢復(最後手段)
# 在 my.cnf 添加:
# innodb-force-recovery = 1 # 僅補數據,禁用寫入
# 5. 從備份恢復後移除該參數
故障三:長事務鎖表
-- 查找長時間運行的事務
SELECT
trx_id,
trx_state,
trx_started,
TIMESTAMPDIFF(MINUTE, trx_started, NOW()) AS minutes_running,
trx_mysql_thread_id,
trx_query
FROM information_schema.INNODB_TRX
ORDER BY trx_started;
-- 查找鎖等待
SELECT
b.trx_id AS waiting_trx_id,
b.trx_query AS waiting_query,
b.trx_mysql_thread_id AS waiting_thread,
b.trx_started AS waiting_started,
b.trx_rows_locked AS waiting_rows_locked,
a.requesting_thd_id AS blocking_thread_id,
a.lock_id AS blocking_lock_id,
a.lock_mode
FROM information_schema.INNODB_LOCK_WAITS w
JOIN information_schema.INNODB_LOCKS a ON w.blocking_lock_id = a.lock_id
JOIN information_schema.INNODB_TRX b ON w.requesting_trx_id = b.trx_id;
-- 強制終止阻塞進程(殺掉前確認業務影響)
KILL [thread_id];
-- 批量殺掉所有長事務(緊急使用)
SELECT CONCAT('KILL ', trx_mysql_thread_id, ';')
FROM information_schema.INNODB_TRX
WHERE TIMESTAMPDIFF(MINUTE, trx_started, NOW()) > 30;
故障四:慢查詢定位與優化
-- 開啟慢查詢日誌
SET GLOBAL slow_query_log = 1;
SET GLOBAL slow-query-log-file = '/var/lib/mysql/slow-query.log';
SET GLOBAL long_query_time = 1;
SET GLOBAL log_queries_not_using_indexes = 1;
-- 分析慢查詢日誌(使用 pt-query-digest)
-- pt-query-digest /var/lib/mysql/slow-query.log
-- 查看當前所有連接的查詢狀態
SHOW FULL PROCESSLIST;
-- 查看重複執行的查詢
SELECT
digest_text,
count_star AS execution_count,
avg_timer_wait / 1000000000000 AS avg_seconds,
sum_timer_wait / 1000000000000 AS total_seconds
FROM performance_schema.events_statements_summary_by_digest
ORDER BY count_star DESC
LIMIT 10;
-- EXPLAIN 分析慢查詢
EXPLAIN SELECT * FROM orders WHERE user_id = 123 AND status = 'pending';
EXPLAIN ANALYZE SELECT * FROM orders WHERE user_id = 123; -- MariaDB 10.6+
故障五:主從複製延遲
-- 1. 檢查從庫延遲(MariaDB 10.5+,使用 REPLICA 語法)
SHOW REPLICA STATUS\G
-- 關注:Seconds_Behind_Replica、Replica_IO_Running、Replica_SQL_Running
-- 如使用舊版 MariaDB 或 MySQL 語法,替換如下:
-- SHOW SLAVE STATUS\G
-- 2. 查看 binlog 應用進度
SHOW MASTER STATUS;
-- 3. 從庫優化配置
# 在 my.cnf [mysqld] 添加:
# relay-log-recovery = 1
# relay-log-purge = 1
# read-only = 1
# slave_parallel_threads = 4
# slave_parallel_mode = optimistic
-- 4. 跳過錯誤複製(緊急使用)
STOP REPLICA;
SET GLOBAL sql_slave_skip_counter = 1;
START REPLICA;
-- 5. 重新同步從庫(資料不一致時)
STOP REPLICA;
RESET REPLICA ALL;
-- 然後重新 CHANGE REPLICA TO ...(或舊版 CHANGE MASTER TO...)
故障六:中文亂碼
-- 1. 確認字符集配置
SHOW VARIABLES LIKE 'character%';
SHOW VARIABLES LIKE 'collation%';
-- 2. 檢查表字符集
SHOW CREATE TABLE table_name;
-- 3. 緊急修復:將欄位改為 utf8mb4
ALTER TABLE table_name MODIFY column_name VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- 4. 永久修復:在 my.cnf [mysqld] 添加
# character-set-server = utf8mb4
# collation-server = utf8mb4_unicode_ci
# init-connect = 'SET NAMES utf8mb4'
驗證步驟
完成任意模組操作後,按以下順序驗證:
- 服務狀態:
systemctl status mysql確認運行中 - 版本確認:
mysql -V確認版本號 - 配置生效:
SHOW GLOBAL VARIABLES LIKE '%param%'查詢關鍵參數 - 業務測試: 執行一條業務常用 SQL,確認響應正常
- 備份還原測試: 每季度執行一次完整還原演練
專項優化建議
大表專項(日均千萬級別)
-- 分區表設計(按時間)
ALTER TABLE orders PARTITION BY RANGE (YEAR(created_at)) (
PARTITION p2023 VALUES LESS THAN (2024),
PARTITION p2024 VALUES LESS THAN (2025),
PARTITION p2025 VALUES LESS THAN MAXVALUE
);
-- 定期歸檔冷數據
INSERT INTO orders_archive SELECT * FROM orders WHERE created_at < DATE_SUB(NOW(), INTERVAL 2 YEAR);
DELETE FROM orders WHERE created_at < DATE_SUB(NOW(), INTERVAL 2 YEAR);
日誌庫專項
# my.cnf 添加
innodb-flush-log-at-trx-commit = 2 # 日誌寫入放寬,提升寫入性能
sync-binlog = 0 # binlog 同步放寬
# 注意:以上參數犧牲持久性,僅適合獨立日誌庫
讀寫分離專項
# 主庫配置
binlog-do-db = app_db
binlog-ignore-db = mysql
binlog-ignore-db = information_schema
# 從庫配置(讀負載分流)
read-only = 1
super-read-only = 1
slave-parallel-threads = 8
replicate-do-db = app_db
注意事項
- 生產環境修改 my.cnf 前必備:備份原配置
cp /etc/mysql/my.cnf /etc/mysql/my.cnf.bak.$(date +%Y%m%d) - innodb-force-recovery 超過 3 可能有數據丟失風險
- PURGE BINARY LOGS 會刪除 binlog,執行前確認從庫已同步
- KILL 殺線程時注意區分業務線程和管理員線程
- 字符集統一使用 utf8mb4,避免 emoji 和生僻字丟失
如需完整伺服器部署方案、澳門政企 IT 搭建諮詢,可進一步溝通。
📊 使用統計
本技能會自動記錄使用情況到本地文件 ~/.qclaw/skills/maria-db-ops-toolkit/usage.json。
記錄內容
{
"totalSessions": 0,
"totalConfigGen": 0,
"totalBackupRestore": 0,
"totalTroubleshoot": 0,
"lastUsed": null,
"sessions": []
}
安全聲明
- ✅ 只記錄維度(配置生成次數、備份還原次數、故障排查次數等)
- ❌ 不記錄資料庫名稱、連接信息、SQL 語句等敏感內容
- ✅ 數據完全本地存儲,不上傳、不外傳
- ✅ 說「清理統計」可一鍵清空記錄
📋 更新日誌
v1.1.0(2026-07-20)
新增功能:
- ✅ 使用統計模塊(自動記錄啟動次數、配置生成次數、備份還原次數等)
- ✅ 統計數據本地存儲,不上傳,不記錄敏感信息
- ✅ 支持「清理統計」一鍵清空
安全性:
- 只記維度(次數、日期),不記錄資料庫詳情
- 數據完全本地化,符合隱私保護原則
v1.0.0(初始版本)
- 初始功能發布
- my.cnf 調優配置生成
- 備份還原與 Binlog 回滾
- 常見故障排查
Current listing version
1.1.0
Safety and assessment details
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 直接解决MariaDB生产环境运维核心痛点,涵盖配置调优、备份恢复、Binlog回滚、故障排查等全场景
- 面向DBA和运维人员的高频刚需工具,显著提升日常运维效率
- 提供从配置生成到故障排查的完整闭环解决方案
Areas to improve
-
触发词可进一步细化 Reported severity: Minor
触发条件已覆盖主要运维场景,但可补充更多具体错误码或日志关键词
Recommendation: 增加如'ERROR 2002'、'InnoDB corruption'等具体错误码作为触发词
Highlights
- 触发条件覆盖全面,包含配置生成、备份恢复、故障排查等多个维度
- 关键词设置合理,边界清晰,能有效区分运维场景
Areas to improve
-
文档长度略长 Reported severity: Minor
文档内容详实但篇幅较长,建议适当拆分或增加目录导航
Recommendation: 考虑将各模块拆分为独立文档或增加更清晰的章节导航
Highlights
- Phase/步骤划分清晰,每个模块都有明确的执行流程
- 包含完整的端到端示例和验证步骤
- frontmatter完整,版本信息清晰
Areas to improve
-
部分脚本缺少错误处理 Reported severity: Minor
备份脚本等关键操作缺少详细的错误处理和日志记录
Recommendation: 在备份脚本中增加set -e、错误码检查和更详细的日志输出
Highlights
- 工具来源明确,参数配置合理且有详细说明
- 覆盖主要异常场景,如磁盘满、配置错误、锁表等
- 不可逆操作(如KILL线程、PURGE BINARY LOGS)都有明确警告和确认机制
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
These common operations were not identified in the main document. This does not mean no permissions or risks exist.
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.