当前位置: 首页 > 工具软件 > Varnish Agent > 使用案例 >

varnish 编译安装

单于庆
2023-12-01

下载地址:http://varnish-cache.org/releases/
这里用的是varnish-4.1.11版本
varnish4版本使用python2.6即可,varnish6版本要求python2.7

visudo
注释掉 Defaults requiretty 这行

安装:
安装依赖包:
yum -y install autoconf automake jemalloc-devel libedit-devel libtool ncurses-devel pcre-devel pkgconfig python-docutils python-sphinx
yum -y install gcc gcc-c++ openssl openssl-devel openssh-clients wget make lrzsz unzip zip xz ntpdate lsof telnet epel-release vim tree libselinux-python

cd /usr/local/src/
tar -zxf varnish-4.1.11.tgz
cd varnish-4.1.11
./configure --prefix=/home/tools/varnish
make
make install
[root@slave2 src]# cd /home/tools/varnish/
[root@slave2 varnish]# ll
total 40
drwxr-xr-x 2 root root 4096 Jun 26 18:37 bin
drwxr-xr-x 3 root root 4096 Jun 26 15:46 include
drwxr-xr-x 4 root root 4096 Jun 26 15:46 lib
drwxr-xr-x 2 root root 4096 Jun 26 15:46 sbin
drwxr-xr-x 6 root root 4096 Jun 26 15:46 share
drwxr-xr-x 3 root root 4096 Jun 27 09:59 var

创建日志目录:
mkdir logs

配置:
创建配置文件:
cat /home/tools/varnish/default.vcl

vcl 4.0;
# 加载后端轮询模块
import directors;
# 创建健康监测
probe backend_healthcheck {
    .url = "/health.html";
    .window = 5;
    .threshold = 2;
    .interval = 5s;
    .timeout  = 3s;
}
# 创建后端主机
backend web1 {
    .host = "192.168.1.223";
    .port = "80";
    .probe = backend_healthcheck;
}
backend web2 {
    .host = "192.168.1.223";
    .port = "80";
    .probe = backend_healthcheck;
}
backend img1 {
    .host = "192.168.1.223";
    .port = "80";
    .probe = backend_healthcheck;
}
backend img2 {
    .host = "192.168.1.223";
    .port = "80";
    .probe = backend_healthcheck;
}
# 创建后端主机组,基于round_robin轮转
sub vcl_init {
    new web_cluster = directors.round_robin();
    web_cluster.add_backend(web1);
    web_cluster.add_backend(web2);
    new img_cluster = directors.round_robin();
    img_cluster.add_backend(img1);
    img_cluster.add_backend(img2);
}
# 定义PURGE方法访问来源IP
acl purgers {
        "127.0.0.1";
        #"192.168.0.0"/24;
}
sub vcl_recv {
    # 带cookie首部的GET请求也缓存
    if (req.method == "GET" && req.http.cookie) {
        return(hash);
    }
    # health.html文件不缓存
    if (req.url ~ "health.html") {
        return(pass);
    }
    # PURGE请求的处理
    if (req.method == "PURGE") {
        if (!client.ip ~ purgers) {
            return(synth(405,"Method not allowed"));
        }
        return(hash);
    }
    # 为发往后端主机的请求添加X-Forward-For首部
    if (req.restarts == 0) {
        if (req.http.X-Fowarded-For) {
            set req.http.X-Forwarded-For = req.http.X-Forwarded-For + "," + client.ip;
        } else {
            set req.http.X-Forwarded-For = client.ip;
        }
    }
    # 匹配不通的URL,分发至不同的后端主机组
    if (req.url ~ "\.(jpg|jpeg|gif|png)$") {
        set req.backend_hint = img_cluster.backend();
    } else {
    #} elseif (req.url ~ "\.(html|css|js)$") {
        set req.backend_hint = web_cluster.backend();
    }
    set req.backend_hint = web_cluster.backend();
    return(hash);
}
# PURGE请求的处理
sub vcl_hit {
    if (req.method == "PURGE") {  
        return(synth(200,"Purged"));
    }
}
# PURGE请求的处理
sub vcl_miss {
    if (req.method == "PURGE") {
        return(synth(404,"Not in cache"));
    }
}
# PURGE请求的处理
sub vcl_pass {
    if (req.method == "PURGE") {
        return(synth(502,"PURGE on a passed object"));
    }
}
# 自定义缓存文件的缓存时长,即TTL值
sub vcl_backend_response {
    if (bereq.url ~ "\.(jpg|jpeg|gif|png)$") {
        set beresp.ttl = 7200s;
    }
    if (bereq.url ~ "\.(html|css|js)$") {
        set beresp.ttl = 1200s;
    }
    # 定义带Set-Cookie首部的后端响应不缓存,直接返回给客户端
    if (beresp.http.Set-Cookie) {
        return(deliver);
    }
}
# 为响应添加X-Cache首部,显示缓存是否命中
sub vcl_deliver {
    if (obj.hits > 0) {
        set resp.http.X-Cache = "HIT from " + server.ip;
    } else {
        set resp.http.X-Cache = "MISS from " + server.ip;
    }
}

