3.1 HAproxy

HAproxy原理

    HAProxy 是一款提供高可用性、负载均衡以及基于TCP(第四层)和HTTP(第七层)应用的代理软件,支持虚拟主机,它是免费、快速并且可靠的一种解决方案。 HAProxy特别适用于那些负载特大的web站点,这些站点通常又需要会话保持或七层处理。HAProxy运行在时下的硬件上,完全可以支持数以万计的 并发连接。并且它的运行模式使得它可以很简单安全的整合进您当前的架构中, 同时可以保护你的web服务器不被暴露到网络上。

    HAProxy 实现了一种事件驱动、单一进程模型,此模型支持非常大的并发连接数。多进程或多线程模型受内存限制 、系统调度器限制以及无处不在的锁限制,很少能处理数千并发连接。事件驱动模型因为在有更好的资源和时间管理的用户端(User-Space) 实现所有这些任务,所以没有这些问题。此模型的弊端是,在多核系统上,这些程序通常扩展性较差。这就是为什么他们必须进行优化以 使每个CPU时间片(Cycle)做更多的工作。

    HAProxy 支持连接拒绝 : 因为维护一个连接的打开的开销是很低的,有时我们很需要限制攻击蠕虫(attack bots),也就是说限制它们的连接打开从而限制它们的危害。 这个已经为一个陷于小型DDoS攻击的网站开发了而且已经拯救了很多站点,这个优点也是其它负载均衡器没有的。

    HAProxy 支持全透明代理(已具备硬件防火墙的典型特点): 可以用客户端IP地址或者任何其他地址来连接后端服务器. 这个特性仅在Linux 2.4/2.6内核打了cttproxy补丁后才可以使用. 这个特性也使得为某特殊服务器处理部分流量同时又不修改服务器的地址成为可能。

性能

HAProxy借助于OS上几种常见的技术来实现性能的最大化。

1,单进程、事件驱动模型显著降低了上下文切换的开销及内存占用。
2,O(1)事件检查器(event checker)允许其在高并发连接中对任何连接的任何事件实现即时探测。
3,在任何可用的情况下,单缓冲(single buffering)机制能以不复制任何数据的方式完成读写操作,这会节约大量的CPU时钟周期及内存带宽;
4,借助于Linux 2.6 (>= 2.6.27.19)上的splice()系统调用,HAProxy可以实现零复制转发(Zero-copy forwarding),在Linux 3.5及以上的OS中还可以实现零复制启动(zero-starting);
5,内存分配器在固定大小的内存池中可实现即时内存分配,这能够显著减少创建一个会话的时长;
6,树型存储:侧重于使用作者多年前开发的弹性二叉树,实现了以O(log(N))的低开销来保持计时器命令、保持运行队列命令及管理轮询及最少连接队列;
7,优化的HTTP首部分析:优化的首部分析功能避免了在HTTP首部分析过程中重读任何内存区域;

8,精心地降低了昂贵的系统调用,大部分工作都在用户空间完成,如时间读取、缓冲聚合及文件描述符的启用和禁用等;

    所有的这些细微之处的优化实现了在中等规模负载之上依然有着相当低的CPU负载,甚至于在非常高的负载场景中,5%的用户空间占用率和95%的系统空间占用率也是非常普遍的现象,这意味着HAProxy进程消耗比系统空间消耗低20倍以上。因此,对OS进行性能调优是非常重要的。即使用户空间的占用率提高一倍,其CPU占用率也仅为10%,这也解释了为何7层处理对性能影响有限这一现象。由此,在高端系统上HAProxy的7层性能可轻易超过硬件负载均衡设备。

    在生产环境中,在7层处理上使用HAProxy作为昂贵的高端硬件负载均衡设备故障故障时的紧急解决方案也时长可见。硬件负载均衡设备在“报文”级别处理请求,这在支持跨报文请求(request across multiple packets)有着较高的难度,并且它们不缓冲任何数据,因此有着较长的响应时间。对应地,软件负载均衡设备使用TCP缓冲,可建立极长的请求,且有着较大的响应时间。

