正在浏览标签为 linux网络服务 的文章

如今利用nginx做负载均衡的实例已经很多了,针对不同的应用场合,还有很多需要注意的地方,本文要说的就是在通过CDN 后到达nginx做负载均衡时请求头中的X-Forwarded-For项到底发生了什么变化。下图为简单的web架构图:

nginx_x_forwarded_for.png
nginx 负载均衡

先来看一下X-Forwarded-For的定义:
X-Forwarded-For:简称XFF头,它代表客户端,也就是HTTP的请求端真实的IP,只有在通过了HTTP 代理或者负载均衡服务器时才会添加该项。它不是RFC中定义的标准请求头信息,在squid缓存代理服务器开发文档中可以找到该项的详细介绍。
标准格式如下:
X-Forwarded-For: client1, proxy1, proxy2
从标准格式可以看出,
X-Forwarded-For头信息可以有多个,中间用逗号分隔,第一项为真实的客户端ip,剩下的就是曾经经过的代理或负载均衡的ip地址,经过几个就会出现几个。

按照上图的Web架构图,可以很容易的看出,当用户请求经过CDN后到达Nginx负载均衡服务器时,其X-Forwarded-For头信息应该为 客户端IP,CDN的IP 但实际情况并非如此,一般情况下CDN服务商为了自身安全考虑会将这个信息做些改动,只保留客户端IP。我们可以通过php程序获得X-Forwarded-For信息或者通过Nginx的add header方法来设置返回头来查看。

下面来分析请求头到达Nginx负载均衡服务器的情况;在默认情况下,Nginx并不会对X-Forwarded-For头做任何的处理,除非用户使用proxy_set_header 参数设置:
proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;

$proxy_add_x_forwarded_for变量包含客户端请求头中的"X-Forwarded-For",与$remote_addr用逗号分开,如果没有"X-Forwarded-For" 请求头,则$proxy_add_x_forwarded_for等于$remote_addr。

$remote_addr变量的值是客户端的IP

当Nginx设置X-Forwarded-For等于$proxy_add_x_forwarded_for后会有两种情况发生

1、如果从CDN过来的请求没有设置X-Forwarded-For头(通常这种事情不会发生),而到了我们这里Nginx设置将其设置为$proxy_add_x_forwarded_for的话,X-Forwarded-For的信息应该为CDN的IP,因为相对于Nginx负载均衡来说客户端即为CDN,这样的话,后端的web程序时死活也获得不了真实用户的IP的。

2、CDN设置了X-Forwarded-For,我们这里又设置了一次,且值为$proxy_add_x_forwarded_for的话,那么X-Forwarded-For的内容变成 ”客户端IP,Nginx负载均衡服务器IP“如果是这种情况的话,那后端的程序通过X-Forwarded-For获得客户端IP,则取逗号分隔的第一项即可

如上两点所说,如果我们知道了CDN设置了X-Forwarded-For信息,且只有客户端真实的IP的话,那么我们的Nginx负载均衡服务器可以不必理会该头,让它默认即可。

其实Nginx中还有一个$http_x_forwarded_for变量,这个变量中保存的内容就是请求中的X-Forwarded-For信息。如果后端获得X-Forwarded-For信息的程序兼容性不好的话(没有考虑到X-Forwarded-For含有多个IP的情况),最好就不要将X-Forwarded-For设置为 $proxy_add_x_forwarded_for。应该设置为$http_x_forwarded_for或者干脆不设置!

参考文章:http://en.wikipedia.org/wiki/X-Forwarded-For

原创文章,转载请注明: 转自 http://salogs.com

今天测试了一下在squid上建一个ssl代理转发.其实也蛮容易的.

  1. https_port 443 cert=/etc/squid/SSL.CRT key=/etc/squid/SSL.KEY defaultsite=ssl.php-oa.com
  2. cache_peer ssl.php-oa.com parent 80 o no-query no-digest originserver name=www
  3. cache_peer_homain www .php-oa.com

其实真的很容易.是吧.有个https_port和cache_peer加上那个ssl的地址基本就好了.记的https_port要加defaultsite.不加会下面错

The following error was encountered:

Invalid Request

Some aspect of the HTTP Request is invalid. Possible problems:

Missing or unknown request method

Missing URL

Missing HTTP Identifier (HTTP/1.0)

Request is too large

Content-Length missing for POST or PUT requests

Illegal character in hostname; underscores are not allowed

可以使用下面命令可以生成测试用的证书:

openssl req -new -keyout key.pem -nodes -x509 -days 365 -out cert.pem

如果要生成一个证书请求用于申请正式证书请用下面两个命令:

1.生成私钥 openssl genrsa -out key.pem 1024
2.生成待签名证书 openssl req -new -out req.csr -key key.pem

然后将req.csr文件中的内容提交给证书颁发机构。

Creating Certificates

$ openssl req -new -x509 -days 365 -out server.crt -keyout server.key

