heartbeat实现HA!!

来源:互联网 发布:js 验证码倒计时 编辑:程序博客网 时间:2024/05/18 00:45

heartbeat介绍:

Heartbeat 是一个基于Linux开源的,被广泛使用的高可用集群系统,自1999年开始到现在,发布了众多版本,是目前开源Linux-HA项目最成功的一个例子,在行业内得到了广泛的应用,

工作原理:

heartbeat最核心的包括两个部分,心跳监测部分和资源接管部分,心跳监测可以通过网络链路和串口进行,而且支持冗 余链路,它们之间相互发送报文来告诉对方自己当前的状态,如果在指定的时间内未收到对方发送的报文,那么就认为对方失效,这时需启动资源接管模块来接管运 行在对方主机上的资源或者服务。

Heartbeat 工作模式:

主备:(双机热备)

在配置文件ha.cf中修改配置可以制定查那一台hearbeat服务器是主服务器,则另一台将自动成为热被备服务器,在热备服务器上配置heartbeat守护进程来监听主服务器的心跳消息,如果在制定的时间内未能收到心跳信息,热备服务器会认定主服务器已经失败,然后接管主服务的服务和数据,向用户提供不间断的服务,从而达到服务器高可用性(说白了就像一个市有市长和副市长,两个人之间一直有着不间断的联系,副市长一直在问市长你还在吗,市长回答是的我还在,那么副市长就就会继续干着自己的工作(作为一个备用市长(备用的主机))但是当副市长再次询问市长你还在吗市长在一定的时间内没有回答副市长,副市长就会认为市长已经挂了,这是副市长就会接替市长的位置从一个备用市长(备用主机)转换成市长,继续向市民提供服务)这种模式比较消耗资源因为主服务器不挂那么备用服务器就会一直空闲着


主主:(双机互备)

即两台服务器互为主备,这时它们之间会相互发送报文来告诉对方自己当前的状态,如果在指定的时间内为收到对方发送的心跳报文,那么久认为对方失效或者宕机了,这时就会启动自身的资源接管模块来接管运行在对方主机上的资源或者服务,继续对用户提供服务。正常情况下,可以较好的实现主机故障后,业务仍不间断的持续运行。

Heartbeat的心跳连接:

要部署Heartbeat服务至少需要两台之际来完成。那么这两台主机之间是如何做到互相通信和互相监测

串行电缆

一根以太网电缆两网卡

以太网电缆,通过交换机等网络设备连接增加了交换机故障端,同时,线路不是专用心跳线,容易受其他数据传输的   影响。

heartbeat脑裂:

由于两台搞科研服务器对之间在指定时间内,无法互相检查到对法心跳而各自启动故障转移功能,取得了资源及服务的所有权,而此时的两台高可用服务器对都还活着并在正常运行,这样就会导致同一个IP或服务器在两端同时启动而发生冲突的严重问题,最严重的事故两台主机占用一个IP地址,这样会导致两端的数据不一致或造成数据丢失,这种情况被称为裂脑

heartbeat导致裂脑发生的多种原因

高可用服务器对之间心跳链路故障,导致无法正常通信

高可用服务器对上开启了防火墙阻挡了心跳消息传输

高可用服务器对上心跳网卡抵制等信息配置不正确,导致发送心跳失败

其他服务配置不宕机等原因,如心跳方式不同,心跳广播冲突,软件BUG

heartbeat防止裂脑发生的7种秘籍:

1.同时使用串行电缆和以太网电缆连接,同时用两条心跳线路,这样一条线路坏了,另一条还是好的,依然能传送心跳消息

2.检测到裂脑时强行关闭一个心跳节点。相当于程序上备节点发现心跳线故障,发送关机命令到主节点

3.做好裂脑的监控报警(如邮件及手机短信等),在问题发生时人为第一时间介入仲裁,降低损失

4.启用磁盘锁。正在服务一方锁住共享磁盘,“裂脑”发生时,让对方完全“抢不走”共享磁盘资源。但使用锁磁盘也会有一个不小的问题,如果占用共享盘的一方不主动解锁,另一方就永远得不到共享磁盘。现实中假如服务器节点突然死机或崩溃,就不可能执行解锁命令。后备节点也就接管不了共享资源和应用服务。于是有人在HA中设计了‘智能’锁。即,正在服务的一方只在发现心跳线全部断开时才启用磁盘锁。平时就不上锁

5.报警在服务器接管之前,给人员处理留足够的时间

