keepalived 詳解


什麼是Keepalived呢,keepalived觀其名可知,保持存活,在網絡裏面就是保持在線了,也就是所謂的高可用或熱備,用來防止單點故障(單點故障是指一旦某一點出現故障就會導致整個系統架構的不可用)的發生,那說到keepalived時不得不說的一個協議就是VRRP協議,可以說這個協議就是keepalived實現的基礎,那麼首先我們來看看VRRP協議


VRRP術語:

VRRP虛擬路由(VRRP router):


VRRP的優勢:

冗餘:可以使用多個路由器設備作爲LAN客戶端的默認網關,大大降低了默認網關成爲單點故障的可能性;

負載共享:允許來自LAN客戶端的流量由多個路由器設備所共享;

多VRRP組:在一個路由器物理接口上可配置多達255個VRRP組;

多IP地址:基於接口別名在同一個物理接口上配置多個IP地址,從而支持在同一個物理接口上接入多個子網;

搶佔:在master故障時允許優先級更高的backup成爲master;

通告協議:使用IANA所指定的組播地址224.0.0.18進行VRRP通告;

VRRP追蹤:基於接口狀態來改變其VRRP優先級來確定最佳的VRRP路由器成爲master;


IP地址擁有者(IP Address Owner):如果一個VRRP設備將虛擬路由器IP地址作爲真實的接口地址,則該設備被稱爲IP地址擁有者。如果IP地址擁有者是可用的,通常它將成爲Master。 



keepalived是一個類似於layer3, 4 & 5交換機制的軟件,也就是我們平時說的第3層、第4層和第5層交換。

Keepalived的作用是檢測web服務器的狀態,如果有一臺web服務器死機,或工作出現故障,Keepalived將檢測到,並將有故障的web服務器從系統中剔除,當web服務器工作正常後Keepalived自動將web服務器加入到服務器羣中,這些工作全部自動完成,不需要人工干涉,需要人工做的只是修復故障的web服務器。


Layer3:Keepalived使用Layer3的方式工作式時,Keepalived會定期向服務器羣中的服務器發送一個ICMP的數據包(既我們平時用的Ping程序),如果發現某臺服務的IP地址沒有激活,Keepalived便報告這臺服務器失效,並將它從服務器羣中剔除,這種情況的典型例子是某臺服務器被非法關機。Layer3的方式是以服務器的IP地址是否有效作爲服務器工作正常與否的標準。在本文中將採用這種方式。

Layer4:如果您理解了Layer3的方式,Layer4就容易了。Layer4主要以TCP端口的狀態來決定服務器工作正常與否。如web server的服務端口一般是80,如果Keepalived檢測到80端口沒有啓動,則Keepalived將把這臺服務器從服務器羣中剔除。

Layer5:Layer5就是工作在具體的應用層了,比Layer3,Layer4要複雜一點,在網絡上佔用的帶寬也要大一些。Keepalived將根據用戶的設定檢查服務器程序的運行是否正常,如果與用戶的設定不相符,則Keepalived將把服務器從服務器羣中剔除。


                             wKioL1h_CRegi_J8AAKw_IExP1o639.png


keepalived啓動後會有三個進程
父進程:內存管理,子進程管理等等
子進程:VRRP子進程
子進程:healthchecker子進程



keepalived配置文件詳解