创建普通账号:

groupadd varnish
useradd -s /sbin/nologin -g varnish varnish -M

授权varnish安装目录:
chown -R varnish. /home/tools/varnish

[root@slave2 varnish]# ll
total 44
drwxr-xr-x 2 varnish varnish 4096 Jun 26 18:37 bin
-rw-r--r-- 1 varnish varnish 3099 Jun 26 18:52 default.vcl
drwxr-xr-x 3 varnish varnish 4096 Jun 26 15:46 include
drwxr-xr-x 4 varnish varnish 4096 Jun 26 15:46 lib
drwxr-xr-x 2 varnish varnish 4096 Jun 27 12:12 logs
drwxr-xr-x 2 varnish varnish 4096 Jun 26 15:46 sbin
drwxr-xr-x 6 varnish varnish 4096 Jun 26 15:46 share
drwxr-xr-x 3 varnish varnish 4096 Jun 27 09:59 var

命令启动:
sudo -u varnish /home/tools/varnish/sbin/varnishd -f /home/tools/varnish/default.vcl -s malloc,1G -T 127.0.0.1:20000 -a 0.0.0.0:8888 -p thread_pool_min=50 -p thread_pool_max=1000 -P /home/tools/varnish/varnish.pid
-s:指定使用内存进行缓存,内存大小1G
-T:指定管理IP和端口
-a:指定访问IP和端口
-p:指定单个pool打开的最小thread和最大thread(pool数一般与CPU核数一致)
-P:pid进程文件
命令停止:
pkill varnish

脚本启动:
创建配置文件:
cat /etc/sysconfig/varnish

