Code Snippet: Keep Alive check for servers

When you want to test out if your webserver configuration currently is supporting Keep-Alive requests and how it’s responding them, there are several ways. You could use Firebug, Chrome Developer Tools or you could use benchmarking tools like “ab” (ApacheBench) and so on. For me “ab” was always a good choice, but I seem to have found some weakness in it…

Unfortunately, it seems that “ab” is unreliable when it comes to Keep-Alive and Firebug & Co. are not very handy for a quick test and so I wrote a simple keep-alive test in Python.

#!/usr/bin/env python
 
#
# Simple Keep-Alive test for servers
# This script only tests, if keep-alive connections are possible. No other checks
# are made. Also for now only domains can be checked. If you want location
# support, you'll have to implement it yourself.
# To test that we send a HEAD request to the server and parse the response.
#
# @author Matin Albrecht <martin.albrecht@javacoffee.de>
#
from httplib import *
import sys
import time
 
#
# Fetch the header from the server
def getHeader(url):
  conn = HTTPConnection(url)
  conn.request("HEAD", "/")
  res = conn.getresponse()
  header = res.getheaders()
  data = {}
 
  for i, key in enumerate(header):
    data[key[0]] = key[1]
 
  conn.close()
  return data
## END ##
 
#
# Keep-Alive check
def checkKeepAlive(count, url):
  start = time.time();
  failed = 0
  if count <= 0:
    count = 1
 
  print "-------------------------------------------------"
  print "\t  Simple Keep-Alive check\n(c)2012 Martin Albrecht - http://javacoffee.de"
  print "-------------------------------------------------\n"
  print "URL: " + url + "\nCount:", count
 
  for i in range(0,count):
    header = getHeader(url)
 
    if not 'connection' in header.keys():
      print "Error: Keep-Alive unsupported!"
      break
 
    if not header['connection']:
      print "Error: No connection header field!"
      break
 
    if header['connection'] != 'keep-alive':
      failed += 1
      sys.stdout.write("x")
    else:
      sys.stdout.write(".")
 
    sys.stdout.flush()
    #time.sleep(0.3)  ## UNCOMMENT THIS IF YOU WANT LESS SERVER LOAD
 
  end = time.time();
  duration = end-start
  print "\n\nTime needed:", duration, "seconds"
  print "Request/Sec.:", (count/duration)
  print "Result: " + str(failed) + "/" + str(i+1) + " failed requests..."
## END ##
 
#### START  OF SCRIPT ####
if len(sys.argv) < 3:
  print "Usage: " + sys.argv[0] + " <url> <count>"
else:
  url = sys.argv[1]
  count = int(sys.argv[2])
  checkKeepAlive(count, url)

This test is not complex and only test the root page of the domain with a HTTP HEAD request. If you want more complex tasks to do, feel free to  extend the code!

Similar Posts: