goinception简介
SQL审核是DBA的一项常规工作,人工审核机械无聊。王竹峰老师研发开源了inception工具,造福了广大DBA,也是业界SQL审核的标志性工具。
goinception是韩川川老师在基于inception的基础上,借鉴了tidb的语法解析器实现的golang版本的工具。
goInception是一个集审核、执行、备份及生成回滚语句于一身的MySQL运维工具, 通过对执行SQL的语法解析,返回基于自定义规则的审核结果,并提供执行和备份及生成回滚语句的功能。
图1 goinception架构
安装
安装方式有三种:分别是源码安装、二进制安装、docker安装。
0 源码安装
go版本v1.12及以上
使用go mod做依赖管理
# 下载源码
git clone https://github.com/hanchuanchuan/goInceptioncd goInceptionmake parser
cd goInception
#下载依赖包
go mod tidy
make parser
#构建二进制包
go build -o goInception tidb-server/main.go
启动(注意指定配置文件)
./goInception -config=config/config.toml
1 二进制安装
#下载二进制包(根据需求下载对应版本)
wget https://github.com/hanchuanchuan/goInception/releases/download/v1.3.0/goInception-linux-v1.3.0-1-g140054c.tar.gz
#解压包
tar -xvf goInception-linux-v1.3.0-1-g140054c.tar.gz
#启动
./goInception -config=config/config.toml
2 docker安装
直接拉取镜像修改参数启动即可或者根据提供的docker-compose集成在docker-compose中。配置文件如下:
version: '2'
services:
goinception:
image: hanchuanchuan/goinception
container_name: goinception
restart: always
# 网络模式二选一,使用主机host模式或者映射端口
network_mode: "host"
# ports:
# - 4000:4000
volumes:
# 时区
# - /etc/localtime:/etc/localtime
# 配置文件
- ./config/config.toml:/etc/config.toml
参数说明
goinception有提供默认参数文件config.toml.default,修改需要修改的部分,然后重命名为config.toml。必须要填写备份审核库信息。
backup_host = ""
backup_port = 0
backup_user = ""
backup_password = ""
审核规则修改
审核规则有很多,大家可以参考官方文档。此处说明如何修改审核规则:
1、登录goinception审核server
mysql -h127.0.0.1 -P400
2、查看参数
inception show levels;
# 筛选指定审核名称
inception show levels like '%blob%';
# 筛选指定级别
inception show levels where value=2;
# 筛选指定关键字
inception show levels where `desc` like '%index%';
3、设置审核级别
inception set level er_no_where_condition = 2;
4、修改参数
inception set check_dml_where = 1;
调用示例
goInception延用inception的使用方式,在审核的sql开始前添加注释来指定远端服务器,并在sql的前后添加特殊标识以区分待审核语句,示例如下:
/*--user=root;--password=root;--host=127.0.0.1;--check=1;--port=3306;*/
inception_magic_start;
use test;
create table t1(id int primary key);
inception_magic_commit;
测试案例
1、python测试脚本
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import pymysql
import prettytable as pt
tb = pt.PrettyTable()
#修改为自己线上服务器连接信息
sql = '''/*--user=root;--password=xxx;--host=xxx;--check=0;--port=3306;--execute=1;--backup=1;*/
inception_magic_start;
use testdb;
create table t1(id int primary key,c1 int);
insert into t1(id,c1) values(1,1);
inception_magic_commit;'''
conn = pymysql.connect(host='127.0.0.1', user='', passwd='',
db='', port=4000, charset="utf8mb4")
cur = conn.cursor()
ret = cur.execute(sql)
result = cur.fetchall()
cur.close()
conn.close()
tb.field_names = [i[0] for i in cur.description]
for row in result:
tb.add_row(row)
print(tb)
2、执行结果
3、线上库结果
4、备份库结果
参考文献:https://hanchuanchuan.github.io/goInception/zh/
特别感谢inception作者王竹峰老师、goinception作者韩川川老师!