安装及配置HAproxy

安装 HAproxy

[root@CentOS74 ~]# yum info haproxy
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
Installed Packages
Name        : haproxy
Arch        : x86_64
Version     : 1.5.18         #在7.4版本的centos中安装的是1.5版本
Release     : 6.el7
Size        : 2.6 M
Repo        : installed
From repo   : base          #来自base源
Summary     : TCP/HTTP proxy and load balancer for high availability environments
URL         : http://www.haproxy.org/
License     : GPLv2+
Description : HAProxy is a TCP/HTTP reverse proxy which is particularly suited for high
            : availability environments. Indeed, it can:
            :  - route HTTP requests depending on statically assigned cookies
            :  - spread load among several servers while assuring server persistence
            :    through the use of HTTP cookies
            :  - switch to backup servers in the event a main server fails
            :  - accept connections to special ports dedicated to service monitoring
            :  - stop accepting connections without breaking existing ones
            :  - add, modify, and delete HTTP headers in both directions
            :  - block requests matching particular patterns
            :  - report detailed status to authenticated users from a URI
            :    intercepted by the application

    HAproxy 的主配置文件保存在 /etc/haproxy/haproxy.cfg 中

[root@CentOS74 ~]# ll /etc/haproxy/haproxy.cfg
-rw-r--r-- 1 root root 3142 Jul 15 04:24 /etc/haproxy/haproxy.cfg

    代理配置段:

- defaults <name>
- frontend <name>
- backend  <name>

- listen   <name>

    配置 HAproxy 实现加权轮询

[root@CentOS74 ~]# cat /etc/haproxy/haproxy.cfg
#---------------------------------------------------------------------
# Example configuration for a possible web application.  See the
# full configuration options online.
#
#   http://haproxy.1wt.eu/download/1.4/doc/configuration.txt
#
#---------------------------------------------------------------------

#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global      #全局配置段
    # to have these messages end up in /var/log/haproxy.log you will
    # need to:
    #
    # 1) configure syslog to accept network log events.  This is done
    #    by adding the '-r' option to the SYSLOGD_OPTIONS in
    #    /etc/sysconfig/syslog
    #
    # 2) configure local2 events to go to the /var/log/haproxy.log
    #   file. A line like the following can be added to
    #   /etc/sysconfig/syslog
    #
    #    local2.*                       /var/log/haproxy.log
    #
    log         127.0.0.1 local2    #日志配置,需要配置rsyslog服务

    chroot      /var/lib/haproxy
    nbproc      2                   #打开的子进程数量
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        haproxy
    group       haproxy
    daemon

    # turn on stats unix socket
    stats socket /var/lib/haproxy/stats

#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
defaults      #默认参数配置
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    option forwardfor       except 127.0.0.0/8
    option                  redispatch
    retries                 3
    timeout http-request    10s
    timeout queue           1m
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    timeout http-keep-alive 10s
    timeout check           10s
    maxconn                 3000    #每个haproxy进程所能接受的最大并发连接数

#---------------------------------------------------------------------
# main frontend which proxys to the backends
#---------------------------------------------------------------------
frontend  main *:80     #代理服务器配置
    mode http
    default_backend    websvr

#---------------------------------------------------------------------
# round robin balancing between the various backends
#---------------------------------------------------------------------
backend websvr          #后端服务器配置
    balance     roundrobin
    server  web1 192.168.30.174:8000 check
    server  web2 192.168.30.75:80 check

    其他参数:

nbproc <number>:要启动的haproxy的进程数量
maxconn <number>:设定每个haproxy进程所能接受的最大并发连接数,总体的并发连接数:nbproc * maxconn
maxconnrate <number>:每个进程每秒种所能创建的最大连接数量
maxsessrate <number>:每个进程每秒钟所能创建的最大会话数量
maxsslconn <number>: 设定每个haproxy进程所能接受的ssl的最大并发连接数