# Configuration file for Varnish Cache
#
# /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 number of threads (for ulimit -u)
NPROCS="unlimited"
# Maximum size of corefile (for ulimit -c). Default in Fedora is 0
# DAEMON_COREFILE_LIMIT="unlimited"
# Init script support to reload/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.
RELOAD_VCL=1
# Set WARMUP_TIME to force a delay in reload-vcl between vcl.load and vcl.use
# This is useful when backend probe definitions need some time before declaring
# configured backends healthy, to avoid routing traffic to a non-healthy backend.
#WARMUP_TIME=0
# Main configuration file.
VARNISH_VCL_CONF=/home/tools/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_PORT=8888
#
# Telnet admin interface listen address and port
VARNISH_ADMIN_LISTEN_ADDRESS=127.0.0.1
VARNISH_ADMIN_LISTEN_PORT=20000
#
# Shared secret file for admin interface
VARNISH_SECRET_FILE=/home/tools/varnish/secret
#
# The minimum number of worker threads to start
VARNISH_MIN_THREADS=50
#
# The Maximum number of worker threads to start
VARNISH_MAX_THREADS=1000
#
# Cache file size: in bytes, optionally using k / M / G / T suffix.
VARNISH_STORAGE_SIZE=1G
#
# Backend storage specification
VARNISH_STORAGE="malloc,${VARNISH_STORAGE_SIZE}"
#
# Default TTL used when the backend does not specify one
VARNISH_TTL=120
#
# DAEMON_OPTS is used by the init script.
DAEMON_OPTS="-a ${VARNISH_LISTEN_ADDRESS}:${VARNISH_LISTEN_PORT} \
             -f ${VARNISH_VCL_CONF} \
             -T ${VARNISH_ADMIN_LISTEN_ADDRESS}:${VARNISH_ADMIN_LISTEN_PORT} \
             -p thread_pool_min=${VARNISH_MIN_THREADS} \
             -p thread_pool_max=${VARNISH_MAX_THREADS} \
             -S ${VARNISH_SECRET_FILE} \
             -s ${VARNISH_STORAGE}"

创建secret安全文件:

[root@slave2 varnish]# cat /home/tools/varnish/secret 
65c8db78-464e-4450-91c0-789b2a4f96a4

创建reload_vcl文件:
chmod +x /home/tools/varnish/bin/varnish_reload_vcl
cat /home/tools/varnish/bin/varnish_reload_vcl

#!/bin/bash
#
# reload vcl revisited
# A script that loads new vcl based on data from /etc/sysconfig/varnish
# Ingvar Hagelund <ingvar@redpill-linpro.com>
#
# This is free software, distributed under the standard 2 clause BSD license,
# see the LICENSE file in the Varnish documentation directory
#
# 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\"
"
}
# Fallback to the default configuration
if [ -z "$VARNISH_VCL_CONF" ]; then
    . /etc/sysconfig/varnish
fi
# Get warmup time from defaults or use 0 warmup
WARMUP=${WARMUP_TIME:-0}
$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="/home/tools/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 $4 } ' | 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 $4 } ' )
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
# Wait before vcl.use if WARMUP > 0
# Used if backend probes require some time to set backends healthy
sleep $WARMUP
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

chmod +x /home/tools/varnish/bin/varnish_reload_vcl

创建脚本文件:
cat /etc/init.d/varnish

#!/bin/sh
#
# Init script for Varnish Cache.
#
# chkconfig: - 90 10
# description: Varnish is a high-performance HTTP accelerator
# processname: varnishd
# config: /etc/sysconfig/varnish
# pidfile: /var/run/varnish.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-performance HTTP accelerator
### END INIT INFO
# Source function library.
. /etc/init.d/functions
retval=0
pidfile=/home/tools/varnish/varnish.pid
exec="/home/tools/varnish/sbin/varnishd"
reload_exec="/home/tools/varnish/bin/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 Cache: "
    # 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}
    # Maximum number of threads (default in CentOS is 1024, which
    # is often too small for varnish)
    ulimit -u ${NPROCS:-unlimited}
    # If defined, set maximum core size.
    if [ -n "${DAEMON_COREFILE_LIMIT}" ]
    then
        ulimit -c ${DAEMON_COREFILE_LIMIT}
    fi
        # $DAEMON_OPTS is set in /etc/sysconfig/varnish.
    if [ "$DAEMON_OPTS" = "" ]; then
        echo "\$DAEMON_OPTS is empty."
        echo -n "Please put configuration options in $config"
        return 6
    else
        daemon --pidfile $pidfile sudo -u varnish $exec "$DAEMON_OPTS" -P $pidfile
        retval=$?
        if [ $retval -eq 0 ]
        then
            touch $lockfile
            echo_success
            echo
        else
            echo_failure
            echo
        fi
        return $retval
    fi
}
stop() {
    echo -n "Stopping Varnish Cache: "
    killproc -p $pidfile $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 -p $pidfile $prog
}
rh_status_q() {
    rh_status >/dev/null 2>&1
}
configtest() {
    if [ -f "$VARNISH_VCL_CONF" ]; then
        $exec -C $DAEMON_OPTS -n /tmp 2>/dev/null
    if [ "$?" = 0 ]; then
        echo "Syntax ok"
    else
        $exec -C $DAEMON_OPTS -n /tmp
        return $?
    fi
    else
    echo "VARNISH_VCL_CONF is unset or does not point to a file."
    fi
}
# 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
        ;;
    configtest)
        configtest
        ;;
    *)
    echo "Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
    exit 2