Creating a Certificate Signing Request (CSR)

$ openssl req -new -out server.csr -keyout server.key

Creating a Decrypted certificate

Create the certificate as above, then:

$ mv server.key server.key.encrypted
$ openssl rsa -in server.key.encrypted -out server.key

Viewing Certificates

$ openssl x509 -noout -text -in <name>.crt

Viewing Keys

$ openssl rsa -noout -text -in <name>.key

转载自:扶凯[http://www.php-oa.com]

来自nginx wiki

The module ngx_http_core_module supports the built-in variables, whose names correspond with the names of variables in Apache.

First of all, these are the variables, which represent the lines of the title of the client request, for example:
$http_host
$http_user_agent
$http_referer
$http_via
$http_x_forwarded_for
$http_cookie
$content_length
$content_type

Furthermore, there are other variables:

$arg_PARAMETER, this variable contains the value of the GET request variable PARAMETER if present in the query string

$args, this variable is equal to arguments in the line of request;

$content_length, this variable is equal to line “Content-Length” in the header of request;

$content_type, this variable is equal to line “Content-Type” in the header of request;

$document_root, this variable is equal to the value of directive root for the current request;

$document_uri, the same as $uri;

$host, this variable is equal to line “Host” in the header of request or name of the server, to whom the request arrived, if there is no this line;

$is_args evaluates to “?” if $args is set, “” otherwise.

$limit_rate, the variable allows to limit connection rate;

$query_string, the same as $args;

$request_method, this variable is equal to the method of request, usually this “GET” or “POST”;

$remote_addr, this variable is equal to the address of client;

$remote_port, this variable is equal to the port of client;

$remote_user, this variable is equal to the name of user, authenticated by ngx_http_auth_basic_module;

$request_filename, this variable is equal to path to the file for the current request, formed from directives root or alias and URI request;

$request_body_file, client request body temporary filename;

$request_uri, this variable is equal to the complete initial URI together with the arguments;

$scheme, the HTTP scheme (http, https). Evaluated only on demand, for example:

rewrite ^(.+)$ $scheme://example.com$1 redirect;

$server_protocol, this variable is equal to the protocol of request, usually this “HTTP/1.0″ or “HTTP/1.1″;

$server_addr, the variable is equal to the server address, to whom arrived the request. As a rule, for obtaining the value of this variable is done one system call. In order to avoid system call, it is necessary to indicate addresses in directives listen and to use parameter bind;

$server_name, this variable is equal to the name of the server, to whom arrived the request;

$server_port, this variable is equal to the port of the server, to which the request arrived;

$uri, this variable is equal to current URI in the request, it can differ from initial, for example by internal redirects, or with the use of index it is file with internal redirects.

nginx的性能远远优于apache,但由于nagios的web界面中包含php和c-cgi程序,因此需要两套fcgi管理工具(并非必须)和两套解释器(必须)。php用php-cgi跑就可以,c-cgi我选用fcgiwrap。下面介绍安装/配置步骤。

环境介绍:

先前环境:apache+php+nagios 除了nagios 其余的都使用yum自动安装
目标环境:nginx+php5.2.10(php-fpm patch)+nagios 均为源码编译安装

php-fpm:是为PHP打的一个FastCGI管理补丁,可以平滑变更php.ini配置而无需重启php-cgi
Spawn-fcgi:是lighttpd的一个分支项目,是一个cgi进程的管理器

● php 打php-fpm补丁,编译时启用--enable-fastcgi --enable-fpm 参数,使用php-fpm管理php-cgi。php安装详细步骤参见 张宴文章:http://blog.s135.com/nginx_php_v5/
● c-cgi 使用 Spawn-fcgi 管理 ,利用fcgiwrap驱动。fcgiwrap 介绍参见 http://nginx.localdomain.pl/wiki/FcgiWrap

php-cgi 监听 127.0.0.1:9000
fcgiwrap 监听 127.0.0.1:10000

nagios 安装配置不是本文重点,略过。web 目录如下:
/usr/local/nagios/share

安装配置

yum install fcgi fcgi-devel -y

php-fpm 的配置与运行这里略过,下面主要讲解Spawn-fcgi+fcgiwrap 的安装与配置

spawn-fcgi

# wget http://www.lighttpd.net/download/spawn-fcgi-1.6.2.tar.gz
# tar -xvzf spawn-fcgi-1.6.2.tar.gz
# cd spawn-fcgi-1.6.2/
# ./configure
# make
# cp src/spawn-fcgi /usr/local/bin/

fcgiwrap

# wget http://github.com/gnosek/fcgiwrap/tarball/master
# tar -xvzf gnosek-fcgiwrap-28ac6f9aa5e7dadf9aaf2062ab003a0fb4c82ad8.tar.gz
# cd gnosek-fcgiwrap-28ac6f9aa5e7dadf9aaf2062ab003a0fb4c82ad8/
# make
# mv fcgiwrap /usr/local/bin/

创建一个shell脚本来用spawn-fcgi 启动fcgiwrap实例
# vi /usr/local/bin/c-fcgi.sh

#!/bin/sh
/usr/local/bin/spawn-fcgi -f /usr/local/bin/fcgiwrap -a 127.0.0.1 -p 10000 -F 3 -P /var/run/fastcgi-c.pid -u www -g www

# chmod +x /usr/local/bin/c-fcgi.sh

创建一个系统启动进程,方便使用service 和chkconfig 命令管理
# vi /etc/init.d/c-fcgi

#!/bin/bash
# c-fcgi - this script starts and stops the fcgiwrap instance
#
# chkconfig:   - 96 28
# description:  c-fcgi
# processname: c-fcgi

C_SCRIPT=/usr/local/bin/c-fcgi.sh

RETVAL=0

case "$1" in
start)
echo "Starting fastcgi"
$C_SCRIPT
RETVAL=$?
;;
stop)
echo "Stopping fastcgi"
killall -9 fcgiwrap
RETVAL=$?
;;
restart)
echo "Restarting fastcgi"
killall -9 fcgiwrap
$C_SCRIPT
RETVAL=$?
;;
*)
echo "Usage: c-fastcgi {start|stop|restart}"
exit 1
;;
esac
exit $RETVAL
# <span style="color: #0000ff;">chkconfig --add c-fcgi</span>
# <span style="color: #0000ff;">chkconfig c-fcgi on</span>
# <span style="color: #0000ff;">service c-fcgi start</span>

