Saturday, September 20, 2014

Enable/Disable HAproxy Backend Servers via Python

Sometimes we may want to automatically enable/disable machines behind our HAproxy automatically (during a deploy or maintenance), this is how it's done via Python code. The idea is to use HAproxy Unix Socket based API.
import socket
import os
def haproxy_ctrl(command, socket_path, backend, machine):
command_str = ''
if os.path.exists(socket_path):
client = socket.socket( socket.AF_UNIX, socket.SOCK_STREAM )
print socket_path
client.connect(socket_path)
command_str+=command+' server '+backend+'/'+machine+"\n"
try:
print '[debug] executing =>',command_str
client.send(command_str)
except Exception, e:
print str(e)
client.close()
#invoke
command = 'disable'
ha_socket = '/var/lib/run/haproxystat'
backend = 'tomcats'
machine = 'tomcat01.domain.local'
haproxy_ctrl (command, ha_socket, backend, machine)
view raw haproxy_python hosted with ❤ by GitHub