esac
exit $?

chmod +x /etc/init.d/varnish
chkconfig varnish on

[root@slave2 init.d]# /etc/init.d/varnish start
Starting Varnish Cache:                                    [  OK  ]
[root@slave2 init.d]# 
[root@slave2 init.d]# ps -ef |grep varnish
varnish  23100     1  0 15:16 ?        00:00:00 /home/tools/varnish/sbin/varnishd -a :8888 -f /home/tools/varnish/default.vcl -T 127.0.0.1:20000 -p thread_pool_min=50 -p thread_pool_max=1000 -S /home/tools/varnish/secret -s malloc,1G -P /home/tools/varnish/varnish.pid
varnish  23102 23100  2 15:16 ?        00:00:00 /home/tools/varnish/sbin/varnishd -a :8888 -f /home/tools/varnish/default.vcl -T 127.0.0.1:20000 -p thread_pool_min=50 -p thread_pool_max=1000 -S /home/tools/varnish/secret -s malloc,1G -P /home/tools/varnish/varnish.pid
root     23220  3849  0 15:16 pts/0    00:00:00 grep varnish
[root@slave2 init.d]# /etc/init.d/varnish reload
Loading vcl from /home/tools/varnish/default.vcl
Current running config name is boot
Using new config name reload_2019-06-27T152105
VCL compiled.
VCL 'reload_2019-06-27T152105' now active
available  auto/warm          0 boot
active     auto/warm          0 reload_2019-06-27T152105
Done
[root@slave2 ~]# /home/tools/varnish/bin/varnishadm -T 127.0.0.1:20000 -S /home/tools/varnish/secret backend.list
Backend name                   Admin      Probe
reload_2019-06-27T152105.web1  probe      Healthy 5/5
reload_2019-06-27T152105.web2  probe      Healthy 5/5
reload_2019-06-27T152105.img1  probe      Healthy 5/5
reload_2019-06-27T152105.img2  probe      Healthy 5/5
reload_2019-06-27T152105.img3  probe      Healthy 5/5
[root@slave2 ~]# /home/tools/varnish/bin/varnishadm -T 127.0.0.1:20000 -S /home/tools/varnish/secret help
help [<command>]
ping [<timestamp>]
auth <response>
quit
banner
status
start
stop
vcl.load <configname> <filename> [auto|cold|warm]
vcl.inline <configname> <quoted_VCLstring> [auto|cold|warm]
vcl.use <configname>
vcl.state <configname> [auto|cold|warm]
vcl.discard <configname>
vcl.list
param.show [-l] [<param>]
param.set <param> <value>
panic.show
panic.clear [-z]
storage.list
vcl.show [-v] <configname>
backend.list [-p] [<backend_expression>]
backend.set_health <backend_expression> <state>
ban <field> <operator> <arg> [&& <field> <oper> <arg> ...]
ban.list

