Archive

Posts Tagged ‘HAProxy’

Accessing HAProxy statistics with Python

July 1st, 2011 Comments off

HAProxy exposes some if its statistics through a UNIX socket and it turns out it’s very easy to access it from Python, like below.

I guess the code is pretty self-explanatory – essentially it’s expecting you to give it a path to the socket and then to feed it with commands. Some commands  may need an extra argument, like ‘show sess’ does and if you’re particularly impatient – or maybe you’re under a very heavy load – you can also you use the ‘timeout’ parameter to specify how long you’re willing to wait for HAProxy to reply.

The responses are returned as-is and actually I wouldn’t mind it if someone took the code and added a nice OO look’n'feel to it so that it read like here ..

stats = HAProxyStats('/tmp/haproxy-stat.sock')
sess = stats.sess('0x19e8fd0')
print(sess.svname)

.. that could make for a useful project but for now, here’s some code that works today :-)

# -*- coding: utf-8 -*-
 
from __future__ import absolute_import, division, print_function, unicode_literals
 
# stdlib
import logging
import socket
from cStringIO import StringIO
from time import time
from traceback import format_exc
 
logger = logging.getLogger(__name__)
 
class HAProxyStats(object):
    """ Used for communicating with HAProxy through its local UNIX socket interface.
    """
    def __init__(self, socket_name=None):
        self.socket_name = socket_name
 
    def execute(self, command, extra="", timeout=200):
        """ Executes a HAProxy command by sending a message to a HAProxy's local
        UNIX socket and waiting up to 'timeout' milliseconds for the response.
        """
 
        if extra:
            command = command + ' ' + extra
 
        buff = StringIO()
        end = time() + timeout
 
        client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
 
        try:
            client.connect(self.socket_name)
            client.send(command + '\n')
 
            while time()

@fourthrealm

Share
Categories: Software Tags: , ,