AWS Varnish Monit实战

源码编译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__':

    main()

原文:http://ggb98.blog.163.com/blog/static/92068522012396327821/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
东南亚位于我国倡导推进的“一带一路”海陆交汇地带,作为当今全球发展最为迅速的地区之一,近年来区域内生产总值实现了显著且稳定的增长。根据东盟主要经济体公布的最新数据,印度尼西亚2023年国内生产总值(GDP)增长5.05%;越南2023年经济增长5.05%;马来西亚2023年经济增速为3.7%;泰国2023年经济增长1.9%;新加坡2023年经济增长1.1%;柬埔寨2023年经济增速预计为5.6%。 东盟国家在“一带一路”沿线国家中的总体GDP经济规模、贸易总额与国外直接投资均为最大,因此有着举足轻重的地位和作用。当前,东盟与中国已互相成为双方最大的交易伙伴。中国-东盟贸易总额已从2013年的443亿元增长至 2023年合计超逾6.4万亿元,占中国外贸总值的15.4%。在过去20余年中,东盟国家不断在全球多变的格局里面临挑战并寻求机遇。2023东盟国家主要经济体受到国内消费、国外投资、货币政策、旅游业复苏、和大宗商品出口价企稳等方面的提振,经济显现出稳步增长态势和强韧性的潜能。 本调研报告旨在深度挖掘东南亚市场的增长潜力与发展机会,分析东南亚市场竞争态势、销售模式、客户偏好、整体市场营商环境,为国内企业出海开展业务提供客观参考意见。 本文核心内容: 市场空间:全球行业市场空间、东南亚市场发展空间。 竞争态势:全球份额,东南亚市场企业份额。 销售模式:东南亚市场销售模式、本地代理商 客户情况:东南亚本地客户及偏好分析 营商环境:东南亚营商环境分析 本文纳入的企业包括国外及印尼本土企业,以及相关上下游企业等,部分名单 QYResearch是全球知名的大型咨询公司,行业涵盖各高科技行业产业链细分市场,横跨如半导体产业链(半导体设备及零部件、半导体材料、集成电路、制造、封测、分立器件、传感器、光电器件)、光伏产业链(设备、硅料/硅片、电池片、组件、辅料支架、逆变器、电站终端)、新能源汽车产业链(动力电池及材料、电驱电控、汽车半导体/电子、整车、充电桩)、通信产业链(通信系统设备、终端设备、电子元器件、射频前端、光模块、4G/5G/6G、宽带、IoT、数字经济、AI)、先进材料产业链(金属材料、高分子材料、陶瓷材料、纳米材料等)、机械制造产业链(数控机床、工程机械、电气机械、3C自动化、工业机器人、激光、工控、无人机)、食品药品、医疗器械、农业等。邮箱:market@qyresearch.com

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值