最近在做开发和办公环境的高可用,采用的是keepalived;keepalived基于Linux内核支持的LVS,既能实现高可用,又能实现负载均衡,非常实用。
keepalived监控服务状态时可以用多种方式,如:HTTP_GET|SSL_GET|TCP_CHECK|SMTP_CHECK|MISC_CHECK(自定义脚本方式),为了精确的监控服务的状态,我们需要编写自定义监控脚本。
目前很多公司都会部署nagios作为服务的监控平台,nagios也有监控脚本或者程序,如果keepalived监控脚本能套用naigios的,那么就可以省去很多麻烦。但是nagios监控脚本或者程序与keepalived有一些不同:
nagios脚本或者程序的返回值:0-OK,1-Warn, 2-Critical, 3-Unknown
keepalived脚本返回值:0-OK,1-Fail,2~255-OK且退出码-2
可见,只需要把nagios脚本或者程序的返回值改一下就可以用在keepalived上了。如果是文本格式的nagios脚本,可以直接改返回值,如果是二进制格式的程序,就不能直接改了。我采用的方法是把 nagios监控程序放到python里并且修改其返回值,这样就可以给keepalived用了。
下面的例子是用python把nagios的check_dns二进制监控程序改成keepalived能用的脚本,请注意commands.getstatusoutput里的命令,就是调用的nagios二进制监控程序:
(由于我的服务不需要修改退出状态码,因此只返回0或者1)
#!/usr/bin/python
#coding: utf-8
#返回0:健康检查OK,权重保持
#返回1:健康检查失败,权重设为0
#返回2-255:健康检查OK,权重设置为:退出状态码-2
import commands
import sys, getopt
import os.path
def check_dns(server='', timeout='', name='', address=''):
status, output = commands.getstatusoutput("/usr/lib64/nagios/plugins/check_dns -s " + server + " -t " + timeout + " -H " + name + " -a " + address)
return status
if __name__ == '__main__':
server, timeout, name, address = '', '', '', ''
script = os.path.split(os.path.realpath(__file__))[1]
try:
opts, args = getopt.getopt(sys.argv[1:], "s:n:a:t:", ["server=", "name=", "address=", "timeout="])
except getopt.GetoptError, err:
#print str(err)
sys.exit(3)
for o, a in opts:
if o in ("-s", "--server"):
server = a
elif o in ("-n", "--name"):
name = a
elif o in ("-a", "--address"):
address = a
elif o in ("-t", "--timeout"):
timeout = a
else:
#print "usage: " + script + " -s server -n name -a address -t timeout"
sys.exit(3)
if server == '' or name == '' or address == '' or timeout == '':
#print "usage: " + script + " -s server -n name -a address -t timeout"
sys.exit(3)
else:
status = check_dns(server, timeout, name, address)
if status:
#print status
sys.exit(1)
else:
#print status
sys.exit(0)