Mini Shell

Direktori : /opt/imh-python/lib/python2.7/site-packages/mtrlib/
Upload File :
Current File : //opt/imh-python/lib/python2.7/site-packages/mtrlib/carbon.py

"""Functions for dealing with carbon/graphite data"""

import socket
import time
import random

RELAY_PORTS = [2003, 2005, 2007, 2009]

def carbon_post(
        data,
        server='graphite.imhadmin.net',
        port=None,
        chunk_size=500,
        chunk_sleep=0.2,
        max_tries=3
):
    """Post all items in a list of strings to Carbon"""
    if port is None:
        port = random.choice(RELAY_PORTS)
    if not isinstance(data, list):
        raise ValueError('carbon_post data must be a list')
    to_carbon = data[:] # create a new copy in memory
    success = True
    while len(to_carbon) > 0 and success:
        chunk = []
        for _ in xrange(chunk_size):
            try:
                chunk.append(to_carbon.pop(0))
            except IndexError:
                continue
        for attempt in xrange(max_tries): # attempt to post it 3 times
            try:
                sock = socket.socket()
                sock.connect((server, port))
                sock.sendall('{0}\n'.format('\n'.join(chunk)))
                sock.close()
                success = True
                break # stop trying
            except socket.error:
                success = False
                if attempt < max_tries - 1:
                    time.sleep(chunk_sleep)
        if len(to_carbon) > 0:
            time.sleep(chunk_sleep)
    return success

Zerion Mini Shell 1.0