源码编译varnish和 monit 使用monit来监控varnish 进程
Aws EC2
Cento5.7 i386
Varnish-3.0.2 revision 55e70a4
monit-5.3.2.tar.gz
编写管理脚本前的说明
++++++++++++++++
1. 修改varnish rpm 安装方式时的service管理脚本用于 varnish源码编译后的service管理。
2.文件/etc/init.d/varnish 主要修改的地方如下
VARNISH_VCL_CONF=/usr/local/varnish/etc/varnish/default.vcl
pidfile=/var/run/varnish.pid
exec="/usr/local/varnish/sbin/varnishd"
reload_exec="/usr/local/varnish/sbin/varnish_reload_vcl"
prog="varnishd"
config="/etc/sysconfig/varnish"
lockfile="/var/lock/subsys/varnish"
VARNISH_SECRET_FILE=/etc/varnish/secret
exec="/usr/local/varnish/sbin/varnishd"
VARNISHADM="/usr/local/varnish/bin/varnishadm $secret -T $VARNISH_ADMIN_LISTEN_ADDRESS:$VARNISH_ADMIN_LISTEN_PORT"
3.如果启用了密码文件,要保证它不不为空: 如 /etc/varnish/secret 否则varnish服务是起不来的
4.varnish的编译后安装目录为/usr/local/varnish以下几个目录和文件要存在并做设置执行权限
/etc/varnish
/etc/sysconfig/varnish
echo "oursect">/etc/varnish/secret
chmod 755 /etc/init.d/varnish
chmod 755 /usr/local/varnish/sbin/varnish_reload_vcl
5. varnish用户要存在
6.分配给varnish内存和打开文件数( ulimit -l, ulimit -n)通过命令先设置好:ulimit -SH -n 131072
查看当前系统状态 ulimit -l
ulimit -n
7.monit内置一个管理服务通过3500的默认端口,这里只允许本地查看监控状态,如果要通过远程http查看其状态,则要修改两个use address 0.0.0.0和allow ip
set httpd port 3500 and
use address localhost
allow localhost
allow monit:userpassord
//通过web http查看monit状态,时用到的 用户和密码
++++++++++++++++
第一部分varnish的安装与管理脚本
(1)安装 varnish-cache-3.0.2
依赖性
Build dependencies on Debian / Ubuntu
In order to build Varnish from source you need a number of packages installed. On a Debian or Ubuntu system these are:
autotools-dev
automake1.9
libtool
autoconf
libncurses-dev
xsltproc
groff-base
libpcre3-dev
pkg-config
Build dependencies on Red Hat / CentOS
To build Varnish on a Red Hat or CentOS system you need the following packages installed:
automake
autoconf
libtool
ncurses-devel
libxslt
groff
pcre-devel
pkgconfig
wget -c
http://repo.varnish-cache.org/source/varnish-3.0.2.tar.gz
tar -zxvf varnish-3.0.2.tar.gz
chown root.root -R varnish-3.0.2
cd varnish-3.0.2
./configure
--prefix=/usr/local/varnish
make
make check
make install
ldconfig
(2)将如下两行放在 /etc/profile文件中来设置系统变量。
export VARNISH_HOME=/usr/local/varnish
export PATH=$PATH:$VARNISH_HOME:$VARNISH_HOME/sbin:$VARNISH_HOME/bin
(3)varnish VCL文件配置
vi /usr/local/varnish/etc/varnish/default.vcl
# Default backend definition. The Seting is just for varnish3.0.X
backend default {
.host = "127.0.0.1";
.port = "8080";
.connect_timeout = 600s;
.first_byte_timeout = 600s;
.between_bytes_timeout = 600s;
.max_connections = 800;
}
sub vcl_recv {
set req.backend = default;
set req.grace = 5m;
if (req.restarts == 0) {
if (req.http.x-forwarded-for) {
set req.http.X-Forwarded-For = req.http.X-Forwarded-For + ", " + client.ip;
}
else {
set req.http.X-Forwarded-For = client.ip;
}
}
# Properly handle different encoding types
if (req.http.Accept-Encoding) {
if (req.url ~ "\.(jpg|jpeg|png|gif|gz|tgz|bz2|tbz|mp3|ogg|swf)$") {
remove req.http.Accept-Encoding;
} elsif (req.http.Accept-Encoding ~ "gzip") {
set req.http.Accept-Encoding = "gzip";}
elsif (req.http.Accept-Encoding ~ "deflate") {
set req.http.Accept-Encoding = "deflate";}
else {
remove req.http.Accept-Encoding;
}
}
if (req.http.Cache-Control ~ "no-cache") {
return (pass);
}
if (req.request != "GET" &&
req.request != "HEAD" &&
req.request != "PUT" &&
req.request != "POST" &&
req.request != "TRACE" &&
req.request != "OPTIONS" &&
req.request != "DELETE") {
#
return (pipe);
}
if (req.request != "GET" && req.request != "HEAD") {
#
return (pass);
}
if (req.http.Authorization || req.http.Cookie) {
return (pass);
}
if (req.http.host ~ "(os.mysite.com)|(re.mysite.com)|(hi.mysite.com)|(mysite.com.tw)|(mysite.com.cn)|(mysite.jp)|(mysite.com)"){
set req.http.host = "www.mysite.com";
}
## This would make varnish skip caching for this particular site
# if (req.http.host ~ "internet-safety.yoursphere.com$") {
#
return (pass);
# }
# This makes varnish skip caching for every site except this one
# Commented out here, but shown for sake of some use cases
# if (req.http.host != "sitea.com") {
#
return (pass);
#}
## Remove has_js and Google Analytics cookies.
set req.http.Cookie = regsuball(req.http.Cookie, "(^|;\s*)(__[a-z]+|has_js)=[^;]*", "");
## Remove a ";" prefix, if present.
set req.http.Cookie = regsub(req.http.Cookie, "^;\s*", "");
## Remove empty cookies.
if (req.http.Cookie ~ "^\s*$") {
unset req.http.Cookie;
}
# Pass server-status
if (req.url ~ ".*/server-status$") {
return (pass);
}
# Don't cache install.php update.php cron.php
if (req.url ~ "install.php|update.php|cron.php") {
return (pass);
}
# Cache these extension file ,but No point to cache their cookie
if (req.url ~ "\.(js|css|jpg|jpeg|png|gif|gz|tgz|bz2|tbz|mp3|ogg|swf)$") {
unset req.http.Cookie;
return (lookup);
}
# Don't cache Drupal logged-in user sessions
# LOGGED_IN is the cookie that earlier version of Pressflow sets
# VARNISH is the cookie which the varnish.module sets
if (req.http.Cookie ~ "(VARNISH|DRUPAL_UID|LOGGED_IN)") {
return (pass);
}
return (lookup);
}
sub vcl_fetch {
# Grace to allow varnish to serve content if backend is lagged
set beresp.grace = 5m;
# These status codes should always pass through and never cache.
if (beresp.status == 404 || beresp.status == 503 || beresp.status == 500) {
set beresp.http.X-Cacheable = "NO: beresp.status";
set beresp.http.X-Cacheable-status = beresp.status;
return (hit_for_pass);
}
if (req.url ~ "\.(js|css|jpg|jpeg|png|gif|gz|tgz|bz2|tbz|mp3|ogg|swf)$") {
unset beresp.http.set-cookie;
}
if (req.url ~ "(^/files/)|(^/sites/)") {
unset req.http.Set-Cookie;
}
#if (beresp.ttl <= 0s) {
#
set beresp.http.X-Cacheable = "NO";
#
return (hit_for_pass);
#}
#else {
unset beresp.http.expires;
if (req.url ~ "(.js|.css)$") {
set beresp.ttl = 60m; // js and css files ttl 60 minutes
}
elsif (req.url ~ "(^/articles/)|(^/tags/)|(^/taxonomy/)") {
set beresp.ttl = 10m; // list page ttl 10 minutes
}
elsif (req.url ~ "^/article/") {
set beresp.ttl = 5m; // article ttl 5 minutes
}
else{
set beresp.ttl = 45m; // default ttl 45 minutes
}
set beresp.http.magicmarker = "1";
set beresp.http.X-Cacheable = "YES";
#}
return (deliver);
}
sub vcl_deliver {
if (resp.http.magicmarker) {
unset resp.http.magicmarker;
set resp.http.age = "0";
}
# add cache hit data
if (obj.hits > 0) {
set resp.http.X-Cache = "HIT";
set resp.http.X-Cache-Hits = obj.hits;
}
else {
set resp.http.X-Cache = "MISS";
}
# hidden some sensitive http header returning to client, when the cache server received from backend server response
#remove resp.http.X-Varnish;
#remove resp.http.Via;
##remove resp.http.Age;
#remove resp.http.X-Powered-By;
#remove resp.http.X-Drupal-Cache;
return (deliver);
}
sub vcl_error {
if (obj.status == 503 && req.restarts < 5) {
set obj.http.X-Restarts = req.restarts;
return (restart);
}
}
sub vcl_hit {
if (req.http.Cache-Control ~ "no-cache") {
#Ignore requests via proxy caches,
IE users and badly behaved crawlers
#like msnbot that send no-cache with every request.
if (! (req.http.Via || req.http.User-Agent ~ "bot|MSIE")) {
set obj.ttl = 0s;
return (restart);
}
}
return(deliver);
}
sub vcl_miss {
return (fetch);
}
以上几步就完成了varnis的安装和配置了,接下来就是写脚本来管理 varnish了。
(4) varnish 启动服务管理脚本:
vi /etc/init.d/varnish
#!/bin/sh
#
# varnish Control the varnish HTTP accelerator
# chmod 755
/etc/init.d/varnish
# chkconfig: - 90 10
# description: Varnish is a high-perfomance HTTP accelerator
# processname: varnishd
# config: /etc/sysconfig/varnish
# pidfile: /var/run/varnish/varnishd.pid
### BEGIN INIT INFO
# Provides: varnish
# Required-Start: $network $local_fs $remote_fs
# Required-Stop: $network $local_fs $remote_fs
# Default-Start:
# Default-Stop:
# Should-Start: $syslog
# Short-Description: start and stop varnishd
# Description: Varnish is a high-perfomance HTTP accelerator
### END INIT INFO
# Source function library.
. /etc/init.d/functions
retval=0
pidfile=/var/run/varnish.pid
exec="/usr/local/varnish/sbin/varnishd"
reload_exec="/usr/local/varnish/sbin/varnish_reload_vcl"
prog="varnishd"
config="/etc/sysconfig/varnish"
lockfile="/var/lock/subsys/varnish"
# Include varnish defaults
[ -e /etc/sysconfig/varnish ] && . /etc/sysconfig/varnish
start() {
if [ ! -x $exec ]
then
echo $exec not found
exit 5
fi
if [ ! -f $config ]
then
echo $config not found
exit 6
fi
echo -n "Starting varnish HTTP accelerator: "
# Open files (usually 1024, which is way too small for varnish)
ulimit -n ${NFILES:-131072}
# Varnish wants to lock shared memory log in memory.
ulimit -l ${MEMLOCK:-82000}
# $DAEMON_OPTS is set in /etc/sysconfig/varnish. At least, one
# has to set up a backend, or /tmp will be used, which is a bad idea.
if [ "$DAEMON_OPTS" = "" ]; then
echo "\$DAEMON_OPTS empty."
echo -n "Please put configuration options in $config"
return 6
else
# Varnish always gives output on STDOUT
daemon
$exec -P $pidfile "$DAEMON_OPTS" > /dev/null 2>&1
retval=$?
if [ $retval -eq 0 ]
then
touch $lockfile
echo_success
echo
else
echo_failure
echo
fi
return $retval
fi
}
stop() {
echo -n "Stopping varnish HTTP accelerator: "
killproc $prog
retval=$?
echo
[ $retval -eq 0 ] && rm -f $lockfile
return $retval
}
restart() {
stop
start
}
reload() {
if [ "$RELOAD_VCL" = "1" ]
then
$reload_exec
else
force_reload
fi
}
force_reload() {
restart
}
rh_status() {
status $prog
}
rh_status_q() {
rh_status >/dev/null 2>&1
}
# See how we were called.
case "$1" in
start)
rh_status_q && exit 0
$1
;;
stop)
rh_status_q || exit 0
$1
;;
restart)
$1
;;
reload)
rh_status_q || exit 7
$1
;;
force-reload)
force_reload
;;
status)
rh_status
;;
condrestart|try-restart)
rh_status_q || exit 0
restart
;;
*)
echo "Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
exit 2
esac
exit $?
(5)varnish 启动时的参数脚本
vi
/etc/sysconfig/varnish
# Configuration file for varnish
# /etc/init.d/varnish expects the variable $DAEMON_OPTS to be set from this
# shell script fragment.
# Maximum number of open files (for ulimit -n)
NFILES=131072
# Locked shared memory (for ulimit -l)
# Default log size is 82MB + header
MEMLOCK=82000
# Maximum size of corefile (for ulimit -c). Default in Fedora is 0
# DAEMON_COREFILE_LIMIT="unlimited"
# Set this to 1 to make init script reload try to switch vcl without restart.
# To make this work, you need to set the following variables
# explicit: VARNISH_VCL_CONF, VARNISH_ADMIN_LISTEN_ADDRESS,
# VARNISH_ADMIN_LISTEN_PORT, VARNISH_SECRET_FILE, or in short,
# use Alternative 3, Advanced configuration, below
RELOAD_VCL=1
# This file contains 4 alternatives, please use only one.
## Alternative 1, Minimal configuration, no VCL
#
# Listen on port 6081, administration on localhost:6082, and forward to
# content server on localhost:8080.
Use a fixed-size cache file.
#
#DAEMON_OPTS="-a :6081 \
#
-T localhost:6082 \
#
-b localhost:8080 \
#
-u varnish -g varnish \
#
-s file,/var/lib/varnish/varnish_storage.bin,1G"
## Alternative 2, Configuration with VCL
#
# Listen on port 6081, administration on localhost:6082, and forward to
# one content server selected by the vcl file, based on the request.
Use a
# fixed-size cache file.
#
#DAEMON_OPTS="-a :6081 \
#
-T localhost:6082 \
#
-f /etc/varnish/default.vcl \
#
-u varnish -g varnish \
#
-S /etc/varnish/secret \
#
-s file,/var/lib/varnish/varnish_storage.bin,1G"
## Alternative 3, Advanced configuration
# See varnishd(1) for more information.
# # Main configuration file.
VARNISH_VCL_CONF=/usr/local/varnish/etc/varnish/default.vcl
# # Default address and port to bind to
Blank address means all IPv4 and IPv6 interfaces, otherwise specify
# # a host name, an IPv4 dotted quad, or an IPv6 address in brackets.
VARNISH_LISTEN_ADDRESS=0.0.0.0
VARNISH_LISTEN_PORT=80
# # Telnet admin interface listen address and port
VARNISH_ADMIN_LISTEN_ADDRESS=127.0.0.1
VARNISH_ADMIN_LISTEN_PORT=6082
#
Shared secret file for admin interface, be sure the file is not null ,Otherwise varnish service can not work.
VARNISH_SECRET_FILE=/etc/varnish/secret
# # The minimum number of worker threads to start
VARNISH_MIN_THREADS=4
# # The Maximum number of worker threads to start
VARNISH_MAX_THREADS=512
# # Idle timeout for worker threads
VARNISH_THREAD_TIMEOUT=120
# # Cache file location
VARNISH_STORAGE_FILE=/usr/local/varnish/var/varnish/varnish_storage.bin
#
# # Cache file size: in bytes, optionally using k / M / G / T suffix,
# # or in percentage of available disk space using the % suffix.
VARNISH_STORAGE_SIZE=1G
# # Backend storage specification
VARNISH_STORAGE="file,${VARNISH_STORAGE_FILE},${VARNISH_STORAGE_SIZE}"
# # Default TTL used when the backend does not specify one
VARNISH_TTL=120
# # DAEMON_OPTS is used by the init script.
If you add or remove options, make
# # sure you update this section, too.
DAEMON_OPTS="-a ${VARNISH_LISTEN_ADDRESS}:${VARNISH_LISTEN_PORT} \
-f ${VARNISH_VCL_CONF} \
-T ${VARNISH_ADMIN_LISTEN_ADDRESS}:${VARNISH_ADMIN_LISTEN_PORT} \
-t ${VARNISH_TTL} \
-w ${VARNISH_MIN_THREADS},${VARNISH_MAX_THREADS},${VARNISH_THREAD_TIMEOUT} \
-u varnish -g varnish \
-S ${VARNISH_SECRET_FILE} \
-s ${VARNISH_STORAGE} \
-p cli_timeout=15 -p session_linger=20"
## Alternative 4, Do It Yourself. See varnishd(1) for more information.
#
# DAEMON_OPTS=""
(6) varnish reload即:重新编译varnish vcl文件并将其加载
vi /usr/local/varnish/sbin/varnish_reload_vcl
#!/bin/bash
#
# reload vcl revisited
# A script that loads new vcl based on data from /etc/sysconfig/varnish
# chmod 755 /usr/local/varnish/sbin/varnish_reload_vcl
#
# The following environment variables have to be set:
# RELOAD_VCL, VARNISH_VCL_CONF, VARNISH_ADMIN_LISTEN_PORT
# The following are optional:
# VARNISH_SECRET_FILE, VARNISH_ADMIN_LISTEN_ADDRESS
#
# Requires GNU bash and GNU date
#
debug=false
missing() {
echo "Missing configuration variable: $1"
exit 2
}
print_debug() {
echo "
Parsed configuration:
RELOAD_VCL=\"$RELOAD_VCL\"
VARNISH_VCL_CONF=\"$VARNISH_VCL_CONF\"
VARNISH_ADMIN_LISTEN_ADDRESS=\"$VARNISH_ADMIN_LISTEN_ADDRESS\"
VARNISH_ADMIN_LISTEN_PORT=\"$VARNISH_ADMIN_LISTEN_PORT\"
VARNISH_SECRET_FILE=\"$VARNISH_SECRET_FILE\"
"
}
# Read configuration
exec="/usr/local/varnish/sbin/varnishd"
. /etc/sysconfig/varnish
$debug && print_debug
# Check configuration
if [ ! "$RELOAD_VCL" = "1" ]; then
echo "Error: RELOAD_VCL is not set to 1"
exit 2
elif [ -z "$VARNISH_VCL_CONF" ]; then
echo "Error: VARNISH_VCL_CONF is not set"
exit 2
elif [ ! -s "$VARNISH_VCL_CONF" ]; then
echo "Eror: VCL config $VARNISH_VCL_CONF is unreadable or empty"
exit 2
elif [ -z "$VARNISH_ADMIN_LISTEN_ADDRESS" ]; then
echo "Warning: VARNISH_ADMIN_LISTEN_ADDRESS is not set, using 127.0.0.1"
VARNISH_ADMIN_LISTEN_ADDRESS="127.0.0.1"
elif [ -z "$VARNISH_ADMIN_LISTEN_PORT" ]; then
echo "Error: VARNISH_ADMIN_LISTEN_PORT is not set"
exit 2
elif [ -z "$VARNISH_SECRET_FILE" ]; then
echo "Warning: VARNISH_SECRET_FILE is not set"
secret=""
elif [ ! -s "$VARNISH_SECRET_FILE" ]; then
echo "Error: varnish secret file $VARNISH_SECRET_FILE is unreadable or empty"
exit 2
else
secret="-S $VARNISH_SECRET_FILE"
fi
# Done parsing, set up command
VARNISHADM="/usr/local/varnish/bin/varnishadm $secret -T $VARNISH_ADMIN_LISTEN_ADDRESS:$VARNISH_ADMIN_LISTEN_PORT"
# Now do the real work
new_config="reload_$(date +%FT%H:%M:%S)"
# Check if we are able to connect at all
if $VARNISHADM vcl.list > /dev/null; then
$debug && echo vcl.list succeeded
else
echo "Unable to run $VARNISHADM vcl.list"
exit 1
fi
if $VARNISHADM vcl.list | awk ' { print $3 } ' | grep -q $new_config; then
echo Trying to use new config $new_config, but that is already in use
exit 2
fi
current_config=$( $VARNISHADM vcl.list | awk ' /^active/ { print $3 } ' )
echo "Loading vcl from $VARNISH_VCL_CONF"
echo "Current running config name is $current_config"
echo "Using new config name $new_config"
if $VARNISHADM vcl.load $new_config $VARNISH_VCL_CONF; then
$debug && echo "$VARNISHADM vcl.load succeded"
else
echo "$VARNISHADM vcl.load failed"
exit 1
fi
if $VARNISHADM vcl.use $new_config; then
$debug && echo "$VARNISHADM vcl.use succeded"
else
echo "$VARNISHADM vcl.use failed"
exit 1
fi
$VARNISHADM vcl.list
echo Done
exit 0
+++++++++++++++++
第二部分 monit的编译与安装
官方文档
http://mmonit.com/monit/documentation/monit.html#init_support
(1)开始编译monit
flex-2.5.4a-41.fc6
bison-2.3-2.1
byacc-1.9-29.2.2
wget http://mmonit.com/monit/dist/monit-5.3.2.tar.gz
tar zxvf monit-5.3.2.tar.gz
cd monit-5.3.2
./configure --enable-optimized(use ./configure –-help to view available options)
+------------------------------------------------------------+
| License:
|
| This is Open Source Software and use is subject to the GNU |
| AFFERO GENERAL PUBLIC LICENSE version 3, available in this |
| distribution in the file COPYING.
|
|
|
| By continuing this installation process, you are bound by
|
| the terms of this license agreement. If you do not agree
|
| with the terms of this license, you must abort the
|
| installation process at this point.
|
+------------------------------------------------------------+
| Monit has been configured with the following options:
|
|
|
|
PAM support:
ENABLED
|
|
SSL support:
ENABLED
|
|
Large files support:
ENABLED
|
|
Optimized:
ENABLED
|
+------------------------------------------------------------+
make && make install
(2)monit全局文件配置 /usr/local/etc/monitrc 并将权限设置为 chmod 0700 /usr/local/etc/monitrc
vi /usr/local/etc/monitrc
# directory /usr/local/etc/monit.d
and file
/usr/local/etc/monitrc must existed firstly
set daemon 30
with start delay 10
set httpd port 3500 and
use address localhost
allow localhost
allow monit:userpassord
#allow @monit
#allow @users readonly
include /usr/local/etc/monit.d/*
我们将需要监控的服务放在单独的文件里好管理 vi /usr/local/etc/monit.d/varnish
# Check varnish on port 80 and request url
check process varnish with pidfile "/var/run/varnish.pid"
start program = "/etc/init.d/varnish start"
stop program = "/etc/init.d/varnish stop"
if failed host localhost port 80 protocol http
and request "/elbstatus.html"
then restart
group cacheserver
if 5 restarts within 6 cycles then timeout
#check process apache with pidfile "/var/run/httpd.pid"
#start program = "/etc/init.d/httpd start"
#stop program = "/etc/init.d/httpd stop"
#if failed host localhost port 8080 protocol http
#
and request "/elbstatus.html"
#
then restart
#group webserver
#if 5 restarts within 6 cycles then timeout
[like@ec2 ~]# vi /usr/local/etc/monit.d/logging
# log to monit.log
set logfile /var/log/monit
(3)检查monit语法 /usr/local/bin/monit -t
Control file syntax OK
(4)启动monit 服务
4.1 直接用户命令启动 /usr/local/bin/monit -c /usr/local/etc/monitrc
4.2 (推荐这种做法,在Aws EC2上也是使用这种方法)也可以设置monit随系统启动,在/etc/inittab文件的最后加入,monit init support可查看官方http://mmonit.com/monit/documentation/monit.html#pid_testing
# Run monit in standard run-levels
mo:2345:respawn:/usr/local/bin/monit -Ic /usr/local/etc/monitrc
更新init
After you have modified init's configuration file, you can run the following command to re-examine /etc/inittab and start Monit:
telinit q
For systems without telinit:
kill -1 1
注意:
由于将monit设置成为了守护进程,并且在inittab中加入了随系统启动的设置,则monit进程如果停止,init进程会将其重启,而monit又监视着其它的服务,这意味着monit所监视的服务不能使用一般的方法来停止,因为一停止,monit又会将其启动.要停止monit所监视的服务,应该使用monit stop name这样的命令,例如要停止tomcat: monit stop tomcat
要停止全部monit所监视的服务可以使用monit stop all.
要启动某个服务可以用monit stop name这样的命令,启动全部则是monit start all.
对于monit配置进行更新,需要使用monit quit进行重新加载
4.3 使用脚本来管理monit服务
[like@ec2 ~]# cat /etc/init.d/monit
#!/bin/bash
#
# Init file for Monit system monitor
# Written by XXXX
# 2012/2/10
# chkconfig: - 98 02
# description: Utility for monitoring services on a Unix system
#
# processname: monit
# config: /usr/local/etc/monitrc
# pidfile: /var/run/monit
# Short-Description: Monit is a system monitor
# Source function library.
. /etc/init.d/functions
PATH="$PATH:/usr/local/bin"
export PATH
### Default variables
CONFIG="/usr/local/etc/monitrc"
prog="monit"
# Check if requirements are met
[ -x /usr/local/bin/monit ] || exit 1
[ -r "$CONFIG" ] || exit 1
RETVAL=0
start() {
echo -n $"Starting $prog: "
daemon $prog
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && touch /var/lock/subsys/$prog
return $RETVAL
}
stop() {
echo -n $"Shutting down $prog: "
killproc $prog
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/$prog
return $RETVAL
}
restart() {
stop
start
}
reload() {
echo -n $"Reloading $prog: "
monit -c "$CONFIG" reload
RETVAL=$?
echo
return $RETVAL
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
reload)
reload
;;
condrestart)
[ -e /var/lock/subsys/$prog ] && restart
RETVAL=$?
;;
status)
status $prog
RETVAL=$?
;;
*)
echo $"Usage: $0 {start|stop|restart|reload|condrestart|status}"
RETVAL=1
esac
注:
1.monit的主要control file 可是以在这些位置: ~/.monitrc, /etc/monitrc, /usr/local/etc/monitrc, /usr/local/etc/monitrc or at ./monitrc
2.在aws ec2 centos5.7系统中启动monit服务时提示:
Starting monit: /usr/local/etc/monitrc:11: Error: PAM is not supported 'allow'
/usr/local/etc/monitrc:11: Error: PAM is not supported 'readonly'
将如下项
# directory /usr/local/etc/monit.d
and file
/usr/local/etc/monitrc must existed firstly
set daemon 30
with start delay 10
set httpd port 3500 and
use address localhost
allow localhost
allow monit:userpassord
allow @monit
allow @users readonly
include /usr/local/etc/monit.d/*
修改成如下就能起启了,看似allow @组不支持,目前还在想办法解决
# directory /usr/local/etc/monit.d
and file
/usr/local/etc/monitrc must existed firstly
set daemon 30
with start delay 10
set httpd port 3500 and
use address localhost
allow localhost
allow monit:userpassord
#allow @monit
#allow @users readonly
include /usr/local/etc/monit.d/*
(3)monit中 check process +service名称来监控某个服务时,其中的service名称可随意写,只要它与其它已定义要监控的service名称不相同就可以,例如:
check process varnish或
check process cacheserver .其它要check的服务类同。
(4)查看命令帮助
/usr/local/bin/monit -h
Usage: monit [options] {arguments}
Options are as follows:
-c file
Use this control file
-d n
Run as a daemon once per n seconds
-g name
Set group name for start, stop, restart, monitor and unmonitor
-l logfile
Print log information to this file
-p pidfile
Use this lock file in daemon mode
-s statefile
Set the file monit should write state information to
-I
Do not run in background (needed for run from init)
-t
Run syntax check for the control file
-v
Verbose mode, work noisy (diagnostic output)
-vv
Very verbose mode, same as -v plus log stacktrace on error
-H [filename] Print SHA1 and MD5 hashes of the file or of stdin if the
filename is omited; monit will exit afterwards
-V
Print version number and patchlevel
-h
Print this text
Optional action arguments for non-daemon mode are as follows:
start all
- Start all services
start name
- Only start the named service
stop all
- Stop all services
stop name
- Only stop the named service
restart all
- Stop and start all services
restart name
- Only restart the named service
monitor all
- Enable monitoring of all services
monitor name
- Only enable monitoring of the named service
unmonitor all
- Disable monitoring of all services
unmonitor name
- Only disable monitoring of the named service
reload
- Reinitialize monit
status
- Print full status information for each service
summary
- Print short status information for each service
quit
- Kill monit daemon process
validate
- Check all services and start if not running
procmatch <pattern> - Test process matching pattern
假设我们配置了varnish 和 apache的监控,能过monit status命令查看监控状态
[like@ec2 ~]# monit status
The Monit daemon 5.3.2 uptime: 2m
Process 'varnish'
status
Running
monitoring status
Monitored
pid
1640
parent pid
1
uptime
4m
children
1
memory kilobytes
1136
memory kilobytes total
3124
memory percent
0.0%
memory percent total
0.1%
cpu percent
0.0%
cpu percent total
0.0%
port response time
0.000s to localhost:80/elbstatus.html [HTTP via TCP]
data collected
Thu, 09 Feb 2012 19:29:33
Process 'apache'
status
Running
monitoring status
Monitored
pid
1866
parent pid
1
uptime
1m
children
17
memory kilobytes
9344
memory kilobytes total
83144
memory percent
0.5%
memory percent total
4.7%
cpu percent
0.0%
cpu percent total
0.0%
data collected
Thu, 09 Feb 2012 19:29:33
System 'system_localhost'
status
Running
monitoring status
Monitored
load average
[0.29] [0.28] [0.13]
cpu
1.3%us 1.2%sy 0.0%wa
memory usage
132356 kB [7.5%]
swap usage
0 kB [0.0%]
data collected
Thu, 09 Feb 2012 19:29:33
第三部分 nagios监控 monit实例
http://mmonit.com/wiki/Monit/EnableSSLInMonit
http://code.google.com/p/nagios-monit-plugin/
(1)check_monit.py用法
This Nagios plugin checks status of Monit server using its XML status.
Unmonitored status causes plugin to return WARNING state, all other failures return CRITICAL state.
Usage: check_monit.py [options]
Options:
-h, --help
show this help message and exit
-H HOST, --host=HOST
Hostname or IP address
-p PORT, --port=PORT
Port (Default: 3500)
-s, --ssl
Use SSL
-u USERNAME, --username=USERNAME
Username
-P PASSWORD, --password=PASSWORD
Password
Nagios command definition looks like this:
define command{
command_name
check_monit
command_line
$USER1$/check_monit.py -H $HOSTADDRESS$ -p 1234 -s -u $USER3$ -P $USER4$
}
(2)插件脚本check_monit.py
#!/usr/bin/env python
import httplib
from optparse import OptionParser
import sys
import xml.etree.ElementTree
import re
svc_types = {
'FILESYSTEM': '0',
'DIRECTORY': '1',
'FILE': '2',
'PROCESS': '3',
'HOST': '4',
'SYSTEM': '5',
'FIFO': '6',
'STATUS': '7',
}
for (k, v) in svc_types.items(): svc_types[v] = k
xml_hacks = (
(re.compile(r"<request>(.*?)</request>",flags=re.MULTILINE), (r"<request><![CDATA[\1]]></request>")),
)
warnings = []
errors = []
totsvcs = 0
svc_includere = None
svc_excludere = None
opts = None
def ok(message):
print "OK: %s"%message
sys.exit(0)
def warning(message):
print "WARNING: %s"%message
sys.exit(1)
def critical(message):
print "CRITICAL: %s"%message
sys.exit(2)
def unknown(message):
print "UNKNOWN: %s"%message
sys.exit(3)
def get_status():
if opts.ssl is True:
HTTPClass = httplib.HTTPSConnection
else:
HTTPClass = httplib.HTTPConnection
connection = HTTPClass(opts.host,opts.port)
headers = {}
if opts.username and opts.password:
import base64
headers['Authorization'] = 'Basic ' + (base64.encodestring(opts.username + ':' + opts.password)).strip()
try:
connection.request('GET','/_status?format=xml',headers=headers)
response = connection.getresponse()
if not response.status == 200:
critical('Monit HTTP response: %i:%s'%(response.status, response.reason))
return response.read()
except Exception, e:
critical('Exception: %s'%str(e))
def process_ystem(service):
system = service.find('system')
def process_service(service):
global totsvcs
svctype_num = service.get('type')
#if svctype_num == "5": process_system(service)
svctype = svc_types.get(svctype_num,svctype_num)
svcname = service.find('name').text
if svc_excludere and re.match(svc_excludere,svcname): return
if svc_includere and not re.match(svc_includere,svcname): return
monitor = service.find('monitor').text
status_num = service.find('status').text
totsvcs += 1
if not monitor == "1":
warnings.append('%s %s is unmonitored'%(svctype, svcname))
if not status_num == "0":
status_message = service.find('status_message').text
errors.append('%s %s: %s'%(svctype,svcname,status_message))
def process_status(status):
for regex, replacement in xml_hacks:
status = re.sub(regex, replacement,status)
#from xml.dom import minidom
#print xml.dom.minidom.parseString(status).toprettyxml()
#print status
tree = xml.etree.ElementTree.fromstring(status)
for service in
tree.findall('service'):
process_service(service)
def main():
global opts, svc_includere, svc_excludere
p = OptionParser()
p.add_option("-H","--host", dest="host", help="Hostname or IP address")
p.add_option("-p","--port", dest="port", type="int", default=3500, help="Port (Default: ?fault)")
p.add_option("-s","--ssl", dest="ssl", action="store_true", default=False, help="Use SSL")
p.add_option("-u","--username", dest="username", help="Username")
p.add_option("-P","--password", dest="password", help="Password")
p.add_option("-i","--include", dest="svc_include", help="Regular expression for service(s) to include into monitoring")
p.add_option("-e","--exclude", dest="svc_exclude", help="Regular expression for service(s) to exclude from monitoring")
(opts, args) = p.parse_args()
if not opts.host:
print "\nUsage: %s -H <host> [<options>]\n"%sys.argv[0]
print "For full usage instructions please invoke with -h option\n"
sys.exit(1)
if opts.svc_include: svc_includere = re.compile(opts.svc_include)
if opts.svc_exclude: svc_excludere = re.compile(opts.svc_exclude)
process_status(get_status())
if errors:
critical('%s'%'; '.join(errors))
if warnings:
warning('%s'%'; '.join(warnings))
ok('Total %i services are monitored'%totsvcs)
if __name__ == '__main__':
编写管理脚本前的说明
++++++++++++++++
1. 修改varnish rpm 安装方式时的service管理脚本用于 varnish源码编译后的service管理。
2.文件/etc/init.d/varnish 主要修改的地方如下
VARNISH_VCL_CONF=/usr/local/varnish/etc/varnish/default.vcl
pidfile=/var/run/varnish.pid
exec="/usr/local/varnish/sbin/varnishd"
reload_exec="/usr/local/varnish/sbin/varnish_reload_vcl"
prog="varnishd"
config="/etc/sysconfig/varnish"
lockfile="/var/lock/subsys/varnish"
VARNISH_SECRET_FILE=/etc/varnish/secret
exec="/usr/local/varnish/sbin/varnishd"
VARNISHADM="/usr/local/varnish/bin/varnishadm $secret -T $VARNISH_ADMIN_LISTEN_ADDRESS:$VARNISH_ADMIN_LISTEN_PORT"
3.如果启用了密码文件,要保证它不不为空: 如 /etc/varnish/secret 否则varnish服务是起不来的
4.varnish的编译后安装目录为/usr/local/varnish以下几个目录和文件要存在并做设置执行权限
echo "oursect">/etc/varnish/secret
chmod 755 /etc/init.d/varnish
chmod 755 /usr/local/varnish/sbin/varnish_reload_vcl
5. varnish用户要存在
6.分配给varnish内存和打开文件数( ulimit -l, ulimit -n)通过命令先设置好:ulimit -SH -n 131072
7.monit内置一个管理服务通过3500的默认端口,这里只允许本地查看监控状态,如果要通过远程http查看其状态,则要修改两个use address 0.0.0.0和allow ip
set httpd port 3500 and
++++++++++++++++
第一部分varnish的安装与管理脚本
(1)安装 varnish-cache-3.0.2
Build dependencies on Debian / Ubuntu
In order to build Varnish from source you need a number of packages installed. On a Debian or Ubuntu system these are:
Build dependencies on Red Hat / CentOS
To build Varnish on a Red Hat or CentOS system you need the following packages installed:
wget -c
tar -zxvf varnish-3.0.2.tar.gz
chown root.root -R varnish-3.0.2
cd varnish-3.0.2
./configure
make
make check
make install
ldconfig
(2)将如下两行放在 /etc/profile文件中来设置系统变量。
export VARNISH_HOME=/usr/local/varnish
export PATH=$PATH:$VARNISH_HOME:$VARNISH_HOME/sbin:$VARNISH_HOME/bin
(3)varnish VCL文件配置
vi /usr/local/varnish/etc/varnish/default.vcl
# Default backend definition. The Seting is just for varnish3.0.X
backend default {
.host = "127.0.0.1";
.port = "8080";
.connect_timeout = 600s;
.first_byte_timeout = 600s;
.between_bytes_timeout = 600s;
.max_connections = 800;
}
sub vcl_recv {
set req.backend = default;
set req.grace = 5m;
#
#
## This would make varnish skip caching for this particular site
# if (req.http.host ~ "internet-safety.yoursphere.com$") {
#
# }
# This makes varnish skip caching for every site except this one
# Commented out here, but shown for sake of some use cases
# if (req.http.host != "sitea.com") {
#
#}
## Remove has_js and Google Analytics cookies.
set req.http.Cookie = regsuball(req.http.Cookie, "(^|;\s*)(__[a-z]+|has_js)=[^;]*", "");
## Remove a ";" prefix, if present.
set req.http.Cookie = regsub(req.http.Cookie, "^;\s*", "");
## Remove empty cookies.
if (req.http.Cookie ~ "^\s*$") {
}
# Pass server-status
if (req.url ~ ".*/server-status$") {
return (pass);
}
# Don't cache install.php update.php cron.php
if (req.url ~ "install.php|update.php|cron.php") {
}
# Cache these extension file ,but No point to cache their cookie
if (req.url ~ "\.(js|css|jpg|jpeg|png|gif|gz|tgz|bz2|tbz|mp3|ogg|swf)$") {
}
# Don't cache Drupal logged-in user sessions
# LOGGED_IN is the cookie that earlier version of Pressflow sets
# VARNISH is the cookie which the varnish.module sets
if (req.http.Cookie ~ "(VARNISH|DRUPAL_UID|LOGGED_IN)") {
}
}
sub vcl_fetch {
# Grace to allow varnish to serve content if backend is lagged
set beresp.grace = 5m;
# These status codes should always pass through and never cache.
if (beresp.status == 404 || beresp.status == 503 || beresp.status == 500) {
}
if (req.url ~ "\.(js|css|jpg|jpeg|png|gif|gz|tgz|bz2|tbz|mp3|ogg|swf)$") {
}
if (req.url ~ "(^/files/)|(^/sites/)") {
#if (beresp.ttl <= 0s) {
#
#
#}
#else {
if (req.url ~ "(.js|.css)$") {
else{
#}
return (deliver);
}
sub vcl_deliver {
if (resp.http.magicmarker) {
# add cache hit data
if (obj.hits > 0) {
}
else {
}
# hidden some sensitive http header returning to client, when the cache server received from backend server response
#remove resp.http.X-Varnish;
#remove resp.http.Via;
##remove resp.http.Age;
#remove resp.http.X-Powered-By;
#remove resp.http.X-Drupal-Cache;
return (deliver);
}
sub vcl_error {
}
sub vcl_hit {
if (req.http.Cache-Control ~ "no-cache") {
}
}
}
以上几步就完成了varnis的安装和配置了,接下来就是写脚本来管理 varnish了。
(4) varnish 启动服务管理脚本:
vi /etc/init.d/varnish
#!/bin/sh
#
# varnish Control the varnish HTTP accelerator
# chmod 755
# chkconfig: - 90 10
# description: Varnish is a high-perfomance HTTP accelerator
# processname: varnishd
# config: /etc/sysconfig/varnish
# pidfile: /var/run/varnish/varnishd.pid
### BEGIN INIT INFO
# Provides: varnish
# Required-Start: $network $local_fs $remote_fs
# Required-Stop: $network $local_fs $remote_fs
# Default-Start:
# Default-Stop:
# Should-Start: $syslog
# Short-Description: start and stop varnishd
# Description: Varnish is a high-perfomance HTTP accelerator
### END INIT INFO
# Source function library.
. /etc/init.d/functions
retval=0
pidfile=/var/run/varnish.pid
exec="/usr/local/varnish/sbin/varnishd"
reload_exec="/usr/local/varnish/sbin/varnish_reload_vcl"
prog="varnishd"
config="/etc/sysconfig/varnish"
lockfile="/var/lock/subsys/varnish"
# Include varnish defaults
[ -e /etc/sysconfig/varnish ] && . /etc/sysconfig/varnish
start() {
}
stop() {
}
restart() {
}
reload() {
}
force_reload() {
}
rh_status() {
}
rh_status_q() {
}
# See how we were called.
case "$1" in
esac
exit $?
(5)varnish 启动时的参数脚本
vi
# Configuration file for varnish
# /etc/init.d/varnish expects the variable $DAEMON_OPTS to be set from this
# shell script fragment.
# Maximum number of open files (for ulimit -n)
NFILES=131072
# Locked shared memory (for ulimit -l)
# Default log size is 82MB + header
MEMLOCK=82000
# Maximum size of corefile (for ulimit -c). Default in Fedora is 0
# DAEMON_COREFILE_LIMIT="unlimited"
# Set this to 1 to make init script reload try to switch vcl without restart.
# To make this work, you need to set the following variables
# explicit: VARNISH_VCL_CONF, VARNISH_ADMIN_LISTEN_ADDRESS,
# VARNISH_ADMIN_LISTEN_PORT, VARNISH_SECRET_FILE, or in short,
# use Alternative 3, Advanced configuration, below
RELOAD_VCL=1
# This file contains 4 alternatives, please use only one.
## Alternative 1, Minimal configuration, no VCL
#
# Listen on port 6081, administration on localhost:6082, and forward to
# content server on localhost:8080.
#
#DAEMON_OPTS="-a :6081 \
#
#
#
#
## Alternative 2, Configuration with VCL
#
# Listen on port 6081, administration on localhost:6082, and forward to
# one content server selected by the vcl file, based on the request.
# fixed-size cache file.
#
#DAEMON_OPTS="-a :6081 \
#
#
#
#
#
## Alternative 3, Advanced configuration
# See varnishd(1) for more information.
# # Main configuration file.
VARNISH_VCL_CONF=/usr/local/varnish/etc/varnish/default.vcl
# # Default address and port to bind to
# # a host name, an IPv4 dotted quad, or an IPv6 address in brackets.
VARNISH_LISTEN_ADDRESS=0.0.0.0
VARNISH_LISTEN_PORT=80
# # Telnet admin interface listen address and port
VARNISH_ADMIN_LISTEN_ADDRESS=127.0.0.1
VARNISH_ADMIN_LISTEN_PORT=6082
#
VARNISH_SECRET_FILE=/etc/varnish/secret
# # The minimum number of worker threads to start
VARNISH_MIN_THREADS=4
# # The Maximum number of worker threads to start
VARNISH_MAX_THREADS=512
# # Idle timeout for worker threads
VARNISH_THREAD_TIMEOUT=120
# # Cache file location
VARNISH_STORAGE_FILE=/usr/local/varnish/var/varnish/varnish_storage.bin
#
# # Cache file size: in bytes, optionally using k / M / G / T suffix,
# # or in percentage of available disk space using the % suffix.
VARNISH_STORAGE_SIZE=1G
# # Backend storage specification
VARNISH_STORAGE="file,${VARNISH_STORAGE_FILE},${VARNISH_STORAGE_SIZE}"
# # Default TTL used when the backend does not specify one
VARNISH_TTL=120
# # DAEMON_OPTS is used by the init script.
# # sure you update this section, too.
DAEMON_OPTS="-a ${VARNISH_LISTEN_ADDRESS}:${VARNISH_LISTEN_PORT} \
-f ${VARNISH_VCL_CONF} \
-T ${VARNISH_ADMIN_LISTEN_ADDRESS}:${VARNISH_ADMIN_LISTEN_PORT} \
-t ${VARNISH_TTL} \
-w ${VARNISH_MIN_THREADS},${VARNISH_MAX_THREADS},${VARNISH_THREAD_TIMEOUT} \
-u varnish -g varnish \
-S ${VARNISH_SECRET_FILE} \
-s ${VARNISH_STORAGE} \
-p cli_timeout=15 -p session_linger=20"
## Alternative 4, Do It Yourself. See varnishd(1) for more information.
#
# DAEMON_OPTS=""
(6) varnish reload即:重新编译varnish vcl文件并将其加载
vi /usr/local/varnish/sbin/varnish_reload_vcl
#!/bin/bash
#
# reload vcl revisited
# A script that loads new vcl based on data from /etc/sysconfig/varnish
# chmod 755 /usr/local/varnish/sbin/varnish_reload_vcl
#
# The following environment variables have to be set:
# RELOAD_VCL, VARNISH_VCL_CONF, VARNISH_ADMIN_LISTEN_PORT
# The following are optional:
# VARNISH_SECRET_FILE, VARNISH_ADMIN_LISTEN_ADDRESS
#
# Requires GNU bash and GNU date
#
debug=false
missing() {
}
print_debug() {
Parsed configuration:
RELOAD_VCL=\"$RELOAD_VCL\"
VARNISH_VCL_CONF=\"$VARNISH_VCL_CONF\"
VARNISH_ADMIN_LISTEN_ADDRESS=\"$VARNISH_ADMIN_LISTEN_ADDRESS\"
VARNISH_ADMIN_LISTEN_PORT=\"$VARNISH_ADMIN_LISTEN_PORT\"
VARNISH_SECRET_FILE=\"$VARNISH_SECRET_FILE\"
"
}
# Read configuration
exec="/usr/local/varnish/sbin/varnishd"
. /etc/sysconfig/varnish
$debug && print_debug
# Check configuration
if [ ! "$RELOAD_VCL" = "1" ]; then
elif [ -z "$VARNISH_VCL_CONF" ]; then
elif [ ! -s "$VARNISH_VCL_CONF" ]; then
elif [ -z "$VARNISH_ADMIN_LISTEN_ADDRESS" ]; then
elif [ -z "$VARNISH_ADMIN_LISTEN_PORT" ]; then
elif [ -z "$VARNISH_SECRET_FILE" ]; then
elif [ ! -s "$VARNISH_SECRET_FILE" ]; then
else
fi
# Done parsing, set up command
VARNISHADM="/usr/local/varnish/bin/varnishadm $secret -T $VARNISH_ADMIN_LISTEN_ADDRESS:$VARNISH_ADMIN_LISTEN_PORT"
# Now do the real work
new_config="reload_$(date +%FT%H:%M:%S)"
# Check if we are able to connect at all
if $VARNISHADM vcl.list > /dev/null; then
else
fi
if $VARNISHADM vcl.list | awk ' { print $3 } ' | grep -q $new_config; then
fi
current_config=$( $VARNISHADM vcl.list | awk ' /^active/ { print $3 } ' )
echo "Loading vcl from $VARNISH_VCL_CONF"
echo "Current running config name is $current_config"
echo "Using new config name $new_config"
if $VARNISHADM vcl.load $new_config $VARNISH_VCL_CONF; then
else
fi
if $VARNISHADM vcl.use $new_config; then
else
fi
$VARNISHADM vcl.list
echo Done
exit 0
+++++++++++++++++
第二部分 monit的编译与安装
官方文档
http://mmonit.com/monit/documentation/monit.html#init_support
(1)开始编译monit
flex-2.5.4a-41.fc6
bison-2.3-2.1
byacc-1.9-29.2.2
wget http://mmonit.com/monit/dist/monit-5.3.2.tar.gz
tar zxvf monit-5.3.2.tar.gz
cd monit-5.3.2
./configure --enable-optimized(use ./configure –-help to view available options)
+------------------------------------------------------------+
| License:
| This is Open Source Software and use is subject to the GNU |
| AFFERO GENERAL PUBLIC LICENSE version 3, available in this |
| distribution in the file COPYING.
|
| By continuing this installation process, you are bound by
| the terms of this license agreement. If you do not agree
| with the terms of this license, you must abort the
| installation process at this point.
+------------------------------------------------------------+
| Monit has been configured with the following options:
|
|
|
|
|
+------------------------------------------------------------+
make && make install
(2)monit全局文件配置 /usr/local/etc/monitrc 并将权限设置为 chmod 0700 /usr/local/etc/monitrc
# directory /usr/local/etc/monit.d
set daemon 30
with start delay 10
set httpd port 3500 and
include /usr/local/etc/monit.d/*
我们将需要监控的服务放在单独的文件里好管理 vi /usr/local/etc/monit.d/varnish
# Check varnish on port 80 and request url
check process varnish with pidfile "/var/run/varnish.pid"
start program = "/etc/init.d/varnish start"
stop program = "/etc/init.d/varnish stop"
if failed host localhost port 80 protocol http
group cacheserver
if 5 restarts within 6 cycles then timeout
#check process apache with pidfile "/var/run/httpd.pid"
#start program = "/etc/init.d/httpd start"
#stop program = "/etc/init.d/httpd stop"
#if failed host localhost port 8080 protocol http
#
#
#group webserver
#if 5 restarts within 6 cycles then timeout
[like@ec2 ~]# vi /usr/local/etc/monit.d/logging
# log to monit.log
set logfile /var/log/monit
(3)检查monit语法 /usr/local/bin/monit -t
(4)启动monit 服务
4.2 (推荐这种做法,在Aws EC2上也是使用这种方法)也可以设置monit随系统启动,在/etc/inittab文件的最后加入,monit init support可查看官方http://mmonit.com/monit/documentation/monit.html#pid_testing
# Run monit in standard run-levels
mo:2345:respawn:/usr/local/bin/monit -Ic /usr/local/etc/monitrc
更新init
After you have modified init's configuration file, you can run the following command to re-examine /etc/inittab and start Monit:
For systems without telinit:
注意:
对于monit配置进行更新,需要使用monit quit进行重新加载
#!/bin/bash
#
# Init file for Monit system monitor
# Written by XXXX
# 2012/2/10
# chkconfig: - 98 02
# description: Utility for monitoring services on a Unix system
#
# processname: monit
# config: /usr/local/etc/monitrc
# pidfile: /var/run/monit
# Short-Description: Monit is a system monitor
# Source function library.
. /etc/init.d/functions
PATH="$PATH:/usr/local/bin"
export PATH
### Default variables
CONFIG="/usr/local/etc/monitrc"
prog="monit"
# Check if requirements are met
[ -x /usr/local/bin/monit ] || exit 1
[ -r "$CONFIG" ] || exit 1
RETVAL=0
start() {
}
stop() {
}
restart() {
}
reload() {
}
case "$1" in
esac
注:
1.monit的主要control file 可是以在这些位置: ~/.monitrc, /etc/monitrc, /usr/local/etc/monitrc, /usr/local/etc/monitrc or at ./monitrc
2.在aws ec2 centos5.7系统中启动monit服务时提示:
Starting monit: /usr/local/etc/monitrc:11: Error: PAM is not supported 'allow'
/usr/local/etc/monitrc:11: Error: PAM is not supported 'readonly'
将如下项
# directory /usr/local/etc/monit.d
set daemon 30
with start delay 10
set httpd port 3500 and
include /usr/local/etc/monit.d/*
修改成如下就能起启了,看似allow @组不支持,目前还在想办法解决
# directory /usr/local/etc/monit.d
set daemon 30
with start delay 10
set httpd port 3500 and
include /usr/local/etc/monit.d/*
(3)monit中 check process +service名称来监控某个服务时,其中的service名称可随意写,只要它与其它已定义要监控的service名称不相同就可以,例如:
(4)查看命令帮助
/usr/local/bin/monit -h
Usage: monit [options] {arguments}
Options are as follows:
Optional action arguments for non-daemon mode are as follows:
假设我们配置了varnish 和 apache的监控,能过monit status命令查看监控状态
[like@ec2 ~]# monit status
The Monit daemon 5.3.2 uptime: 2m
Process 'varnish'
Process 'apache'
System 'system_localhost'
第三部分 nagios监控 monit实例
http://mmonit.com/wiki/Monit/EnableSSLInMonit
http://code.google.com/p/nagios-monit-plugin/
(1)check_monit.py用法
This Nagios plugin checks status of Monit server using its XML status.
Unmonitored status causes plugin to return WARNING state, all other failures return CRITICAL state.
Usage: check_monit.py [options]
Options:
Nagios command definition looks like this:
define command{
}
(2)插件脚本check_monit.py
#!/usr/bin/env python
import httplib
from optparse import OptionParser
import sys
import xml.etree.ElementTree
import re
svc_types = {
}
for (k, v) in svc_types.items(): svc_types[v] = k
xml_hacks = (
)
warnings = []
errors = []
totsvcs = 0
svc_includere = None
svc_excludere = None
opts = None
def ok(message):
def warning(message):
def critical(message):
def unknown(message):
def get_status():
def process_ystem(service):
def process_service(service):
def process_status(status):
def main():
if __name__ == '__main__':
原文:http://ggb98.blog.163.com/blog/static/92068522012396327821/