#! /usr/bin/env python
# -*- coding: utf-8 -*-
import StringIO
import json
import urllib2

'''
rabbitmq 支持 curl
http://www.quietless.com/kitchen/curl-requests-http-authentication-in-python/
'''

base_url = "http://10.10.125.126:15672/api/queues/%2f/"
username = "guest"
password = "guest"

def list_queues():
    '''
    获取所有Queue的信息
    '''
    # first encode the username & password 
    userData = "Basic " + (username + ":" + password).encode("base64").rstrip()
    # create a new Urllib2 Request object   
    req = urllib2.Request(base_url)
    # add any additional headers you like 
    req.add_header('Accept', 'application/json')
    req.add_header("Content-type", "application/x-www-form-urlencoded")
    # add the authentication header, required
    req.add_header('Authorization', userData)
    # make the request and print the results
    res = urllib2.urlopen(req)
    return res.read()

def monitor_mq():
    '''
    '''
    rs = list_queues()
    if not rs:
        return 
 
    content = ""
    content += "<table>"                                                                                   
    content += "<tr><td colspan=4>ps: RabbitMQ消息</td></tr>"             
    content += "<tr><td colspan=4>" + "".center(120,"-") + "</td></tr>"     
    output_format = "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></p>"  
    content += output_format % ("name", "messages", "messages_ready", "consumers")        
    j_rs = json.loads(rs)
    for i in j_rs:
        content += output_format % (str(i["name"]), str(i["messages"]), str(i["messages_ready"]), str(i["consumers"]))
    content += "<tr><td colspan=4>" + "".center(120,"-") + "</td></tr>"                                                                
    content += "</table>"
    return content

