saltStack的event接口通过mysql数据库接收SaltStack批量管理日志
event是一个本地的ZeroMQ PUB Interface,event是一个开放的系统,用于发送信息通知salt或其他的操作系统。每个event都有一个标签。事件标签允许快速制定过滤事件。除了标签之外,每个事件都有一个数据结构。这个数据结构是一个dict类型,其中包含关于事件的信息。
在master上直接将返回结果写入mysql
1.event接口测试
测试脚本salt-event.py内容如下:
import salt.utils.event
event = salt.utils.event.MasterEvent('/var/run/salt/master')
for data in event.iter_events(full=True):
print data
print '------'
python salt-event.py //执行这个脚本
然后再开一个新的master终端进行salt操作:
salt '*' test.ping
就可以看到返回结果了。结果正常应该如下:
python salt-event.py
{'tag': 'salt/event/new_client', 'data': {'_stamp': '2016-08-07T02:54:56.612273'}}
------
{'tag': '20160807105456636003', 'data': {'_stamp': '2016-08-07T02:54:56.636483', 'minions': ['192.168.3.108', 'minion_client01.DHCP']}}
------
{'tag': 'salt/job/20160807105456636003/new', 'data': {'tgt_type': 'glob', 'jid': '20160807105456636003', 'tgt': '*', '_stamp': '2016-08-07T02:54:56.637362', 'user': 'root', 'arg': [], 'fun': 'test.ping', 'minions': ['192.168.3.108', 'minion_client01.DHCP']}}
------
{'tag': 'salt/job/20160807105456636003/ret/192.168.3.108', 'data': {'fun_args': [], 'jid': '20160807105456636003', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', '_stamp': '2016-08-07T02:54:56.836851', 'fun': 'test.ping', 'id': '192.168.3.108'}}
------
{'tag': 'salt/job/20160807105456636003/ret/minion_client01.DHCP', 'data': {'fun_args': [], 'jid': '20160807105456636003', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', '_stamp': '2016-08-07T02:54:56.845030', 'fun': 'test.ping', 'id': 'minion_client01.DHCP'}}
------
至此event接口测试结束,测试证明event接口是能正常工作的。
2.编写自定义return脚本
vim salt_event_to_mysql.py
#!/bin/env python
#coding=utf8
# Import python libs
import json
# Import salt modules
import salt.config
import salt.utils.event
# Import third part libs
import MySQLdb
__opts__ = salt.config.client_config('/etc/salt/master')
#create MySQL connect
#conn = MySQLdb.connect(host=__opts__['mysql.host'],user=__opts__['mysql.user'],passwd=__opts__['mysql.pass'],db=__opts__['mysql.db'],port=__opts__['mysql.port'])
conn = MySQLdb.connect(host='192.168.3.87',user='salt',passwd='salt',db='salt',port=3306)
cursor = conn.cursor()
# Listen Salt Master Event System
event = salt.utils.event.MasterEvent(__opts__['sock_dir'])
for eachevent in event.iter_events(full=True):
ret = eachevent['data']
if "salt/job/" in eachevent['tag']:
#Return Event
if ret.has_key('id') and ret.has_key('return'):
#Ignore saltutil.find_job event
if ret['fun'] == "saltutil.find_job":
continue
sql = '''INSERT INTO `salt_returns`
(`fun`,`jid`,`return`,`id`,`success`,`full_ret` )
VALUES (%s,%s,%s,%s,%s,%s)'''
cursor.execute(sql,(ret['fun'],ret['jid'],
json.dumps(ret['return']),ret['id'],
ret['success'],json.dumps(ret)))
cursor.execute("COMMIT")
# Other Event
else:
pass
保存退出
注意:
MySQLdb.connect(host=__opts__['mysql.host'],user=__opts__['mysql.user'],passwd=__opts__['mysql.pass'],db=__opts__['mysql.db'],port=__opts__['mysql.port'])
要换成自己的实际数据库地址、数据库用户、密码,如:
conn = MySQLdb.connect(host='192.168.3.87',user='salt',passwd='salt',db='salt',port=3306)
3.修改master的配置文件
vim /etc/salt/master
mysql.host: '192.168.3.87' # mysql服务器的IP地址
mysql.user: 'salt' # mysql数据库的用户名,需要跟后面授权的用户名一致
mysql.pass: 'salt' # mysql数据库的密码,需要跟后面授权的密码一致
mysql.db: 'salt' # mysql数据库的名称
mysql.port: 3306 # 使用端口为3306
mysql.host: '192.168.3.87' # mysql服务器的IP地址
mysql.user: 'salt' # mysql数据库的用户名,需要跟后面授权的用户名一致
mysql.pass: 'salt' # mysql数据库的密码,需要跟后面授权的密码一致
mysql.db: 'salt' # mysql数据库的名称
mysql.port: 3306 # 使用端口为3306
保存退出
4.在master上安装MySQL-python
yum -y install MySQL-python
创建数据库
CREATE DATABASE `salt`DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;
USE `salt`;
DROP TABLE IF EXISTS `jids`;
CREATE TABLE `jids`
(`jid` varchar(255) NOT NULL,`load` mediumtext NOT NULL,UNIQUE KEY `jid` (`jid`) )
ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `salt_returns`;
CREATE TABLE `salt_returns`
(`fun` varchar(50) NOT NULL,`jid` varchar(255) NOT NULL,`return` mediumtext NOT NULL,`id` varchar(255) NOT NULL,`success` varchar(10) NOT NULL,`full_ret` mediumtext NOT NULL,KEY `id` (`id`),KEY `jid` (`jid`),KEY `fun` (`fun`) )
ENGINE=InnoDB DEFAULT CHARSET=utf8;
授权
GRANT ALL PRIVILEGES ON salt.* to 'salt'@'%' identified by 'salt';
flush privileges;
5.在master的后台执行自定义return脚本
python salt_event_to_mysql.py &
6.开一个新的master终端进行测试
salt '*' test.ping
7.在mysql上看是否已经将数据写入数据库
mysql -uroot -p
输入密码之后进入mysql数据库
use salt
show tables;
select * from salt_returns \G
如果出现如下结果表示插入成功:
mysql> select * from salt_returns \G
*************************** 1. row ***************************
fun: test.ping
jid: 20160807111832766142
return: true
id: 192.168.3.108
success: 1
full_ret: {"fun_args": [], "jid": "20160807111832766142", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2016-08-07T03:18:32.950841", "fun": "test.ping", "id": "192.168.3.108"}
*************************** 2. row ***************************
fun: test.ping
jid: 20160807111832766142
return: true
id: minion_client01.DHCP
success: 1
full_ret: {"fun_args": [], "jid": "20160807111832766142", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2016-08-07T03:18:32.953034", "fun": "test.ping", "id": "minion_client01.DHCP"}
在master上直接将返回结果写入mysql
1.event接口测试
测试脚本salt-event.py内容如下:
import salt.utils.event
event = salt.utils.event.MasterEvent('/var/run/salt/master')
for data in event.iter_events(full=True):
print data
print '------'
python salt-event.py //执行这个脚本
然后再开一个新的master终端进行salt操作:
salt '*' test.ping
就可以看到返回结果了。结果正常应该如下:
python salt-event.py
{'tag': 'salt/event/new_client', 'data': {'_stamp': '2016-08-07T02:54:56.612273'}}
------
{'tag': '20160807105456636003', 'data': {'_stamp': '2016-08-07T02:54:56.636483', 'minions': ['192.168.3.108', 'minion_client01.DHCP']}}
------
{'tag': 'salt/job/20160807105456636003/new', 'data': {'tgt_type': 'glob', 'jid': '20160807105456636003', 'tgt': '*', '_stamp': '2016-08-07T02:54:56.637362', 'user': 'root', 'arg': [], 'fun': 'test.ping', 'minions': ['192.168.3.108', 'minion_client01.DHCP']}}
------
{'tag': 'salt/job/20160807105456636003/ret/192.168.3.108', 'data': {'fun_args': [], 'jid': '20160807105456636003', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', '_stamp': '2016-08-07T02:54:56.836851', 'fun': 'test.ping', 'id': '192.168.3.108'}}
------
{'tag': 'salt/job/20160807105456636003/ret/minion_client01.DHCP', 'data': {'fun_args': [], 'jid': '20160807105456636003', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', '_stamp': '2016-08-07T02:54:56.845030', 'fun': 'test.ping', 'id': 'minion_client01.DHCP'}}
------
至此event接口测试结束,测试证明event接口是能正常工作的。
2.编写自定义return脚本
vim salt_event_to_mysql.py
#!/bin/env python
#coding=utf8
# Import python libs
import json
# Import salt modules
import salt.config
import salt.utils.event
# Import third part libs
import MySQLdb
__opts__ = salt.config.client_config('/etc/salt/master')
#create MySQL connect
#conn = MySQLdb.connect(host=__opts__['mysql.host'],user=__opts__['mysql.user'],passwd=__opts__['mysql.pass'],db=__opts__['mysql.db'],port=__opts__['mysql.port'])
conn = MySQLdb.connect(host='192.168.3.87',user='salt',passwd='salt',db='salt',port=3306)
cursor = conn.cursor()
# Listen Salt Master Event System
event = salt.utils.event.MasterEvent(__opts__['sock_dir'])
for eachevent in event.iter_events(full=True):
ret = eachevent['data']
if "salt/job/" in eachevent['tag']:
#Return Event
if ret.has_key('id') and ret.has_key('return'):
#Ignore saltutil.find_job event
if ret['fun'] == "saltutil.find_job":
continue
sql = '''INSERT INTO `salt_returns`
(`fun`,`jid`,`return`,`id`,`success`,`full_ret` )
VALUES (%s,%s,%s,%s,%s,%s)'''
cursor.execute(sql,(ret['fun'],ret['jid'],
json.dumps(ret['return']),ret['id'],
ret['success'],json.dumps(ret)))
cursor.execute("COMMIT")
# Other Event
else:
pass
保存退出
注意:
MySQLdb.connect(host=__opts__['mysql.host'],user=__opts__['mysql.user'],passwd=__opts__['mysql.pass'],db=__opts__['mysql.db'],port=__opts__['mysql.port'])
要换成自己的实际数据库地址、数据库用户、密码,如:
conn = MySQLdb.connect(host='192.168.3.87',user='salt',passwd='salt',db='salt',port=3306)
3.修改master的配置文件
vim /etc/salt/master
mysql.host: '192.168.3.87' # mysql服务器的IP地址
mysql.user: 'salt' # mysql数据库的用户名,需要跟后面授权的用户名一致
mysql.pass: 'salt' # mysql数据库的密码,需要跟后面授权的密码一致
mysql.db: 'salt' # mysql数据库的名称
mysql.port: 3306 # 使用端口为3306
mysql.host: '192.168.3.87' # mysql服务器的IP地址
mysql.user: 'salt' # mysql数据库的用户名,需要跟后面授权的用户名一致
mysql.pass: 'salt' # mysql数据库的密码,需要跟后面授权的密码一致
mysql.db: 'salt' # mysql数据库的名称
mysql.port: 3306 # 使用端口为3306
保存退出
4.在master上安装MySQL-python
yum -y install MySQL-python
创建数据库
CREATE DATABASE `salt`DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;
USE `salt`;
DROP TABLE IF EXISTS `jids`;
CREATE TABLE `jids`
(`jid` varchar(255) NOT NULL,`load` mediumtext NOT NULL,UNIQUE KEY `jid` (`jid`) )
ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `salt_returns`;
CREATE TABLE `salt_returns`
(`fun` varchar(50) NOT NULL,`jid` varchar(255) NOT NULL,`return` mediumtext NOT NULL,`id` varchar(255) NOT NULL,`success` varchar(10) NOT NULL,`full_ret` mediumtext NOT NULL,KEY `id` (`id`),KEY `jid` (`jid`),KEY `fun` (`fun`) )
ENGINE=InnoDB DEFAULT CHARSET=utf8;
授权
GRANT ALL PRIVILEGES ON salt.* to 'salt'@'%' identified by 'salt';
flush privileges;
5.在master的后台执行自定义return脚本
python salt_event_to_mysql.py &
6.开一个新的master终端进行测试
salt '*' test.ping
7.在mysql上看是否已经将数据写入数据库
mysql -uroot -p
输入密码之后进入mysql数据库
use salt
show tables;
select * from salt_returns \G
如果出现如下结果表示插入成功:
mysql> select * from salt_returns \G
*************************** 1. row ***************************
fun: test.ping
jid: 20160807111832766142
return: true
id: 192.168.3.108
success: 1
full_ret: {"fun_args": [], "jid": "20160807111832766142", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2016-08-07T03:18:32.950841", "fun": "test.ping", "id": "192.168.3.108"}
*************************** 2. row ***************************
fun: test.ping
jid: 20160807111832766142
return: true
id: minion_client01.DHCP
success: 1
full_ret: {"fun_args": [], "jid": "20160807111832766142", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2016-08-07T03:18:32.953034", "fun": "test.ping", "id": "minion_client01.DHCP"}