bind:指定代理服务器的监听端口,设置完成后只能重启服务,重载配置无效

frontend  main
    bind *:80
    bind *:443 ssl crt /etc/haproxy/ssl.pem  #声明监听端口,声明使用ssl加密并且指定证书文件路径
    mode http
    default_backend    websvr

balance:后端服务器组内的服务器调度算法

    调度算法:

roundrobin:
动态轮询:支持权重的运行时调整,支持慢启动;每个后端中最多支持4095个主机
server options: weight 
static-rr:

静态轮询:不支持权重的运行时调整及慢启动;后端主机数量无上限

leastconn:
动态,推荐使用在具有较长会话的场景中,例如MySQL、LDAP等

first:
根据服务器在列表中的位置,自上而下进行调度;上一个服务器的连接数达到上限,新请求才会分配给下一台服务器,会忽视服务器上的权重

source:源地址hash;

uri:对URI的左半部分做hash计算,并由服务器总权重相除以后派发至某挑出的服务器;

左半部分:/<path>;<params>

整个uri:/<path>;<params>?<query>#<frag>

url_param:对用户请求的uri的<params>部分中的参数的值作hash计算,并由服务器总权重相除以后派发至某挑出的服务器;通常用于追踪用户,以确保来自同一个用户的请求始终发往同一个Backend Server;

hdr(<name>):对于每个http请求,此处由<name>指定的http首部将会被取出做hash计算; 并由服务器总权重相除以后派发至某挑出的服务器;没有有效值的会被轮询调度; 

    hash-type:哈希算法类型

map-based:除权取余法,哈希数据结构是静态的数组
consistent:一致性哈希,哈希数据结构是一个树

一致性哈希:哈希环模型

    因为除权取余法对整个集群的架构有极强的状态依赖性,比如:
    n个节点中有一个宕掉了,这时候节点数量变更为n-1,此时的映射公式变成 hash(Job)%(n-1)
    由于Job数量增加,需要新增机器,此时的映射公式变成 hash(Job)%(n+1)

    上述两种情形可以看到,基本上所有的Job会被重新分配到跟节点变动前不同的节点上,意味着需要迁移几乎所有正在运行的Job,想想这样会给系统带来多大的复杂性和性能损耗。

    一致性哈希是一种Hashing算法,典型的特征是:在减少或者添加节点时,可以尽可能地保证已经存在Key映射关系不变,尽可能地减少Key的迁移。

<function>: 使用的哈希函数
    sdbm
    djb2
    wt6

#---------------------------------------------------------------------
# round robin balancing between the various backends
#---------------------------------------------------------------------
backend websvr
    balance     uri        #使用uri调度算法
    hash-type consistent   #使用一致性哈希算法
    server  web1 192.168.30.174:8000 check weight 2
    server  web2 192.168.30.75:80 check weight 1

    多次访问不同的页面,测试 uri 调度算法。

[root@CentOS69 ~]# for i in {1..5} ;do curl http://192.168.30.74/index8.html ;done
host 192.168.30.174 of 8
host 192.168.30.174 of 8
host 192.168.30.174 of 8
host 192.168.30.174 of 8
host 192.168.30.174 of 8
[root@CentOS69 ~]# for i in {1..5} ;do curl http://192.168.30.74/index9.html ;done
host 192.168.30.174 of 9
host 192.168.30.174 of 9
host 192.168.30.174 of 9
host 192.168.30.174 of 9
host 192.168.30.174 of 9
[root@CentOS69 ~]# for i in {1..5} ;do curl http://192.168.30.74/index10.html ;done
host 192.168.30.75 of 10
host 192.168.30.75 of 10
host 192.168.30.75 of 10
host 192.168.30.75 of 10
host 192.168.30.75 of 10

server : 定义后端主机的各服务器及其选项

    语法:server <名称> <地址>[:端口] [选项]...