global_defs {
   notification_email {          #指定keepalived在發生切換時需要發送email到的對象,一行一個
     [email protected]
   }
   notification_email_from [email protected] #指定發件人
   smtp_server localhost         #指定smtp服務器地址
   smtp_connect_timeout 30       #指定smtp連接超時時間
   router_id LVS_DEVEL           #運行keepalived機器的一個標識
}
vrrp_sync_group VG_1{            #監控多個網段的實例
group {
inside_network                   #實例名
outside_network
}
notify_master /path/xx.sh        #指定當切換到master時,執行的腳本
netify_backup /path/xx.sh        #指定當切換到backup時,執行的腳本
notify_fault "path/xx.sh VG_1"   #故障時執行的腳本
notify /path/xx.sh 
smtp_alert                       #使用global_defs中提供的郵件地址和smtp服務器發送郵件通知
}
vrrp_instance inside_network {
    state BACKUP                 #指定那個爲master,那個爲backup,如果設置了nopreempt這個值

                                  不起作用,主備考priority決定
    interface eth0               #設置實例綁定的網卡
    dont_track_primary           #忽略vrrp的interface錯誤(默認不設置)
    track_interface{             #設置額外的監控,裏面那個網卡出現問題都會切換
    eth0
    eth1
    }
    mcast_src_ip                 #發送多播包的地址,如果不設置默認使用綁定網卡的primary ip
    garp_master_delay            #在切換到master狀態後,延遲進行gratuitous ARP請求
    virtual_router_id 50         #VPID標記
    priority 99                  #定義優先級,數字越大,優先級越高,高優先級競選爲master
    advert_int 1                 #檢查間隔,默認1秒
    nopreempt                    #設置爲不搶佔 注:這個配置只能設置在backup主機上,而且這個

                                  主機優先級要比另外一臺高
    preempt_delay                #搶佔延時,默認5分鐘
    debug #debug級別
    authentication {             #設置認證
        auth_type PASS           #認證方式
        auth_pass 111111         #認證密碼
    }
    virtual_ipaddress {          #設置vip
        192.168.202.200
    }
}
virtual_server 192.168.202.200 23 {
    delay_loop 6 #健康檢查時間間隔
    lb_algo rr   #lvs調度算法rr|wrr|lc|wlc|lblc|sh|dh
    lb_kind DR   #負載均衡轉發規則NAT|DR|RUN
    persistence_timeout 5 #會話保持時間
    protocol TCP                #使用的協議
    persistence_granularity <NETMASK> #lvs會話保持粒度
    virtualhost <string>        #檢查的web服務器的虛擬主機(host:頭)    
    sorry_server<IPADDR> <port> #備用機,所有realserver失效後啓用
real_server 192.168.200.5 23 {
            weight 1            #默認爲1,0爲失效
            inhibit_on_failure  #在服務器健康檢查失效時,將其設爲0,而不是直接從ipvs中刪除 
            notify_up <string> | <quoted-string>   #在檢測到server up後執行腳本
            notify_down <string> | <quoted-string> #在檢測到server down後執行腳本
            
TCP_CHECK {
            connect_timeout 3          #連接超時時間
            nb_get_retry 3             #重連次數
            delay_before_retry 3       #重連間隔時間
            connect_port 23            #健康檢查的端口的端口
            bindto <ip>   
          }
HTTP_GET | SSL_GET{
    url{                                                 #檢查url,可以指定多個
         path /
         digest <string>                                 #檢查後的摘要信息
         status_code 200                                 #檢查的返回狀態碼
        }
    connect_port <port> 
    bindto <IPADD>
    connect_timeout 5
    nb_get_retry 3
    delay_before_retry 2
}

SMTP_CHECK{
    host{
    connect_ip <IP ADDRESS>
    connect_port <port>                                       #默認檢查25端口
    bindto <IP ADDRESS>
         }
    connect_timeout 5
    retry 3
    delay_before_retry 2
    helo_name <string> | <quoted-string>                      #smtp helo請求命令參數,可選
}
MISC_CHECK{
    misc_path <string> | <quoted-string>                      #外部腳本路徑
    misc_timeout                                              #腳本執行超時時間
    misc_dynamic                                              #如設置該項,則退出狀態碼會用來動態調整服務器的權重,返回0 正常,不修改;返回1,檢查失敗,權重改爲0;返回2-255,正常,權重設置爲:返回狀態碼-2
}
    }



配置keepalived爲實現haproxy高可用的配置文件示例:

========================================================================================

! Configuration File for keepalived


global_defs {

   notification_email {

         [email protected]

         [email protected]

   }

   notification_email_from [email protected]

   smtp_connect_timeout 3

   smtp_server 127.0.0.1

   router_id LVS_DEVEL

}


vrrp_script chk_haproxy {

    script "killall -0 haproxy"

    interval 1

    weight 2

}


vrrp_script chk_mantaince_down {

   script "[[ -f /etc/keepalived/down ]] && exit 1 || exit 0"

   interval 1

   weight -2

}


vrrp_instance VI_1 {

    interface eth0

    state MASTER  # BACKUP for slave routers

    priority 101  # 100 for BACKUP

    virtual_router_id 51

    garp_master_delay 1


    authentication {

        auth_type PASS

        auth_pass password

    }

    track_interface {

       eth0

    }

    virtual_ipaddress {

        172.16.100.1/16 dev eth0 label eth0:0

    }

    track_script {

        chk_haproxy

        chk_mantaince_down

    }


 

    notify_master "/etc/keepalived/notify.sh master"

    notify_backup "/etc/keepalived/notify.sh backup"

    notify_fault "/etc/keepalived/notify.sh fault"

}

========================================================================================


注意:

1、上面的state爲當前節點的起始狀態,通常在master/slave的雙節點模型中,其一個默認爲MASTER,而別一個默認爲BACKUP。

2、priority爲當關節點在當前虛擬路由器中的優先級,master的優先級應該大於slave的;



1、如何在狀態轉換時進行通知?


   notify_master ""

   notify_backup

   notify_fault


   vrrp_sync_group {


   }中定義,也可以在


   vrrp_instance {


   }中定義



通過man keepalived命令可以查看通知腳本定義的兩種方法

第一種

# to MASTER transition

notify_master /path/to_master.sh

# to BACKUP transition

notify_backup /path/to_backup.sh

# FAULT transition

notify_fault "/path/fault.sh VG_1"


第二種

#arguments

# $1 ="GROUP"|"INSTANCE"

# $2 = name of group or instance

# $3 = target state of transition

# ("MASTER"|"BACKUP"|"FAULT")

notify /path/notify.sh



MASTER:

#!/bin/bash

#

vip=172.16.100.100

contact='root@localhost'

thisip=`ifconfig eth0 |awk '/inet addr:/{print $2}' |awk -F: '{print $2}'`


notify() {

    mailbody="vrrp transaction, $vip floated to $thisip."

    subject="$thisip is to be $vip master"

    echo $mailbody | mail -s $subject $contact

}


notify




2、如何配置ipvs?

    virutal server

    realserver

        health check



3、如何對某特定服務做高可用?

   一:要提供監控服務腳本

   二:在vrrp實例中追蹤服務


   1.監控服務

     vrrp_script {


     }


   2.在vrrp實例中追蹤服務

     track_script {


     }


    nginx



4、如何實現基於多虛擬路由的master/master模型?

   一:定義兩個vrrp_instance就可以了

   二:DNS配置兩條A記錄



下面是一個notify.sh腳本的簡單示例:

#!/bin/bash

# Author: MageEdu <[email protected]>

# description: An example of notify script

#


vip=172.16.100.1

contact='root@localhost'


notify() {

    mailsubject="`hostname` to be $1: $vip floating"

    mailbody="`date '+%F %H:%M:%S'`: vrrp transition, `hostname` changed to be $1"

    echo $mailbody | mail -s "$mailsubject" $contact

}


case "$1" in

    master)

        notify master

        /etc/rc.d/init.d/haproxy start

        exit 0

    ;;

    backup)

        notify backup

        /etc/rc.d/init.d/haproxy stop

        exit 0

    ;;

    fault)

        notify fault

        /etc/rc.d/init.d/haproxy stop

        exit 0

    ;;

    *)

        echo 'Usage: `basename $0` {master|backup|fault}'

        exit 1

    ;;