日志进程启动:
命令行启动:
sudo -u varnish /home/tools/varnish/bin/varnishncsa -F "%{X-Forwarded-For}i %l %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-agent}i\" %D" -a -w /home/tools/varnish/logs/log.log -D
命令行关闭:
pkill varnishncsa
参数:
-a:当把日志写到文件里时,使用附加方式而不是覆盖;
-C:做正则表达式和字符匹配时不区分大小写;
-d:在日志的首部开始处理日志记录而不是日志结尾;
-D:以守护进程方式运行;
-F format:设置输出日志格式字符串;
-g :日志记录的分组,默认分组为vxid;
-h:打印varnishlog用法并退出;
-n name:指定varnish实例用来获取日志的名称,如果未指定-n参数,那么就使用主机名;
-N filename:指定过时VSM实例的文件名。当使用这个参数时,放弃检查功能会被禁用;
-P file:将进程的PID写入到指定文件中;
-q query:使用指定的VSL;
-V:打印版本信息并退出;
-w filename:重定向输出到指定文件,如果-a参数未指定那么该文件将会被覆盖重写
-F 指定格式FORMAT:
指定可以使用的日志格式,如果未指定那么就使用默认的格式;
默认的日志格式为:
%h %l %u %t "%r" %s %b "%{Referer}i" "%{User-agent}i"
支持转义字符\n和\t;
支持的格式标志符有:
%b:response的字节大小,不包括HTTP报头。当没有字节被发送时,CLF格式中是 - 而不是0;
%D:处理请求的实际时间,单位为微秒;
%H:请求协议。如果不知道的话默认为HTTP/1.0;
%h:远程主机。如果不知道的话默认为 - ;
%I:从客户端接收的总字节大小;
%{X}i:请求报头X的内容;
%l:远程登录用户(总是为 - );
%m:请求方法;如果不知道的话默认为 -
%{X}o:响应报头X的内容;
%O:发送的总字节大小;
%q:查询字符串,如果没有查询字符串存在,使用空字符串;
%r:请求的第一行。从其他字段合成,所以可能不会原样呈现请求;
%s:发送到客户端的状态;
%t:请求被接受时的时间(HTTP date/time格式);
%{X}t:请求被接受时的时间(以指定的X格式)。时间规范格式和strftime一样;
%T:处理请求的实际时间,单位为秒;
%U:不带有任何查询字符串的URL请求。如果不知道的话默认为 - ;
%u:远程认证用户;
%{X}x:扩展变量。支持的变量有:
Varnish:time_firstbyte
从请求开始处理到第一个字节被发送到客户端的时间
Varnish:hitmiss
请求是否命中缓存。pipe和pass被看作是未命中的;
Varnish:handling
请求是如何处理的,它是缓存命中 未命中 pass pipe还是error的;
VCL_Log:key
在VCL中由std.log("key:value")设置值;

脚本启动:
cat /etc/init.d/varnishncsa