验证启动,是否提供了相应的端口
# netstat -tulnp

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name
tcp        0      0 127.0.0.1:9000              0.0.0.0:*                   LISTEN      32629/php-cgi
tcp        0      0 127.0.0.1:10000             0.0.0.0:*                   LISTEN      20039/fcgiwrap

# ps -ef | grep fcgiwrap | grep -v grep

www      20039     1  0 15:20 ?        00:00:00 /usr/local/bin/fcgiwrap
www      20040     1  0 15:20 ?        00:00:00 /usr/local/bin/fcgiwrap
www      20041     1  0 15:20 ?        00:00:00 /usr/local/bin/fcgiwrap

# ps -ef | grep php-cgi | grep -v grep

root     32629     1  0 13:37 ?        00:00:00 /usr/local/php/bin/php-cgi --fpm --fpm-config /usr/local/php/etc/php-fpm.conf
.
.
.
www      32642 32629  0 13:37 ?        00:00:00 /usr/local/php/bin/php-cgi --fpm --fpm-config /usr/local/php/etc/php-fpm.conf

我php-fpm配置启动32个php-cgi 实例

配置nginx

user                www www;
worker_cpu_affinity 0001 0010 0100 1000;
worker_processes        4;

# 可以在下方直接使用 [ debug | info | notice | warn | error | crit ]  参数
error_log   /usr/local/nginx/logs/nginx_error.log   crit;

pid     /var/run/nginx.pid;

#进程所能打开的最大文件描述符个数
worker_rlimit_nofile    51200;

events
{
# linux 2.6+ 版本以上的内核推荐使用 epoll 事件模式
use             epoll;

# 最大连接数=worker_processes*worker_connections/4
worker_connections  4096;
}

http
{
include     ./conf.d/mime.types;
default_type    application/octet-stream;

charset utf-8;

server_names_hash_bucket_size   128;
client_header_buffer_size       32k;
large_client_header_buffers     4   32k;
client_max_body_size            8m;

sendfile        on;
tcp_nopush  on;

keepalive_timeout   60;

tcp_nodelay     on;

# global fastcgi configure
include         ./conf.d/fastcgi_custom.conf;

# include fastcgi_params.conf
include               ./conf.d/fastcgi_params.conf;

# gzip configure
include         ./conf.d/gzip.conf;

#limit_zone  crawler  $binary_remote_addr  10m;

server
{
listen          80;
server_name     cacti.opt.jobkoo.com;
index           index.html index.htm index.php;
root            /data/www/cacti;

#limit_conn   crawler  20;

location ~ .*\.(php|php5)?$
{
fastcgi_pass        127.0.0.1:9000;
fastcgi_index       index.php;
}

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires     30d;
}

location ~ .*\.(js|css)?$
{
expires     1h;
}

log_format  access  '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" $http_x_forwarded_for';
access_log  /usr/local/nginx/logs/access.log  access;
}