esac

========================================================================================

以上配置keepalived會有問題,監控的服務不管是停止還是重啓,還是有問題!


直接在監控腳本中殺死keepalived進程!讓VIP轉到從節點。

例如haproxy服務監控腳本:

#!/bin/bash

#A = `ps -C haproxy --no-header |wc -l`

if [[ `ps -C haproxy --no-header |wc -l` -eq 0 ]];

then

echo "haproxy not runing,attempt to start up."

/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg

sleep 3

if [[ `ps -C haproxy --no-header |wc -l` -eq 0 ]];

then

/etc/init.d/keepalived stop

echo "haproxy start failure,stop keepalived"

else

echo "haproxy started success"

fi

fi

========================================================================================


案例:

當master down了,backup接管了,master再次起來,不會再成爲master。

否則master恢復了再接管的話。如果出現問題了,則切換兩次對網站業務來說並不好。

 

解決方法是:

state 都設置爲Backup,在優先級高的那臺設置參數nopreempt.


keepalived.conf中的man有說明

# VRRP will normally preempt a lower priority
# machine when a higher priority machine comes
# online. "nopreempt" allows the lower priority
# machine to maintain the master role, even when
# a higher priority machine comes back online.
# NOTE: For this to work, the initial state of this
# entry must be BACKUP.
nopreempt


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章