<name>:服务器在haproxy上的内部名称;出现在日志及警告信息中;
<address>:服务器地址,支持使用主机名;
[:[port]]:端口映射;省略时,表示同bind中绑定的端口;
maxconn <maxconn>:当前server的最大并发连接数;
backlog <backlog>:当前server的连接数达到上限后的后援队列长度;
backup:设定当前server为备用服务器;
check:对当前server做健康状态检测;
    addr :检测时使用的IP地址;
    port :针对此端口进行检测;
    inter <delay>:连续两次检测之间的时间间隔,默认为2000ms; 
    rise <count>:连续多少次检测结果为“成功”才标记服务器为可用;默认为2;

    fall <count>:连续多少次检测结果为“失败”才标记服务器为不可用;默认为3;

    注意:option httpchk,"smtpchk","mysql-check","pgsql-check" ,"ssl-hello-chk" 用于定义应用层检测方法;

    语法:option httpchk 方法 uri [版本]

#---------------------------------------------------------------------
# round robin balancing between the various backends
#---------------------------------------------------------------------
backend websvr
    balance     roundrobin
    option httpchk GET /index.html HTTP/1.0   #启用七层检测
    server  web1 192.168.30.174:8000 check
    server  web2 192.168.30.75:80 check

cookie <value>:为当前server指定其cookie值,用于实现基于cookie的会话黏性;
disabled:标记为不可用;
on-error <mode>:后端服务故障时的行动策略;
    fastinter: force fastinter
    fail-check: simulate a failed check, also forces fastinter (default)
    sudden-death: simulate a pre-fatal failed health check, one more failed check will mark a server down, forces fastinter

    mark-down: mark the server immediately down and force fastinter

redir <prefix>:将发往此server的所有GET和HEAD类的请求重定向至指定的URL;
weight <weight>:权重,默认为1;

#---------------------------------------------------------------------
# round robin balancing between the various backends
#---------------------------------------------------------------------
backend websvr
    balance     roundrobin
    server  web1 192.168.30.174:8000 check redir http://192.168.30.69  weight 2  #将请求转发至指定URL
    server  web2 192.168.30.75:80 check weight 1
[root@CentOS69 ~]# curl -IL 192.168.30.74
HTTP/1.1 302 Found    #302重定向
Cache-Control: no-cache
Content-length: 0
Location: http://192.168.30.69/   #重定向至http://192.168.30.69
Connection: close

HTTP/1.1 200 OK   #成功访问
Date: Sat, 09 Jun 2018 12:31:46 GMT
Server: Apache/2.2.15 (CentOS)
Last-Modified: Sat, 09 Jun 2018 12:24:42 GMT
ETag: "60429-16-56e3499e34742"
Accept-Ranges: bytes
Content-Length: 22
Connection: close
Content-Type: text/html; charset=UTF-8

cookie : 为后端服务器打上标签,当客户端发送报文头部中带有相应 cokkie 的请求时,就会调度至对应后端

    语法:cookie 变量名 [方法] [报文类型]

    方法:

rewirte:重写;
insert:插入;
prefix:前缀;

#---------------------------------------------------------------------
# round robin balancing between the various backends
#---------------------------------------------------------------------
backend websvr
    balance     roundrobin
    cookie Server_Name insert nocache indirect   #定义cookie选项
    server  web1 192.168.30.174:8000 check cookie Server1  #定义本server的cookie标记
    server  web2 192.168.30.75:80 check cookie Server2

    使用 chrome 访问,并查看 cookie 值

    使用 curl 命令指定 cookie 的内容

[root@CentOS69 ~]# for i in {1..5} ;do curl -b "Server_Name=Server1" http://192.168.30.74/index1.html ;done
host 192.168.30.174 of 1
host 192.168.30.174 of 1
host 192.168.30.174 of 1
host 192.168.30.174 of 1
host 192.168.30.174 of 1
[root@CentOS69 ~]# for i in {1..5} ;do curl -b "Server_Name=Server2" http://192.168.30.74/index1.html ;done
host 192.168.30.75 of 1
host 192.168.30.75 of 1
host 192.168.30.75 of 1
host 192.168.30.75 of 1
host 192.168.30.75 of 1

 stats enable : 启用统计页;基于默认的参数启用stats page:
    stats uri   : /haproxy?stats
    stats realm : "HAProxy Statistics"
    stats auth  : no authentication

    stats scope : no restriction

stats auth <user>:<passwd>  认证时的账号和密码,可以有多个
stats realm <realm>  认证时的realm
stats uri <prefix>  自定义stats page uri
stats refresh <delay>  设定自动刷新时间间隔

stats admin { if | unless } <cond>  启用stats page中的管理功能

#---------------------------------------------------------------------
# main frontend which proxys to the backends
#---------------------------------------------------------------------
frontend  main
    bind *:80
    bind *:443 ssl crt /etc/haproxy/ssl.pem
    mode http
    default_backend    websvr
listen stats
    bind *:9527
    stats enable
    stats uri /admin?stats
    stats realm "Admin Login"
    stats auth linux:centos
    stats admin if TRUE

maxconn <conns>:为指定的frontend定义其最大并发连接数;默认为2000;

mode { tcp|http|health }  定义haproxy的工作模式

    tcp:基于layer4实现代理;可代理mysql, pgsql, ssh, ssl等协议
    http:仅当代理的协议为http时使用

    health:工作为健康状态检查的响应模式,当连接请求到达时回应“OK”后即断开连接

option forwardfor [ except <network> ] [ header <name> ]

在由haproxy发往后端主机的请求报文中添加“X-Forwarded-For”首部,其值前端客户端的地址;用于向后端主发送真实的客户端IP

    [ except <network> ]:请求报文来自此处指定的网络时不予添加此首部

    [ header <name> ]:使用自定义的首部名称,而非默认“X-Forwarded-For”

reqadd  <string> [{if | unless} <cond>]  添加代理服务器向后端服务器的请求报文头部

req[i]del  <search> [{if | unless} <cond>]  删除代理服务器向后端服务器的请求报文头部