server
{
listen          80;
server_name     nagios.opt.jobkoo.com;
index           index.html index.htm index.php;
root            /usr/local/nagios/share/;

auth_basic      "Welcome to Jobkoo Nagios Monitor System!";
auth_basic_user_file    ./conf.d/htpasswd;

# 这个rewrite针对的是pnp插件的鼠标移动到图标后显示的浮动窗
rewrite     ^/nagios/pnp/(.*)\.php /pnp/$1.php break;

# 以 cgi 结尾的文件
location ~ \.cgi$ {
root    /usr/local/nagios/sbin;
rewrite ^/nagios/cgi-bin/(.*)\.cgi /$1.cgi break;

fastcgi_pass   127.0.0.1:10000;
fastcgi_index  index.cgi;

}

# 以 php/php5 结尾的文件
location ~ \.(php|php5)+$
{
fastcgi_pass        127.0.0.1:9000;
fastcgi_index       index.php;
}

log_format  wwwlogs  '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" $http_x_forwarded_for';
access_log      /usr/local/nginx/logs/nagios.access.log  wwwlogs;
}

server
{
listen          80;
server_name     status.apt.jobkoo.com;

location / {
stub_status     on;
access_log      off;
}
}
}

/etc/nginx/conf.d 目录下的cgi 参数配置文件
#vi /etc/nginx/conf.d/fastcgi_custom.conf

fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;

# vi /etc/nginx/conf.d/fastcgi_params.conf

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx;

fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

设置nagios页面身份验证
# htpasswd -c /etc/nginx/conf.d/htpasswd admin
# cat /etc/nginx/conf.d/htpasswd
admin:QqbxsY3jdkOpQ

配置nagios

#vi /usr/local/nagios/etc/cgi.cfg
use_authentication=1

# service nagios start
# service nginx start

访问nagios页面
nagios_nginx.png

原创文章,转载请注明: 转自 http://salogs.com

squid.conf

抢沙发
?View Code SQUID_CONF
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#squid.conf
#服务器IP 192.168.108.109
 
#Squid信息设置
visible_hostname squid2.jobkoo.com
cache_mgr root@localhost.localdomain
 
 
#监听服务器的80端口,透明代理,支持域名和IP的虚拟主机
http_port 80 accel vhost vport defaultsite=www.myhome2.com
 
 
#基本ACL设置
acl all src 0.0.0.0/0.0.0.0
acl Localhost src 127.0.0.1
acl myhost src 192.168.108.108 192.168.108.109 192.168.108.161 192.168.108.162
acl localnet  src 127.0.0.1 192.168.108.108 192.168.108.109
 
#仅允许80端口的代理
acl Safe_ports port 80 3130
 
# 定义可以清理缓存的访问权限
acl PURGE method PURGE
 
#允许本地管理
acl Manager proto cache_object # cache_object机制是squid的特性。它用于访问squid的缓存管理接口
 
# 防盗链
acl allow_ref referer_regex -i ^http://.+\.myhome2\.com/.*$ ^http://.+\.jobkoo\.com/.*$
acl deny_ref referer_regex -i .+
http_access allow allow_ref
http_access deny deny_ref
 
#deny_info http://www.baidu.com/img/baidu_logo.gif fdlacl
 
# icp 配置
icp_port 3130
log_icp_queries on
icp_hit_stale on
icp_query_timeout 200
# 只允许定义的localhost 主机执行icp查询
icp_access allow localnet
icp_access deny all
 
# 访问控制
http_access allow myhost
http_access allow Manager Localhost
http_access deny Manager
http_access deny !Safe_ports
http_access allow all
http_access allow PURGE localhost
http_access deny PURGE
 
 
 
#基本设置
cache_effective_user squid
cache_effective_group squid
tcp_recv_bufsize 65535 bytes
 
 
# 配置 squid2 为其邻居,当 squid1 在其缓存中没有找到请求的资源
# 时,通过 ICP 查询去其邻居中取得缓存
cache_peer		squid1.jobkoo.com sibling 80  3130 proxy-only
cache_peer_access	squid1.jobkoo.com allow  all
 
# squid1 的2个父节点,originserver 参数指明是源服务器,round-robin
# 参数指明 squid 通过轮询方式将请求分发到其中一台父节点;squid 同时会对这些
# 父节点的健康状态进行检查,如果父节点 down 了,那么 squid 会从剩余的 origin 
# 服务器中抓取数据
cache_peer 192.168.108.161 parent 80 0 no-query originserver round-robin name=webServer1
cache_peer 192.168.108.162 parent 80 0 no-query originserver round-robin name=webServer2
 
# www.myhome.com 域的请求通过 RR 轮询方式转发到2个父节点中的一个
cache_peer_domain webServer1 webServer2 www.myhome2.com
 
# hierarchy_stoplist cgi-bin ?
 
# squid 用于缓存的内存量
cache_mem 256 MB
 
# Cooper:内存中缓存的最大对象 512K 
maximum_object_size_in_memory 512 KB
 
# 缓存目录
cache_dir ufs /var/spool/squid 1000 16 256
 
# 能缓存的最大对象为 10M
maximum_object_size 10240 KB
 
# 访问日志
logformat squid  %ts.%03tu %6tr %>a %Ss/%03Hs %<st %rm %ru %un %Sh/%<A %mt
logformat combined %>a %ui %un [%tl] "%rm %ru HTTP/%rv" %Hs %<st "%{Referer}>h" "%{User-Agent}>h"
access_log /var/log/squid/access.log squid
access_log /var/log/squid/access_apache.log combined
 
# Cache 日志
cache_log /var/log/squid/cache.log
 
refresh_pattern -i .html 60 90% 10080 ignore-reload
refresh_pattern -i .png 60 90% 10080 reload-into-ims
refresh_pattern -i .jpg 1440 90% 129600 ignore-reload 
refresh_pattern -i .gif 1440 90% 129600 ignore-reload 
refresh_pattern -i .js 1440 90% 10080 ignore-reload 
refresh_pattern -i .css 1440 90% 10080 reload-into-ims
refresh_pattern -i .swf 1440 90% 129600 reload-into-ims 
refresh_pattern -i .bmp 1440 90% 129600 reload-into-ims 
 
# 定义不缓存的对象
acl QUERY urlpath_regex cgi-bin \? \.php
cache deny QUERY
 
coredump_dir /var/spool/squid

转自:www.hiadmin.com
原有的配置文件如下

?View Code SQUID_CONF
1
2
3
4
5
6
7
8
9
10
11
12
13
14
cache_peer 10.11.12.51 parent 80 0 no-query originserver round-robin name=web1
cache_peer 10.11.12.52 parent 80 0 no-query originserver round-robin name=web2
cache_peer 10.11.12.53 parent 80 0 no-query originserver round-robin name=web3
cache_peer 10.11.12.54 parent 80 0 no-query originserver round-robin name=web4
cache_peer 10.11.12.160 parent 80 0 no-query originserver name=content
cache_peer 10.11.12.150 parent 80 0 no-query originserver name=bbs
cache_peer 172.16.10.140 parent 80 0 no-query originserver round-robin name=game1
cache_peer 172.16.10.141 parent 80 0 no-query originserver round-robin name=game2
 
cache_peer_domain contentchina content.web.com
cache_peer_domain bbs  bbs.web.com
cache_peer_domain game1 game2 game.web.com
cache_peer_domain web1 web2 web3 web4  .web.com
cache_peer_domain web1 web2 web3 web4   web.com

设定不同的二级域名分发到不同的服务器上.
www.web.com能够正确访问.
查看后台链接.每次访问时squid也会正常去连parent服务器,每次都轮询访问
测试game.web.com
返回有很多内容都是404
但是单独访问140以及141都是没有问题
然后发现很多链接分发到了其他web服务器上
看了说明.里面提到round-robin参数会设置一组随机的访问
感觉是写了round-robin的都是一个组
所以将game的去掉round-robin参数

?View Code SQUID_CONF
1
2
cache_peer 172.16.10.140 parent 80 0 no-query originserver name=game1
cache_peer 172.16.10.141 parent 80 0 no-query originserver name=game2

访问后仍旧发现还是有分发错误的情况
再次查看squid.conf.default
里面的cache_peer_domain的语法如下

?View Code SQUID_CONF
1
2
#       cache_peer_domain cache-host domain [domain ...]
#       cache_peer_domain cache-host !domain

感觉是否是因为cache-host这里只能写一台服务器而非一组的关系
随将配置文件修改

?View Code SQUID_CONF
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
cache_peer 10.11.12.51 parent 80 0 no-query originserver round-robin name=web1
cache_peer 10.11.12.52 parent 80 0 no-query originserver round-robin name=web2
cache_peer 10.11.12.53 parent 80 0 no-query originserver round-robin name=web3
cache_peer 10.11.12.54 parent 80 0 no-query originserver round-robin name=web4
cache_peer 10.11.12.160 parent 80 0 no-query originserver name=content
cache_peer 10.11.12.150 parent 80 0 no-query originserver name=bbs
cache_peer 172.16.10.140 parent 80 0 no-query originserver round-robin name=game1
cache_peer 172.16.10.141 parent 80 0 no-query originserver round-robin name=game2
 
cache_peer_domain contentchina content.web.com
cache_peer_domain bbs  bbs.web.com
cache_peer_domain game1 game.web.com
cache_peer_domain game2 game.web.com
cache_peer_domain web1 .web.com
cache_peer_domain web2 .web.com
cache_peer_domain web3 .web.com
cache_peer_domain web4 .web.com
cache_peer_domain web1 web.com
cache_peer_domain web2 web.com
cache_peer_domain web3 web.com
cache_peer_domain web4 web.com

修改后访问game.web.com
问题解决.没有出现404
后台的分发很正常
可能由于cache-host这里写了一组
导致squid并无法辨识进行针对性的分发
随即将所有的分发都分发到所有round-robin服务器上.
因为www.web.com后端的服务器较多.命中的概率较大.
而命中后第二次取出文件即是squid中的缓存文件,所以访问www.web.com时没有发现问题
而game.web.com因为真实服务器比例较小
分发时很多链接分发到其他web服务器.
导致反馈回很多404