#! /bin/sh
#
# Control the Varnish Cache NCSA logging daemon
#
# chkconfig: - 90 10
# description: Varnish Cache logging daemon
# processname: varnishncsa
# config: 
# pidfile: /var/run/varnishncsa.pid
### BEGIN INIT INFO
# Provides: varnishncsa
# Required-Start: $network $local_fs $remote_fs
# Required-Stop: $network $local_fs $remote_fs
# Default-Start:
# Default-Stop:
# Short-Description: start and stop varnishncsa
# Description: Varnish Cache NCSA logging daemon
### END INIT INFO
# Source function library.
. /etc/init.d/functions
retval=0
pidfile="/home/tools/varnish/varnishncsa.pid"
lockfile="/var/lock/subsys/varnishncsa"
logfile="/home/tools/varnish/logs/varnishncsa.log"
exec="/home/tools/varnish/bin/varnishncsa"
prog="varnishncsa"
#DAEMON_OPTS="-a -w $logfile -D -P $pidfile"
DAEMON_OPTS="-F \"%{X-Forwarded-For}i %l %u %t \'%r\' %s %b \'%{Referer}i\' \'%{User-agent}i\' %D\" -a -w $logfile -D -P $pidfile"
# Include varnishncsa defaults
[ -e /etc/sysconfig/varnishncsa ] && . /etc/sysconfig/varnishncsa
start() {
    if [ ! -x $exec ]
    then
        echo $exec not found
        exit 5
    fi
    echo -n "Starting varnish ncsa logging daemon: "
    daemon --pidfile $pidfile sudo -u varnish $exec "$DAEMON_OPTS" 
    echo
    return $retval
}
stop() {
    echo -n "Stopping varnish ncsa logging daemon: "
    killproc -p $pidfile $prog
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}
restart() {
    stop
    start
}
reload() {
    restart
}
force_reload() {
    restart
}
rh_status() {
    status -p $pidfile $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 $?
[root@slave2 init.d]# /etc/init.d/varnishncsa start
Starting varnish ncsa logging daemon:                      [  OK  ]
[root@slave2 init.d]# 
[root@slave2 init.d]# ps -ef |grep varnishncsa
varnish  26502     1  0 16:22 ?        00:00:00 /home/tools/varnish/bin/varnishncsa -F %{X-Forwarded-For}i %l %u %t \'%r\' %s %b \'%{Referer}i\' \'%{User-agent}i\' %D -a -w /home/tools/varnish/logs/varnishncsa.log -D -P /home/tools/varnish/varnishncsa.pid
root     26505  3849  0 16:22 pts/0    00:00:00 grep varnishncsa

chmod +x /etc/init.d/varnishncsa
chkconfig varnishncsa on

[root@slave2 logs]# cat varnishncsa.log 
192.168.1.223 - - [27/Jun/2019:16:43:26 +0800] 'GET http://192.168.1.224:8888/index.html HTTP/1.1' 200 612 '-' 'curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2' 3008
192.168.1.223 - - [27/Jun/2019:16:43:27 +0800] 'GET http://192.168.1.224:8888/index.html HTTP/1.1' 200 612 '-' 'curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2' 56
192.168.1.223 - - [27/Jun/2019:16:43:31 +0800] 'GET http://192.168.1.224:8888/index.html HTTP/1.1' 200 612 '-' 'curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2' 73
192.168.1.223 - - [27/Jun/2019:16:43:32 +0800] 'GET http://192.168.1.224:8888/index.html HTTP/1.1' 200 612 '-' 'curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2' 56

日志切割:
cat cutVarnishLog.sh

#!/bin/bash
dir=/home/tools/varnish/logs/
date1=`date +%Y%m%d`
cd $dir
mv varnishncsa.log varnishncsa.${date1}.log
/etc/init.d/varnishncsa restart
find . -type f -name 'varnishncsa*' -mtime +30 |xargs rm -f

查看内存使用情况:

[root@slave2 varnish]# ./bin/varnishstat -1|grep SMA.s0.g
SMA.s0.g_alloc                               2          .   Allocations outstanding
SMA.s0.g_bytes                             916          .   Bytes outstanding
SMA.s0.g_space                      1073740908          .   Bytes available

SMA.s0.g_bytes:内存使用量
SMA.s0.g_space:内存剩余

[root@slave2 logs]# ll /home/tools/varnish/bin/
total 992
-rwxr-xr-x 1 varnish varnish  72572 Jun 26 15:46 varnishadm
-rwxr-xr-x 1 varnish varnish  98530 Jun 26 15:46 varnishhist
-rwxr-xr-x 1 varnish varnish  96427 Jun 26 15:46 varnishlog
-rwxr-xr-x 1 varnish varnish 141592 Jun 26 15:46 varnishncsa
-rwxr-xr-x 1 root    root      3174 Jun 27 15:06 varnish_reload_vcl
-rwxr-xr-x 1 varnish varnish  97192 Jun 26 15:46 varnishstat
-rwxr-xr-x 1 varnish varnish 366868 Jun 26 15:46 varnishtest
-rwxr-xr-x 1 varnish varnish 124279 Jun 26 15:46 varnishtop

varnishstat 和 varnishtop:统计命令

 类似资料: