为 Monit 监控 MySQL 设置 Slack Alerts

为 Monit 监控 MySQL 设置 Slack Alerts

尝试设置Slack 警报适用于 Monit 和 MySQL/MariaDB,但无法编写 MySQL 检查脚本。如果 MySQL 停止并收到电子邮件警报,我的 monit 可以成功运行 - 但我想要 slack 警报。

Slack 警报脚本

#!/usr/bin/ruby

require 'net/https'
require 'json'

uri = URI.parse("https://hooks.slack.com/services/XXXXXXXXX/YYYYYYYYY/ZZZZZZZZZZZZZZZZZZZZZZZZ")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.request_uri, {'Content-Type' => 'application/json'})
request.body = {
    "channel"  => "#general",
    "username" => "mmonit",
    "text"     => "[#{ENV['MONIT_HOST']}] #{ENV['MONIT_SERVICE']} - #{ENV['MONIT_DESCRIPTION']}"
}.to_json
response = http.request(request)
puts response.body

我的 mysql conf 由 monitrc 调用

 check process mysqld with pidfile /var/run/mysqld/mysqld.pid
   group database
   group mysql
   start program = "/etc/init.d/mariadb start"
   stop  program = "/etc/init.d/mariadb stop"
   if failed host localhost port 3306 protocol mysql with timeout 15 seconds for 3 times within 4 cycles then restart
   if failed unixsocket /var/run/mysqld/mysqld.sock protocol mysql for 3 times within 4 cycles then restart
   if 5 restarts with 5 cycles then timeout
   depend mysql_bin
   depend mysql_rc

 check file mysql_bin with path /usr/sbin/mysqld
   group mysql
   include /etc/monit/templates/rootbin

 check file mysql_rc with path /etc/init.d/mariadb
   group mysql
   include /etc/monit/templates/rootbin

包含在 monitrc 脚本中检查 mysql,然后执行脚本来提醒 slack

check program check-mysql with path "/opt/monit/check_mysql.sh"
 if status != 0 then exec /path/to/slack.rb

所以我必须添加一个check-mysql.sh脚本——但是我在这个脚本中使用什么内容呢?

答案1

#!/bin/bash

if ! pgrep mysqld >/dev/null 2>&1; then
    /path/to/slack.rb
fi

Replace /path/to/slack.rb with the actual path to your Slack alert script.
Next, make it executable using chmod +x /opt/monit/check_mysql.sh:

check program check-mysql with path "/opt/monit/check_mysql.sh"
 if status != 0 then exec /path/to/slack.rb

相关内容