概述:

这里摘抄BIND9手册中的一段话“视图是 BIND9 的强大的新功能, 允许名称服务器根据询问者的不同有区别的回答 DNS查询。特别是当运行拆分 DNS 设置而不需要运行多个服务器时特别有用。”手册中说得很明了,只是根据不同的来源DNS服务器做出不同的回应。

应用场合:

(1)    需要将域名分成内网和外网两个不同的区域进行解析
(2)    根据不同的来源IP做出相对于来源IP的解析(电信的用户查询,返回电信网络的服务器地址,网通的查询返回网通服务器地址)

试验环境

DNS服务器环境
CentOS 5.2

所需要的包

bind-chroot-9.3.4 将bind主程序关在家里面
bind-libs-9.3.4 Bind程序运行库
bind-9.3.4 Bind服务器主程序
bind-utils-9.3.4 Bind客户端相关命令
caching-nameserver-9.3.4 named.conf等配置文件的示例

网络环境

DNS

eth0:115.12.65.254

eth1:192.168.0.254

WWW Server

eth0: 115.12.65.3

eth1:192.168.0.250

MailServer

eth0: 115.12.65.4

eth1:192.168.0.251

FtpServer

eth0: 115.12.65.5

eth1:192.168.0.252

配置

mv /etc/named.caching-nameserver.conf /etc/named.conf
#将文件名修改为程序需要的名称,实际上/etc/下的named.caching-nameserver.conf文件是个连接文件,其准确位置在/var/named/chroot/etc/目录中,由于我们安装了bind-chroot包,所有的配置文件都在/var/named/chroot/的相关目录下,这里我只需要将/etc/下的连接文件修改为named.conf文件即可,由于named守护进程查找的就是/etc/下的named.conf所以我这一步一定要做。
vi /etc/named.conf

acl "lan"{192.168.0.0/24;};    //定义本地局域网网段地址ACL

options {
listen-on port 53 { any; };    //这里可以写any或者将DNS主机的两个地址写进去
directory       "/var/named";
dump-file       "/var/named/data/cache_dump.db";
statistics-file "/var/named/data/named_stats.txt";
memstatistics-file "/var/named/data/named_mem_stats.txt";
allow-query     { any; };
};
logging {
channel default_debug {
file "data/named.run";
severity dynamic;
};
};
view localhost_resolver {
match-clients      { localhost; };
match-destinations { localhost; };
recursion yes;
include "/etc/named.rfc1912.zones";
};
//定义内网的视图
view inside{
match-clients   {"lan";}; //指定匹配的地址
recursion yes;
zone "example.com" {
type    master;
file    "named.lan.example.com";
allow-transfer{none;};
};
zone "0.168.192.in-addr.arpa"{
type master;
file    "named.192.168.0";
};
};

//定义外网的视图
view outside{
match-clients   {"any";};
recursion yes;

zone "example.com"{
type    master;
file    "named.wan.example.com";
allow-transfer{none;};
};
zone "1.0.10.in-addr.arpa"{
type master;
file    " named.115.12.65";
};
};

针对内网
vi /var/named/chroot/var/named/named.lan.example.com

$TTL    86400
@               IN SOA  ns1.      root.ns1. (
42              ; serial (d. adams)
3H              ; refresh
15M             ; retry
1W              ; expiry
1D )            ; minimum
@          IN      NS      ns1.example.com.
@          MX     10      mail.example.com.
ns1         IN      A       192.168.0.254
www        IN      A       192.168.0.250
bbs         IN      CNAME  www
mail         IN      A       192.168.0.251
ftp          IN      A       192.168.0.252

vi /var/named/chroot/var/named/named.192.168.0

$TTL    86400
@               IN SOA  @       root (
42              ; serial (d. adams)
3H              ; refresh
15M             ; retry
1W              ; expiry
1D )            ; minimum

IN      NS      @
254       IN      PTR     ns1.example.com.
250       IN      PTR     www.example.com.
251       IN      PTR     mail.example.com.
252       IN      PTR     ftp.example.com.

针对外网
vi /var/named/chroot/var/named/named.wan.example.com

$TTL    86400
@               IN SOA  ns1.      root.ns1. (
42              ; serial (d. adams)
3H              ; refresh
15M             ; retry
1W              ; expiry
1D )            ; minimum
@          IN      NS      ns1.example.com.
@          MX     10      mail.example.com.
ns1         IN      A       115.12.65.254
www        IN      A       115.12.65.3
bbs         IN      CNAME  www
mail         IN      A       115.12.65.4
ftp          IN      A       115.12.65.5

vi /var/named/chroot/var/named/named.115.12.65

$TTL    86400
@               IN SOA  @       root (
42              ; serial (d. adams)
3H              ; refresh
15M             ; retry
1W              ; expiry
1D )            ; minimum

IN      NS      @
254     IN      PTR     ns1.example.com.
3       IN      PTR     www.example.com.
4       IN      PTR     mail.example.com.
5       IN      PTR     ftp.example.com.

至此dns的配置文件都已经配置好了,接下来就是启动服务了;
service named restart
chkconfig named on    //随系统启动

注意事项:

(1)    视图语句的顺序是很重要的,一位用户的请求将会在它所匹配的第一个视图中被解答。
(2)    在视图语句中定义的域只对匹配视图的用户是可用的。
(3)    通过在多个视图中用相同名称定义一个域,不同域数据可以传给不同的用户。
(4)    许多在 named.conf的options 里的语句中给出的选项也能在视图语句中使用,仅仅用于使用那个视图解答请求的时候。

为了让awstats分析squid的日志,我们要修改一下它的日志格式.我们先看看squid的默认格式和解释吧.

logformat squid  %ts.%03tu %6tr %>a %Ss/%03Hs %<st %rm %ru %un %Sh/%<A %mt

解释如下:
Seconds since epoch; subsecond time (milliseconds);  Response time (milliseconds); Client source IP address;  Squid request status (TCP_MISS etc); HTTP status code; Reply size including HTTP headers;  Request method (GET/POST etc) ; Request URL;  User name;  Squid hierarchy status (DEFAULT_PARENT etc);  Client FQDN;  MIME content type

下面看看要怎么样修改,awstats才能认识和分析squid的日志

squid: /etc/squid/squid.conf
代码:

logformat combined %>a %ui %un [%tl] "%rm %ru HTTP/%rv" %Hs %<st "%{Referer}>h" "%{User-Agent}>h" %Ss:%Sh %{host}>h
access_log /var/log/squid/access.log combined

awstats: /etc/awstats/awstats.conf.local
代码:

LogFormat = "%host %other %logname %time1 %methodurl %code %bytesd %refererquot %uaquot %other %virtualname"
LogFile="/var/log/squid/access.log"

关键点: squid 的日志需要加上虚拟主机名: %{host}>h awstats的读取参数指出 %virtualname 还有一种方法,我觉得也是比较理想的,直接修改apache的日志格式:

原:
#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

修改为:
LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\""combined

这样也可以将apache的日志转为正常的日志。