6.不直接自动服务器接管,而是由人为人员控制接管

7.增加仲裁机制,确定谁该获得资源


Heartbeat脚本的默认目录

/etc/init.d/

/etc/ha.d/resource.d/

heartbeat配置文件:

Heartbeat的默认配置文件目录为/etc/ha.dHeartbeat常用的配置文件有三个,ha.cfauthkeyharesource

ha.cf------------------heartbeat参数配置文件-----------------------在这里配置heartbeat的一些基本参数

authkey-------------------heartbeat认证文件-----------------------------高可用服务器对之间根据对端的authkey,对对端进行认证

haresource----heartbeat资源配置文件-------------------如配置IP资源及脚本程序等

实际配置:

操作系统:rhel6.5

准备工作:

两台主机:

172.25.99.66

172.25.99.77

虚拟IP为172.25.99.100

虚拟IP配置在172.25.99.66上,这台主机为master

配置yum源:

一,安装heartbeat:

66主机和77主机都要安装:

安装包:


安装包下载地址:

heartbeat-devel-3.0.4-2.el6.x86_64.rpm

ftp://mirror.switch.ch/pool/4/mirror/epel/6/x86_64/heartbeat-devel-3.0.4-2.el6.x86_64.rpm

heartbeat-3.0.4-2.el6.x86_64.rpm

http://dl.fedoraproject.org/pub/epel/6/x86_64//heartbeat-3.0.4-2.el6.x86_64.rpm

heartbeat-libs-3.0.4-2.el6.x86_64.rpm

ftp://mirror.switch.ch/pool/4/mirror/epel/6/x86_64/heartbeat-libs-3.0.4-2.el6.x86_64.rpm

ldirectord-3.9.5-3.1.x86_64.rpm

ftp://ftp.pbone.NET/mirror/ftp5.gwdg.de/pub/opensuse/repositories/network%3A/ha-clustering%3A/Stable/RedHat_RHEL-6/x86_64/ldirectord-3.9.5-3.1.x86_64.rpm

安装上面的四个安装包:

yum install *

复制配置文件

heartbeat的配置文件目录在/etc/ha.d/

ha.cf主配置文件

haresourcs资源配置文件

authkeys认证信息

把以上三个配置文件cp到/etc/ha.d/下并且修改authkeys这个配置文件的权限600为了安全考虑

配置文件复制完成后我们修改配置文件信息

