#!/usr/bin/env python

"""
 Copyright (c) 2012 Yahoo! Inc. All rights reserved.
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,   
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License. See accompanying LICENSE file.
"""


import sys
import socket
import json

# Default socket filename
socket_file = '/tmp/haproxy_socket'

def get_haproxy_socket_filename():
  socket_file=None
  # Open the haproxy config and see if we can find the socket file
  for line in open('/etc/haproxy/haproxy.cfg'):
    splitline=line.strip().split()
    if len(splitline) > 2 and splitline[0] == 'stats' and splitline[1] == 'socket':
      socket_file=splitline[2]
      break
  return socket_file

def query_haproxy_socket(socket_file='/tmp/haproxy',command='show stat'):
  if not command.endswith('\n'):
      command += '\n'
  s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  s.connect(socket_file)
  s.send(command)
  data=""
  d=s.recv(1024)
  while d:
    data+=d
    d=s.recv(1024)
  #data = s.recv()
  s.close()
  return data

def get_backends(vip,state='ALL'):  
  hosts=[]
  for line in query_haproxy_socket(get_haproxy_socket_filename(),'show stat').split('\n'):
    if not line.startswith('#') and len(line.strip()):
      splitline=line.strip().split(',')
      if splitline[0]==vip and splitline[1] != 'BACKEND':
        if state.upper() == 'ALL' or (splitline[17]==state):
          hosts.append(splitline[1])
  return hosts

state='ALL'
if len(sys.argv) > 2 and sys.argv[2].upper() in ['UP','DOWN']:
  state=sys.argv[2].upper()
print json.dumps(get_backends(sys.argv[1],state),indent=4)
