Monit:開源伺服器監控工具

飛鴻影~發表於2017-03-12

Monit是一個跨平臺的用來監控Unix/linux系統(比如Linux、BSD、OSX、Solaris)的工具。Monit特別易於安裝,而且非常輕量級(只有500KB大小),並且不依賴任何第三方程式、外掛或者庫。

Monit可以監控伺服器程式狀態、HTTP/TCP狀態碼、伺服器資源變化、檔案系統變動等等,根據這些變化,可以設定郵件報警、重啟程式或服務。易於安裝、輕量級的實現以及強大的功能,讓Monit成為一個理想的後備監控工具。

官網:https://mmonit.com/monit
文件:https://mmonit.com/monit/documentation/monit.html
最新版本:https://mmonit.com/monit/dist/monit-5.20.0.tar.gz

注意:Monit是一個開源工具,但M/Monit是收費的。

安裝

yum install monit

當然也可以下載原始碼安裝。

當前使用版本:

# monit -V
This is Monit version 5.17.1
Built with ssl, with pam and with large files
Copyright (C) 2001-2016 Tildeslash Ltd. All Rights Reserved.

常用命令

monit -t # 配置檔案檢測
monit # 啟動monit daemon
monit -c /var/monit/monitrc # 啟動monit daemon時指定配置檔案
monit reload # 當更新了配置檔案需要過載
monit status # 檢視所有服務狀態
monit status nginx # 檢視nginx服務狀態
monit stop all # 停止所有服務
monit stop nginx # 停止nginx服務
monit start all # 啟動所有服務
monit start nginx # 啟動nginx服務
monit -V # 檢視版本

配置檔案

使用yum安裝預設配置檔案在:

/etc/monitrc # 主配置檔案
/etc/monit.d/ # 單獨配置各項服務

為了保護控制檔案和密碼的安全性,monitrc必須具有讀寫許可權不超過0700(u=xrw,g=,o=)。

主配置檔案主要配置全域性:
/etc/monitrc

## Global section
set daemon 30

set logfile syslog

# 郵箱設定
set mailserver xxx@xxx
username "xxx" password "xxx"
# using ssl
set alert xxx@xxx
set alert xxx@xxx #可以設定多個

set mail-format {
from: xxx@xxx
subject: [$SERVICE] $EVENT
message:
[$SERVICE] $EVENT

Date: $DATE
Action: $ACTION
Host: $HOST
Description: $DESCRIPTION

Your faithful employee,
Monit }

# 設定web服務認證
set httpd port 2812 and
# ssl enable
# pemfile /etc/certs/monit.pem
# use address all # only accept connection from localhost
allow 127.0.0.1 # 允許localhost連線
allow admin:monit # web登入的使用者名稱和密碼
## Services