#      There are lots of options in this file.  All you have to have is a set
#      of nodes listed {"node ...} one of {serial, bcast, mcast, or ucast},
#      and a value for "auto_failback".
#      必须设置的有节点列表集{node ...},{serial,bcast,mcast,或ucast}中的一个,auto_failback的值
#
#      ATTENTION: As the configuration file is read line by line,
#                  THE ORDER OF DIRECTIVE MATTERS!
#      配置文件是逐行读取的,并且选项的顺序是会影响最终结果的。
#
#      In particular, make sure that the udpport, serial baud rate
#      etc. are set before the heartbeat media are defined!
#      debug and log file directives go into effect when they
#      are encountered.
#
#      确保在udpport,serial baud rate在heartbeat检测前预先定义或预留可用
#      也就是是在定义网卡,串口等心跳检测接口前先要定义端口号。
#
#      All will be fine if you keep them ordered as in this example.
#      如果保持本样例中的定义顺序,本配置将会正常工作。
#
#      Note on logging:
#      If all of debugfile, logfile and logfacility are not defined,
#      logging is the same as use_logd yes. In other case, they are
#      respectively effective. if detering the logging to syslog,
#      logfacility must be "none".
#      记录日志方面的注意事项:
#      如果debugfile,logfile和logfacility都没有定义,日志记录就相当于use_logd yes。
#      否则,他们将分别生效。如果要阻止记录日志到syslog,那么logfacility必须设置为“none”
#
#      File to write debug messages to 
#写入debug消息的文件
#debugfile /var/log/ha-debug
#
#
#      File to write other messages to 
#     
#单独指定日志文件
logfile        /var/log/ha-log
#
#
#      Facility to use for syslog()/logger
#用于syslog()/logger的设备,通常情况下不建议与logfile同时启用
#logfacility    local0
#
#
#      A note on specifying "how long" times below...
#
#      The default time unit is seconds
#              10 means ten seconds
#
#      You can also specify them in milliseconds
#              1500ms means 1.5 seconds
#
#
#      keepalive: how long between heartbeats?
#心跳时长
#keepalive 2
#
#      deadtime: how long-to-declare-host-dead?
#
#              If you set this too low you will get the problematic
#              split-brain (or cluster partition) problem.
#              See the FAQ for how to use warntime to tune deadtime.
#              如果这个时间值设置得过长将导致脑裂或集群分区的问题。
#心跳丢失后死亡时长
#deadtime 30
#
#      warntime: how long before issuing "late heartbeat" warning?
#      See the FAQ for how to use warntime to tune deadtime.
#     
#     
#心跳丢失后警告时长
#warntime 10
#
#
#      Very first dead time (initdead)
#
#      On some machines/OSes, etc. the network takes a while to come up
#      and start working right after you've been rebooted.  As a result
#      we have a separate dead time for when things first come up.
#      It should be at least twice the normal dead time.
#      在某些机器/操作系统等中,网络在机器启动或重启后需要花一定的时间启动并正常工作。
#      因此我们必须分开他们初次起来的dead time,这个值应该最少设置为两倍的正常dead time。
#
#初始死亡时长
#initdead 120
#
#
#      What UDP port to use for bcast/ucast communication?
#
#端口号的配置
#udpport        694
#
#      Baud rate for serial ports...                     
#
#波特率的配置
#baud  19200
#
#      serial  serialportname ...     
#串口名称                   
#serial /dev/ttyS0      # Linux
#serial /dev/cuaa0      # FreeBSD
#serial /dev/cuad0      # FreeBSD 6.x
#serial /dev/cua/a      # Solaris
#
#
#      What interfaces to broadcast heartbeats over?           
#
#广播的网络接口名称
#bcast  eth0            # Linux
#bcast  eth1 eth2      # Linux
#bcast  le0            # Solaris
#bcast  le1 le2        # Solaris
#
#      Set up a multicast heartbeat medium               
#      mcast [dev] [mcast group] [port] [ttl] [loop]
#
#      [dev]          device to send/rcv heartbeats on
#      [mcast group]  multicast group to join (class D multicast address
#                      224.0.0.0 - 239.255.255.255)
#      [port]          udp port to sendto/rcvfrom (set this value to the
#                      same value as "udpport" above)
#      [ttl]          the ttl value for outbound heartbeats.  this effects
#                      how far the multicast packet will propagate.  (0-255)
#                      Must be greater than zero.
#      [loop]          toggles loopback for outbound multicast heartbeats.
#                      if enabled, an outbound packet will be looped back and
#                      received by the interface it was sent on. (0 or 1)
#                      Set this value to zero.
#
#有关多播的配置
#mcast eth0 225.0.0.1 694 1 0
#
#      Set up a unicast / udp heartbeat medium           
#      ucast [dev] [peer-ip-addr]
#
#      [dev]          device to send/rcv heartbeats on
#      [peer-ip-addr]  IP address of peer to send packets to
#
#
#ucast eth0 192.168.1.2 
#
#对于广播,单播或多播,各有优缺点。
#单播多用于2节点情形,但是2节点上则不能使用相同的配置文件,因为ip地址不一样                                   
#
#
#      About boolean values...  关于boolean值
#     
#      下面的任意不区分大小写敏感值将被当作true
#      Any of the following case-insensitive values will work for true:
#              true, on, yes, y, 1
#      下面的任意不区分大小写敏感值将被当作false
#      Any of the following case-insensitive values will work for false:
#              false, off, no, n, 0
#     
#
#
#
#      auto_failback:  determines whether a resource will
#      automatically fail back to its "primary" node, or remain
#      on whatever node is serving it until that node fails, or
#      an administrator intervenes.
#      决定一个resource是否自动恢复到它的初始primary节点,
#      或者继续运行在转移后的节点直到出现故障或管理员进行干预。
#
#      The possible values for auto_failback are:
#              on      - enable automatic failbacks
#              off    - disable automatic failbacks
#              legacy  - enable automatic failbacks in systems
#                      where all nodes do not yet support
#                      the auto_failback option.
#
#      auto_failback "on" and "off" are backwards compatible with the old
#              "nice_failback on" setting.
#
#      See the FAQ for information on how to convert
#              from "legacy" to "on" without a flash cut.
#              (i.e., using a "rolling upgrade" process)
#
#      The default value for auto_failback is "legacy", which
#      will issue a warning at startup.  So, make sure you put
#      an auto_failback directive in your ha.cf file.
#      (note: auto_failback can be any boolean or "legacy")
#
#自动failback配置
auto_failback on
#
#
#      Basic STONITH support
#      Using this directive assumes that there is one stonith
#      device in the cluster.  Parameters to this device are
#      read from a configuration file. The format of this line is:
#
#        stonith <stonith_type> <configfile>
#
#      NOTE: it is up to you to maintain this file on each node in the
#      cluster!
#
#基本STONITH支持
#stonith baytech /etc/ha.d/conf/stonith.baytech
#
#      STONITH support
#      You can configure multiple stonith devices using this directive.
#      The format of the line is:
#        stonith_host <hostfrom> <stonith_type> <params...>
#        <hostfrom> is the machine the stonith device is attached
#              to or * to mean it is accessible from any host.
#        <stonith_type> is the type of stonith device (a list of
#              supported drives is in /usr/lib/stonith.)
#        <params...> are driver specific parameters.  To see the
#              format for a particular device, run:
#          stonith -l -t <stonith_type>
#
#
#      Note that if you put your stonith device access information in
#      here, and you make this file publically readable, you're asking
#      for a denial of service attack ;-)
#
#      To get a list of supported stonith devices, run
#              stonith -L
#      For detailed information on which stonith devices are supported
#      and their detailed configuration options, run this command:
#              stonith -h
#
#stonith_host *    baytech 10.0.0.3 mylogin mysecretpassword
#stonith_host ken3  rps10 /dev/ttyS1 kathy 0
#stonith_host kathy rps10 /dev/ttyS1 ken3 0
#
#      Watchdog is the watchdog timer.  If our own heart doesn't beat for
#      a minute, then our machine will reboot.
#      NOTE: If you are using the software watchdog, you very likely
#      wish to load the module with the parameter "nowayout=0" or
#      compile it without CONFIG_WATCHDOG_NOWAYOUT set. Otherwise even
#      an orderly shutdown of heartbeat will trigger a reboot, which is
#      very likely NOT what you want.
#
#watchdog计时器的配置
#watchdog /dev/watchdog
#     
#      Tell what machines are in the cluster
#      node    nodename ...    -- must match uname -n
#
#节点名称配置,重要,必须与uname -n获得的名字等同
#node  ken3
#node  kathy
#
#      Less common options...
#
#      Treats 10.10.10.254 as a psuedo-cluster-member
#      Used together with ipfail below...
#      note: don't use a cluster node as ping node
#      将10.10.10.254看成一个伪集群成员,与下面的 ipfail一起使用。
#      注意:不要使用一个集群节点作为ping节点,通常可以设置为Ping 网关。
#      此作用用于觉定集群重构的仲裁票数
#
#ping 172.25.99.250
#
#      Treats 10.10.10.254 and 10.10.10.253 as a psuedo-cluster-member
#      called group1. If either 10.10.10.254 or 10.10.10.253 are up
#      then group1 is up
#      Used together with ipfail below...
#      同上,意思是两个IP当中,任意一个ping通即可
#
#ping_group group1 10.10.10.254 10.10.10.253
#
#      HBA ping derective for Fiber Channel
#      Treats fc-card-name as psudo-cluster-member
#      used with ipfail below ...
#
#      You can obtain HBAAPI from http://hbaapi.sourceforge.net.  You need
#      to get the library specific to your HBA directly from the vender
#      To install HBAAPI stuff, all You need to do is to compile the common
#      part you obtained from the sourceforge. This will produce libHBAAPI.so
#      which you need to copy to /usr/lib. You need also copy hbaapi.h to
#      /usr/include.
#
#      The fc-card-name is the name obtained from the hbaapitest program
#      that is part of the hbaapi package. Running hbaapitest will produce
#      a verbose output. One of the first line is similar to:
#              Apapter number 0 is named: qlogic-qla2200-0
#      Here fc-card-name is qlogic-qla2200-0.
#
#hbaping fc-card-name
#
#
#      Processes started and stopped with heartbeat.  Restarted unless
#              they exit with rc=100
#      指定当一个heartbeat服务或节点宕机时如何处理。
#      开启ipfail则是重启对应的节点,该进程被自动监视,遇到故障则重新启动。
#      ipfail进程用于检测和处理网络故障,需要配合ping语句指定的ping node来检测网络连接。
#
#respawn userid /path/name/to/run
#respawn hacluster /usr/lib/heartbeat/ipfail
#
#      Access control for client api
#              default is no access
#
#apiauth client-name gid=gidlist uid=uidlist
#apiauth ipfail gid=haclient uid=hacluster