转载自:扶凯[http://www.php-oa.com]

用处:

1.用lvs之后,放了多台前端用的Web Server,每台Server有各自的日志.我们分开使用分析软件分析和检查是非常困难的,所以我们使用合并的方法.
2.多个域名,日志分开,使用awstats之类的分析软件进行分析很麻烦,所以需要合并
3.使用google的软件来做sitemap之类的应用,检查也会非常麻烦,所以需要合并
4.象多个节点的CDN日志,要进行流量统计和分析需要合并
5.因为日志文件过大,一个服务器生成多个日志文件.象access_log.1、access_log.2、access_log.3…以此类推,所以要合并.
等等…..

问题
对合并,进行日志排序最麻烦的一个问题就是,容易在跨天过程中生成的非正常数据.用一个前辈的话,这些不正常的日志,对awstats之类,就象吃了虫子一样,还有可能冲掉你以前的所有数据。

解决方法1(多谢东东):
在分析日志前,使用
sort -m -t " " -k 4 -o log_all log1 log2 log3
注释:
-m: 使用 merge优化算法

解决方法2:
使用 awstats 内建的工具logresolvemerge.pl 来合并日志 ,方法非常容易,主要是更改网站的设定档就好了,编辑 /etc/awstats/awstats.php-oa.conf
找到 LogFile 的地方,原来预设单个 log 的设定如下:

LogFile="/var/log/httpd/access_log"(原设置)

修改成
LogFile="/usr/local/awstats/tools/logresolvemerge.pl /var/log/httpd/access_log* |" (合并分析新的设置)

如上,其实只要 logresolvemerge.pl 的路径还有日志的路径及使用匹配来设置即可,记的后面加一个"|"。注意上面我是要合并 access_log.1、access_log.2、access_log.3 的日志,要是你的日志名为别的,记的使用匹配符来匹配你要一起合并分析的日志.
另外.默认logresolvemerge.pl 是放在 awstats 安装路径的 tools 里面,比如我们的 awstats 是装在/usr/local/awstats 里面,所以完整路径就是 /usr/local/awstats/tools/logresolvemerge.pl 。

编辑保存后,再来执行更新记录的程序即可,如:
#/usr/local/awstats/wwwroot/cgi-bin/awstats.pl -config=xxx -update

再来进去您的网址就可以看到合并后输出的结果了,如:

http://www.yoursite.com/awstats/awstats.pl?config=xxx

转载自:扶凯[http://www.php-oa.com]

LVS的监控

已有 2 条评论

一、利用ipvsadm命令

通常情况下lvs的运行情况以及资源使用情况是无法使用top或vmstat命令时来查看的。对于LVS-DR结构的LVS来说,其只会转发网络包。几乎不会耗费CPU资源,这时我们查看系统负载应该为0.00。

通过使用ipvsadm命令可以查看当前LVS的运行情况,如下:

[root@LVS-Master]# ipvsadm
Prot LocalAddress:Port Scheduler Flags
-> RemoteAddress:Port Forward Weight ActiveConn InActConn
TCP localhost:https wlc persistent 50
-> localhost:https Route 1 0 0
-> localhost:https Route 1 0 0
TCP localhost:http wlc persistent 50
-> localhost:http Route 1 0 0
-> localhost:http Route 3 0 0

当有新连接过来时,其相关的计数就会增加。

查看连接数/进入包(字节)/输出包(字节):

命令:ipvsadm -Ln --stats -t |u|f service-address
-t, --tcp-service
-u, --udp-service
-f, --fwmark-service
-L, -l, --list List the virtual server table if no argument is specified.
-n, --numeric Numeric output.
--stats Output of statistics information.

示例:

[root@experiment ~]# ipvsadm -Ln --stats -t 192.168.108.180:80
Prot LocalAddress:Port Conns InPkts OutPkts InBytes OutBytes
-> RemoteAddress:Port
TCP 192.168.108.180:80 5771754 101697K 0 5338M 0
-> 192.168.108.162:80 454297 13736280 0 761572K 0
-> 192.168.108.161:80 5317457 87961304 0 4576M 0

另外通过查看cat /proc/net/ip_vs_stats 也可以查看lvs信息,只不过这里的输出时16进制的。

[root@LVS-Master] # cat /proc/net/ip_vs_stats
Total Incoming Outgoing         Incoming         Outgoing
Conns  Packets  Packets            Bytes            Bytes
594BFC  6335751        0        145F90EC1                0

Conns/s   Pkts/s   Pkts/s          Bytes/s          Bytes/s
0              0             0                     0                     0

二、利用第三方软件以图形的形式查看LVS信息

网上查找了很多资料,只找到了2种比较简单的方法来实现LVS的图形化监控;
1、利用net-snmp-lvs-module 给net-snmp加个模块,然后配合cacti的相关模板来实现监控。由于针对64位系统的net-snmp-lvs-module只支持到rhel4因此放弃使用。

相关网址:net-snmp-lvs-module-0.0.4.tar.gz

2、利用lvs_rrd工具来生成图形
lvs_rrd 工具实现了网页的形式来查看lvs状态图功能。其主要有两个脚本组成:信息收集脚本和图像绘制脚本。信息收集脚本是将lvs的信息生成rrd格式的数据文件,然后利用图像绘制脚本生成图像,并生成一个php页面,这个页面中引用其所生成的图像,这样我们可以通过web页面的形式查看生成的php页面,就可以时时的查看lvs的状态信息了。

lvs_rrd部署
lvs_rrd需要部署在LVS-Master和LVS-Backup上,更准确的说lvs_rrd中的信息收集脚本一定要在LVS director 上运行。通过配置图像生成脚本和图像的生成目录,我们可以将他们时时的复制到其他的服务器中。这里为了方便起见我将它们部署到了LVS director上。

下面简单的介绍部署的步骤

(1).开启LVS director 的apache,配置相关参数,注意端口一定不能为80,我这里修改为9160。指定DocumentRoot 为 "/data/web"
(2).下载lvs_rrd软件。下载地址:lvs-rrd-v0.7.tar.gz
(3).将lvs-rrd-v0.7.tar.gz解压后将文件夹复制到/data/web/目录下并更名为lvs
(4).配置lvs.rrd.update文件
RRDTOOL="/usr/bin/rrdtool"
IPVSADM="/sbin/ipvsadm"
WORKDIR="/data/web/lvs"

配置graph-lvs.sh
WORKDIR="/data/web/lvs"
RRDTOOL="/usr/bin/rrdtool"
GRAPHS="$WORKDIR/graphs"
WEBPATH="/lvs/graphs"

这两个文件根据自己的情况设置一下就可以了。

(5). 将/data/web/lvs/graphs目录修改为apache可读可写。
# chown apache.apache /data/web/lvs/graphs -R
(6).将收集信息的脚本添加到计划任务中
# crontab -e
* * * * * /data/web/lvs/lvs.rrd.update 2> /dev/null > /dev/null

(7).等1分钟后,看lvs目录中是否生成了以rrd为扩展名的文件。如果有的话就可以启动apache通过http://ipaddress:9160/lvs/查看lvs的状态了。如下图:

上面的三张图是lvs_rrd官方给的,由于我搭建的是lvs的测试环境,没有实际使用那么多连接,生成的图像也不是很好看,在这里就贴一张吧:

原创文章,转载请注明: 转自 http://salogs.com