## Includes
include /etc/monit.d/*

配置檔案關鍵字:
`if`, `and`, `with(in)`, `has`, `us(ing|e)`, `on(ly)`, `then`, `for`, `of` 。

如何監控

基本流程

1.修改主配置檔案
2.在/etc/monit.d/增加指定服務的配置檔案,例如/etc/monit.d/nginx。配置變寫完畢,使用下列,命令檢測是否正確:

monit -t

3.啟動monit:

monit

4.啟動所有服務或者單個服務:

monit start all

5.若修改了配置檔案,過載配置:

monit reload

6.使用下面命令檢視監控狀態:

monit status

控制檯輸出:

$ monit status
The Monit daemon 5.17.1 uptime: 4d 15h 45m 

Process `nginx`
  status                            Running
  monitoring status                 Monitored
  pid                               20563
  parent pid                        1
  uid                               0
  effective uid                     0
  gid                               0
  uptime                            3d 22h 36m 
  threads                           1
  children                          2
  memory                            820 kB
  memory total                      7.3 MB
  memory percent                    0.0%
  memory percent total              0.2%
  cpu percent                       0.0%
  cpu percent total                 0.0%
  data collected                    Sat, 18 Feb 2017 10:09:56

System `iZ28s4jxu17Z`
  status                            Running
  monitoring status                 Monitored
  load average                      [0.03] [0.06] [0.06]
  cpu                               8.4%us 0.8%sy 0.2%wa
  memory usage                      1.5 GB [41.2%]
  swap usage                        0 B [0.0%]
  data collected                    Sat, 18 Feb 2017 10:09:56

或者瀏覽器輸入http://localhost:2812登入網頁版檢視實時狀態。

設定錯誤提醒

Monit預設情況下如果一個服務失敗只傳送一個通知:

alert foo@bar

如果您希望在服務保持處於失敗狀態時每十個週期通知一次,您可以使用:

alert foo@bar with reminder on 10 cycles

同樣,如果您想在每個失敗的週期獲得通知,您可以使用:

alert foo@bar with reminder on 1 cycle

要禁止某些使用者和服務的警報,可以在服務檢查的區域性配置裡新增語句:

noalert mail-address

服務型別

首先需要理解在monit裡什麼是服務(service)。看監控語法:

check <型別> <服務名> [PATH <path>] [ADDRESS <host address>]

其中型別是monit支援的監控型別,一共有:system、file、process、fifo、filesystem、directory、host、network、program。
服務名必需是英文且唯一,不可以出現重複!
後面的帶[]是根據型別需要新增的。

服務型別語法

每個服務條目由關鍵字組成check,後面是服務型別。每個條目需要唯一的描述性名稱,可以自由選擇。此名稱由Monit用於在內部和與使用者的所有互動中引用該服務。

目前,支援九種型別的檢查語句:

程式

CHECK PROCESS <unique name> <PIDFILE <path> | MATCHING <regex>>

<path>是程式的pid檔案的絕對路徑。pid檔案是一個包含程式唯一ID的檔案。如果pid檔案不存在或不包含正在執行的程式的PID編號,則Monit將呼叫該條目的start方法(如果已定義)。

<regex>是使用PID檔案的替代方法,並使用程式名稱模式匹配來查詢要監視的程式。選擇具有最長正常執行時間的最頂部匹配的父級,因此如果程式名稱是唯一的,則此檢查形式是最有用的。應該儘可能使用Pid檔案,因為它定義了預期的PID。您可以測試一個程式是否匹配來自命令列使用的模式monit procmatch “regex-pattern”。這將列出匹配或不匹配的所有程式,regex模式。

檔案

CHECK FILE <unique name> PATH <path>

<path>是檔案的絕對路徑。如果檔案不存在,Monit將呼叫該條目的start方法(如果已定義),如果<path>不指向常規檔案型別(例如目錄),Monit將禁用此條目的監視。如果Monit在被動模式下執行或者沒有定義start方法,Monit只會在錯誤時傳送警報。

Fifo

CHECK FIFO <unique name> PATH <path>

<path>是fifo的絕對路徑。如果fifo不存在,Monit將定義呼叫該條目的start方法,如果<path>沒有指向fifo型別(例如目錄),Monit將禁用對該條目的監視。如果Monit在被動模式下執行或者沒有定義start方法,Monit只會在錯誤時傳送警報。

檔案系統

CHECK FILESYSTEM <unique name> PATH <path>

<path>是裝置/磁碟,安裝點,檔案或作為檔案系統一部分的目錄的路徑。建議直接使用塊特殊檔案(例如Linux上的/dev/hda1或Solaris上的/dev/dsk/c0t0d0s1等)如果使用掛載點(例如/data),請注意檔案系統是解除安裝的測試仍然是真的,因為掛載點存在。

如果檔案系統不可用,Monit將呼叫該條目的start方法(如果已定義)。如果不指向檔案系統,Monit將禁用對此條目的監視。如果Monit在被動模式下執行或者沒有定義start方法,Monit只會在錯誤時傳送警報。

目錄

CHECK DIRECTORY <unique name> PATH <path>

<path>是目錄的絕對路徑。如果目錄不存在,Monit將呼叫該條目的start方法(如果已定義)。如果<path>不指向目錄,monit將禁用對此條目的監視。如果Monit在被動模式下執行或者沒有定義啟動方法,Monit只會在錯誤時傳送警報。

遠端主機

CHECK HOST <unique name> ADDRESS <host address>

主機地址可以指定為主機名字串或點分十進位制格式的IP地址字串。例如,tildeslash.com或“64.87.72.95”。

系統

CHECK SYSTEM <unique name>

的唯一的名稱通常是本地主機名,而是可以使用任何描述性名稱。如果使用變數$ HOST作為名稱,它將擴充套件為主機名。此檢查允許監控一般系統資源,如CPU使用率,總記憶體使用或負載平均。該唯一名稱在郵件警報中用作系統主機名,在M/Monit中用作主機條目的初始名稱。

自定義

CHECK PROGRAM <unique name> PATH <executable file> [TIMEOUT <number> SECONDS]

<path>是可執行程式或指令碼的絕對路徑。該狀態測試允許一個檢查程式的退出狀態。如果程式沒有在<number>秒內完成執行,Monit將終止它。預設程式超時為300秒(5分鐘)。程式的輸出被記錄並在使用者介面和警報中可用,預設情況下最大為512B。您可以使用set limits語句自定義限制。

網路

CHECK NETWORK <unique name> <ADDRESS <ipaddress> | INTERFACE <name>>

<ipaddress>是受監視網路介面的IPv4或IPv6地址。也可以在Linux上使用介面名稱,例如“eth0”。

服務檢測時間

可以使用every語句修改服務檢查計劃。

有三種變體:

1.輪詢週期倍數

EVERY [number] CYCLES

2.Cron-style

EVERY [cron]

# [cron]
# * * * * *
# 分 時 日 月 周

3.與Cron-style相反(do-not-check)

NOT EVERY [cron]

示例:
示例1:每兩個週期檢查一次

check process nginx with pidfile /var/run/nginx.pid
every 2 cycles

示例2:在上午8點到下午7點之間檢查每個工作日

check program checkOracleDatabase
with path /var/monit/programs/checkoracle.pl
every "* 8-19 * * 1-5"

示例3:在星期日0AM到3AM之間不要在備份視窗中執行檢查,否則執行具有常規輪詢週期頻率的檢查。

check process mysqld with pidfile /var/run/mysqld.pid
not every "* 0-3 * * 0"

注意不要使用特定的分鐘,因為Monit可能不會在那分鐘執行。

服務重啟限制

Monit提供了一種重啟限制機制,用於服務在較長時間內拒絕啟動或響應的情況。
超時語句的語法如下(關鍵字在大寫):

IF <number> RESTART <number> CYCLE(S) THEN <action>

該行動值是常見的任何一個動作或超時(為向後相容,等於取消監視行動)。

下面是一個示例,如果Monit將在3個週期內重新啟動服務2次,將取消監視服務:

if 2 restarts within 3 cycles then unmonitor

要在禁用監視後使Monit再次檢查服務,請從命令列執行monit monitor servicename。

超時設定自定義exec的示例:

if 5 restarts within 5 cycles then exec "/foo/bar"

停止服務的示例:

if 7 restarts within 10 cycles then stop

服務示例

一個完整的HOST監控服務語法:

check host <service> address <address or ip>
if failed
xxx
then alert
alert xx@xxx

解釋:
第一行是檢查型別為host的服務,需要設定服務名及伺服器地址;
第二行至第四行的意思是中間的預期程式碼xxx如果失敗,則執行then alert
最後一行alert xx@xxx配置區域性推送的郵箱,可選。可以多行,表示配置多個。

第二行至第四行也可以寫成一行:

if failed xxx then alert

下面是示例:

/etc/monit.d/test

## system
check system $HOST
if loadavg (1min) > 4 then alert
if loadavg (5min) > 2 then alert
if cpu usage > 95% for 10 cycles then alert
if memory usage > 75% then alert
if swap usage > 25% then alert

## file
check file apache_bin with path /usr/local/apache/bin/httpd
if failed checksum and
expect the sum 8f7f419955cefa0b33a2ba316cba3659 then unmonitor
if failed permission 755 then unmonitor
if failed uid root then unmonitor
if failed gid root then unmonitor
alert security@foo.bar on {
checksum, permission, uid, gid, unmonitor
} with the mail-format { subject: Alarm! }
group server

## process
check process apache with pidfile /usr/local/apache/logs/httpd.pid
start program = "/etc/init.d/httpd start" with timeout 60 seconds
stop program = "/etc/init.d/httpd stop"
if cpu > 60% for 2 cycles then alert
if cpu > 80% for 5 cycles then restart
if totalmem > 200.0 MB for 5 cycles then restart
if children > 250 then restart
if loadavg(5min) greater than 10 for 8 cycles then stop
if failed host www.tildeslash.com port 80 protocol http
and request "/somefile.html"
then restart
if failed port 443 protocol https with timeout 15 seconds then restart
if 3 restarts within 5 cycles then unmonitor
depends on apache_bin
group server

## filesystem
check filesystem datafs with path /dev/sdb1
start program = "/bin/mount /data"
stop program = "/bin/umount /data"
if failed permission 660 then unmonitor
if failed uid root then unmonitor
if failed gid disk then unmonitor
if space usage > 80% for 5 times within 15 cycles then alert
if space usage > 99% then stop
if inode usage > 30000 then alert
if inode usage > 99% then stop
group server

## file`s timestamp
check file database with path /data/mydatabase.db
if failed permission 700 then alert
if failed uid data then alert
if failed gid data then alert
if timestamp > 15 minutes then alert
if size > 100 MB then exec "/my/cleanup/script" as uid dba and gid dba
## directory permission
check directory bin with path /bin
if failed permission 755 then unmonitor
if failed uid 0 then unmonitor
if failed gid 0 then unmonitor
## remote host
check host myserver with address 192.168.1.1
if failed ping then alert
if failed port 3306 protocol mysql with timeout 15 seconds then alert
if failed port 80 protocol http
and request /some/path with content = "a string"
then alert
## network link status
check network public with interface eth0
if failed link then alert
if changed link then alert
if saturation > 90% then alert
if download > 10 MB/s then alert
if total upload > 1 GB in last hour then alert
## custom program status output
check program myscript with path /usr/local/bin/myscript.sh
if status != 0 then alert

控制檯訪問驗證

訪問Monit Web介面主要通過ALLOW選項進行控制,ALLOW選項用於指定身份驗證並僅授權特定客戶端進行連線。

如果正在使用Monit命令列介面,至少需要一個明文密碼(見下文),否則Monit命令列介面將無法連線到Monit Web介面。

嘗試連線到Monit,但提交錯誤的使用者名稱和/或密碼的客戶端將使用其IP地址記錄。

主機和網路允許列表

Monit維護允許連線的主機和網路的訪問控制列表。您可以新增任意數量的主機,但只允許具有有效域名或其IP地址的主機。

Monit將查詢名稱伺服器以檢查任何嘗試連線的主機。如果主機(客戶端)正在嘗試連線,但無法在訪問列表中找到或無法解決,Monit將立即關閉與客戶端的連線。

配置檔案示例:

set httpd port 2812
  allow localhost
  allow my.other.work.machine.com
  allow 10.1.1.1
  allow 192.168.1.0/255.255.255.0
  allow 10.0.0.0/8

在允許列表中未提及的客戶端,嘗試連線到Monit將被拒絕訪問,並使用其IP地址記錄。

明文使用者和密碼

如果allow語句包含用單獨的“:”字元分隔的使用者名稱和密碼,Monit將使用基本認證。

注意:可以使用特殊字元,但對於非字母數字,必須引用密碼。

句法:

 ALLOW <username>:<password>

PAM

在提供PAM的平臺(如Linux,Mac OS X,FreeBSD,NetBSD)上支援PAM。

句法:

 ALLOW @<group>

其中group是允許訪問Monit的Web介面的組名稱

只讀使用者

最後,可以將一些使用者定義為只讀。只讀使用者可以讀取Monit網頁,但無法訪問按鈕,並且無法從Web介面更改服務。

  set httpd port 2812
      allow admin:password
      allow hauk:password read-only
      allow @admins
      allow @users read-only

通過在 username:password 後使用只讀關鍵字將使用者設定為只讀。在上述示例中,使用者hauk被定義為只讀使用者,而admin使用者具有所有訪問許可權。

實踐

監聽Nginx、php-fpm及API介面

/etc/monit.d/http

# check nginx process
check process nginx with pidfile /run/nginx.pid
start program = "/usr/local/nginx/sbin/nginx " with timeout 10 seconds
stop program = "/usr/local/nginx/sbin/nginx -s stop"
if changed pid then restart

# check php-fpm process
check process php-fpm with MATCHING php-fpm
start program = "/usr/local/php/sbin/php-fpm" with timeout 10 seconds
stop program = "/usr/bin/killall php-fpm" with timeout 10 seconds
if failed port 9000 for 3 cycles then restart

# check http status
check host dev_xxx_http address xxx
start program = "/usr/local/php/sbin/php-fpm ; /usr/local/nginx/sbin/nginx -s reload" with timeout 10 seconds
stop program = "/usr/bin/killall php-fpm ; /usr/local/nginx/sbin/nginx -s stop" with timeout 10 seconds
if failed
port 80
protocol http
and status = 200
for 3 cycles
then restart
#alert xxx@xxx #可以單獨設定新的通知者
#alert xxx@xxx

if failed
port 80
protocol http
request "/Api/Login/Get_Userinfo/"
and status = 200
for 3 cycles
then restart

監聽TCP

/etc/monit.d/tcp

check host dev_xxx_swoole_xxx address xxx
start program = "/usr/local/php/bin/php Server.php" with timeout 10 seconds
stop program = "/usr/bin/kill -9 $(ps -aux|grep -E `Server|swoole_server`|grep -v grep|awk `{print $2}`)" with timeout 10 seconds
if failed port xxx type tcp for 3 cycles then restart

原釋出於部落格園。


相關文章