######################################
#
#      Unusual options. 不常用选项
#
######################################
#
#      hopfudge maximum hop count minus number of nodes in config
#hopfudge 1
#
#      deadping - dead time for ping nodes
#deadping 30
#
#      hbgenmethod - Heartbeat generation number creation method
#              Normally these are stored on disk and incremented as needed.
#hbgenmethod time
#
#      realtime - enable/disable realtime execution (high priority, etc.)
#              defaults to on
#realtime off
#
#      debug - set debug level
#              defaults to zero
#debug 1
#
#      API Authentication - replaces the fifo-permissions-based system of the past
#
#      You can put a uid list and/or a gid list.
#      If you put both, then a process is authorized if it qualifies under either
#      the uid list, or under the gid list.
#
#      The groupname "default" has special meaning.  If it is specified, then
#      this will be used for authorizing groupless clients, and any client groups
#      not otherwise specified.
#
#      There is a subtle exception to this.  "default" will never be used in the
#      following cases (actual default auth directives noted in brackets)
#                ipfail        (uid=HA_CCMUSER) Author : Leshami
#                ccm          (uid=HA_CCMUSER) Blog  : http://blog.csdn.net/leshami
#                ping          (gid=HA_APIGROUP)
#                cl_status    (gid=HA_APIGROUP)
#
#      This is done to avoid creating a gaping security hole and matches the most
#      likely desired configuration.
#      这避免生成一个安全漏洞缺口,可以实现能很多人最渴望的安全配置。
#
#apiauth ipfail uid=hacluster
#apiauth ccm uid=hacluster
#apiauth cms uid=hacluster
#apiauth ping gid=haclient uid=alanr,root
#apiauth default gid=haclient

