keepalived使用shell语句检测haproxy的正确方法

keepalived是现在做高可用架构的重要工具。但使用脚本来检测应用是否正常却很麻烦。有什么更好的方法呢?

直接使用shell语句

keepalived支持在keepalived.conf配置文件中直接写上检测的语句,当然如果复杂的检测还是建议使用脚本。

! Configuration File for keepalived

global_defs {
    notification_email {
        root@localhost
    }
    router_id lb1
}

vrrp_script chk_haproxy {
    script "if [ $(ps -C haproxy --no-header | wc -l) -eq 0 ] ; then exit 1;fi"
    interval 3
    weight -20
}

vrrp_instance VI_1 {
    state BACKUP
    interface eth0
    virtual_router_id 151
    priority 95
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        172.29.101.90
    }
    track_script {
       chk_haproxy
    }
}

但keepalived启动后,出现了如下的日志:

Feb 27 11:01:28 centos92 Keepalived_vrrp[20653]: Registering Kernel netlink reflector
Feb 27 11:01:28 centos92 Keepalived_vrrp[20653]: Registering Kernel netlink command channel
Feb 27 11:01:28 centos92 Keepalived_vrrp[20653]: Registering gratuitous ARP shared channel
Feb 27 11:01:28 centos92 Keepalived_vrrp[20653]: Opening file '/etc/keepalived/keepalived.conf'.
Feb 27 11:01:28 centos92 Keepalived_vrrp[20653]: WARNING - default user 'keepalived_script' for script execution does not exist - please create.
Feb 27 11:01:28 centos92 Keepalived_vrrp[20653]: Cannot find script if in path
Feb 27 11:01:28 centos92 Keepalived_vrrp[20653]: Disabling track script chk_haproxy since not found
Feb 27 11:01:28 centos92 Keepalived_vrrp[20653]: VRRP_Instance(VI_1) removing protocol VIPs.

注意这两行

Feb 27 11:01:28 centos92 Keepalived_vrrp[20653]: Cannot find script if in path
Feb 27 11:01:28 centos92 Keepalived_vrrp[20653]: Disabling track script chk_haproxy since not found

这说明shell检测语句并没有生效,实际测试也证实了这点。那如何解决这个问题呢?

解决方法:巧用 sh

修改keepalived配置文件script项,如下:

script "/usr/bin/sh -c 'if [ $(ps -C haproxy --no-header | wc -l) -eq 0 ] ; then exit 1;fi'"

修改后重启keepalived,查看日志:

Feb 27 16:59:57 centos92 Keepalived_vrrp[614]: VRRP_Script(chk_haproxy) succeeded

解决问题!

你可能感兴趣的:(keepalived使用shell语句检测haproxy的正确方法)