rspadd <string> [{if | unless} <cond>]  添加代理服务器向客户端的响应报文头部
rsp[i]del  <search> [{if | unless} <cond>  删除代理服务器向客户端的响应报文头部

#---------------------------------------------------------------------
# main frontend which proxys to the backends
#---------------------------------------------------------------------
frontend  main
    bind *:80
    bind *:443 ssl crt /etc/haproxy/ssl.pem
    mode http
    default_backend    websvr
    reqadd X-Nmae:\ jiangbowen   #在请求报文中添加名为X-Name的头部信息
    rspidel ^Server.*            #删除响应报文中以"Server"开头的头部信息
    rspadd X-Server:\ BestServer #在响应报文中添加"X-Server: BestServer"的头部信息

acl <aclname> <criterion> [flags] [operator] [<value>] ...

aclname : 访问控制列表名称

<criterion> :
四层访问控制
    dst : ip
    dst_port : integer
    src : ip
    src_port : integer
七层访问控制
path : string  路径匹配
    path : 精准匹配
    path_beg : 首部匹配
    path_dir : 子目录匹配
    path_dom : 子域名匹配
    path_end : 尾部匹配
    path_len : 长度匹配
    path_reg : 正则表达式匹配
    path_sub : 模糊匹配
url : string  uri匹配
    url : exact string match
    url_beg : prefix match
    url_dir : subdir match
    url_dom : domain match
    url_end : suffix match
    url_len : length match
    url_reg : regex match
    url_sub : substring match
req.hdr([<name>[,<occ>]]) : string  请求报文头部内容匹配
    hdr([<name>[,<occ>]])     : exact string match
    hdr_beg([<name>[,<occ>]]) : prefix match
    hdr_dir([<name>[,<occ>]]) : subdir match
    hdr_dom([<name>[,<occ>]]) : domain match
    hdr_end([<name>[,<occ>]]) : suffix match
    hdr_len([<name>[,<occ>]]) : length match
    hdr_reg([<name>[,<occ>]]) : regex match
    hdr_sub([<name>[,<occ>]]) : substring match                

<flags>
    -i : 忽略字符大小写
    -m : 使用特殊匹配方法
    -n : 禁用DNS反向解析
    -u : 强制使用相同的ACL名称
    -- : 强制结束ACL匹配

[operator] 
    匹配整数值:eq、ge、gt、le、lt
    匹配字符串:
- exact match (-m str) : 精准匹配
- substring match (-m sub) : 模糊匹配
- prefix match (-m beg) : 首部匹配
- suffix match (-m end) : 为不匹配
- subdir match (-m dir) : 子目录匹配
- domain match (-m dom) : 子域名匹配

acl作为条件时的逻辑关系:
当两个 criterion 以空格连接时表示逻辑与
当两个 criterion 以"||"连接时表示逻辑与
当一个 criterion 前以 ! 开头表示取反

    简单实现动静分离调度

#---------------------------------------------------------------------
# main frontend which proxys to the backends
#---------------------------------------------------------------------
frontend  main
    bind *:80
    bind *:443 ssl crt /etc/haproxy/ssl.pem
    mode http
    default_backend    dynamicsvr   #默认没有匹配的调度至动态服务器

    acl uri_static	path_beg	-i /static /images /javascript /html   #匹配存放静态内容的uri
    acl file_static	path_end	-i .jpg .gif .peg .css .js   #匹配静态内容的文件

    use_backend staticsvr  if  uri_static || file_static   #当匹配任意一个ACL时调度至静态服务器

#---------------------------------------------------------------------
# round robin balancing between the staticsvr backends
#---------------------------------------------------------------------
backend staticsvr
    balance     roundrobin
    option httpchk GET /index.html HTTP/1.0
    server  web1 192.168.30.174:8000 check

#---------------------------------------------------------------------
# round robin balancing between the dynamicsvr backends
#---------------------------------------------------------------------
backend dynamicsvr
    balance     roundrobin
    server  web2 192.168.30.75:80 check

内置默认ACL
FALSE    always_false    never match
HTTP    req_proto_http    match if protocol is valid HTTP
HTTP_1.0    req_ver 1.0    match HTTP version 1.0
HTTP_1.1    req_ver 1.1    match HTTP version 1.1
HTTP_CONTENT    hdr_val(content-length) gt 0    match an existing content-length
HTTP_URL_ABS    url_reg ^[^/:]*://    match absolute URL with scheme
HTTP_URL_SLASH    url_beg /    match URL beginning with "/"
HTTP_URL_STAR    url *    match URL equal to "*"
LOCALHOST    src 127.0.0.1/8    match connection from local host
METH_CONNECT    method CONNECT    match HTTP CONNECT method
METH_GET    method GET HEAD    match HTTP GET or HEAD method
METH_HEAD    method HEAD    match HTTP HEAD method
METH_OPTIONS    method OPTIONS    match HTTP OPTIONS method
METH_POST    method POST    match HTTP POST method
METH_TRACE    method TRACE    match HTTP TRACE method
RDP_COOKIE    req_rdp_cookie_cnt gt 0    match presence of an RDP cookie
REQ_CONTENT    req_len gt 0    match data in the request buffer
TRUE    always_true    always match
WAIT_END    wait_end    wait for end of content analysis

连接超时时长:        
timeout client <timeout>  客户端非活动时长,默认单位是毫秒
timeout server <timeout>  服务器非活动时长
timeout http-keep-alive <timeout>  持久连接的持久时长
timeout http-request <timeout>  客户端请求报文发送时长
timeout connect <timeout>  后端服务器响应时长
timeout client-fin <timeout>  客户端半连接时长
timeout server-fin <timeout>  服务器半关闭时长

猜你喜欢

转载自blog.csdn.net/M30_Miriam/article/details/81047228
3.1