#      message format in the wire, it can be classic or netstring,
#      default: classic
#msgfmt  classic/netstring

#      Do we use logging daemon?
#      If logging daemon is used, logfile/debugfile/logfacility in this file
#      are not meaningful any longer. You should check the config file for logging
#      daemon (the default is /etc/logd.cf)
#      more infomartion can be fould in http://www.linux-ha.org/ha_2ecf_2fUseLogdDirective
#      Setting use_logd to "yes" is recommended
#
# use_logd yes/no
#
#      the interval we  reconnect to logging daemon if the previous connection failed
#      default: 60 seconds
#conn_logd_time 60
#
#
#      Configure compression module
#      It could be zlib or bz2, depending on whether u have the corresponding
#      library in the system.
#compression    bz2
#
#      Confiugre compression threshold
#      This value determines the threshold to compress a message,
#      e.g. if the threshold is 1, then any message with size greater than 1 KB
#      will be compressed, the default is 2 (KB)
#compression_threshold 2

以上是配置文件的信息我们需要修改的是下面着几项:

48  keepalive 2       每两秒发送一次心跳包

56  deadtime 30      节点死亡时间,着这个时间内没有收到心跳包就认为其死亡

61  warntime 10       发出警告时间

71  initdead 60         守护进程首次启动等待60秒后启动主服务器上的资源

76  udpport 694        心跳信息传递接口(该端口不得有其他进程占用)

91  bcast   eth0         选择网卡eth0并且以udp广播形式工作

211  node    master

212  node    slave

220  ping 172.25.99.250   ping一个局域网中的其他主机用来确认网络通畅(一般写成网关)

253  respawn hacluster /usr/lib64/heartbeat/ipfail    默认的hearbrat并不检测除本身之外的其他任何服务,也比检测网络状态,所以网络中断时,并不会进行load balancer和backup之间的切换,可以通过ipfail插件,设置pingnodes来解决这一问题(这项参数中注意/usr/lib是lib64默认是lib)

259   apiauth ipfail gid=haclient uid=hacluster

修改authkeys

修改加密方式:

auth 3

#1  crc

#2  shal  HI !

3  md5  Hello!

修改配置文件haresources

master  IPaddr::172.25.99.100/24/eth0  httpd

以上配置文件是在66主机上配置的77主机的配置和这个一样所以直接scp过去覆盖就好

两台主机上安装http

yum install  httpd  -y(两台都要作)

写测试页:

66:  vim/var/www/html/index.html

master

77:  vim/var/www/html/index.html

slave

注意:安装完成后不要手动启动http服务

启动heartbeat

两台全部启动

/etc/init.d/heartbeat start

测试

另找一台主机配置好hosts文件

将master停止服务

使用curl命令查看发现服务器是slave

当再次把master主机启动后服务有跳转回来了