# Path: duct/outputs/opentsdb.py
# class OpenTSDB(Output):
#     def __init__(self, *a):
#     def createClient(self):
#     def stop(self):
#     def transformEvent(self, ev):
#     def sendEvents(self, events):
#     def tick(self):
# 
# Path: duct/utils.py
# class HTTPRequest(object):
#     """Helper class for creating HTTP requests.
#        Accepts a `timeout` to cancel requests which take too long
#     """
#     def __init__(self, timeout=120):
#         self.timeout = timeout
#         self.timedout = None
# 
#     def abort_request(self, request):
#         """Called to abort request on timeout"""
#         self.timedout = True
#         if not request.called:
#             try:
#                 request.cancel()
#             except error.AlreadyCancelled:
#                 return
# 
#     @defer.inlineCallbacks
#     def response(self, request):
#         """Response received
#         """
#         if request.length:
#             de = defer.Deferred()
#             request.deliverBody(BodyReceiver(de))
#             body = yield de
#             body = body.read()
#         else:
#             body = ""
# 
#         if (request.code < 200) or (request.code > 299):
#             raise Exception((request.code, body))
# 
#         defer.returnValue(body)
# 
#     def request(self, url, method='GET', headers={}, data=None, socket=None,
#                 follow_redirect=False):
#         """Perform an HTTP request
#         """
#         self.timedout = False
# 
#         if socket:
#             agent = SocketyAgent(reactor, socket)
#         else:
#             if url[:5] == 'https':
#                 if SSL:
#                     agent = Agent(reactor, WebClientContextFactory())
#                 else:
#                     raise Exception('HTTPS requested but not supported')
#             else:
#                 agent = Agent(reactor)
# 
#         request = agent.request(method.encode(), url.encode(),
#                                 Headers(headers),
#                                 StringProducer(data) if data else None)
# 
#         if self.timeout:
#             timer = reactor.callLater(self.timeout, self.abort_request,
#                                       request)
# 
#             def timeoutProxy(request):
#                 """Wrapper function to time-out requests
#                 """
#                 if timer.active():
#                     timer.cancel()
# 
#                 if follow_redirect and (request.code in (301, 302,)):
#                     location = request.headers.getRawHeaders('location')
#                     url = request.request.absoluteURI
#                     if location:
#                         if not location[0].startswith("http"):
#                             # Well this isn't really allowed
#                             if location[0].startswith("/"):
#                                 hp = '/'.join(url.split('/')[:3])
#                                 url = hp + location[0]
#                             else:
#                                 url = url.rstrip('/') + '/' + location[0]
#                         else:
#                             url = location[0]
# 
#                         log.msg("Redirecting to %s" % url)
# 
#                         return self.request(url, method=method, headers=headers,
#                                             data=data, socket=socket,
#                                             follow_redirect=follow_redirect)
#                     else:
#                         raise Exception("Server responded with %s code but no"
#                                         " location header" % request.code)
# 
#                 return self.response(request)
# 
#             def requestAborted(failure):
#                 """Request was aborted due to timeout
#                 """
#                 if timer.active():
#                     timer.cancel()
# 
#                 failure.trap(defer.CancelledError,
#                              error.ConnectingCancelledError)
# 
#                 raise Timeout(
#                     "Request took longer than %s seconds" % self.timeout)
# 
#             request.addCallback(timeoutProxy).addErrback(requestAborted)
#         else:
#             request.addCallback(self.response)
# 
#         return request
# 
# 
#     def getBody(self, url, method='GET', headers={}, data=None, socket=None):
#         """Make an HTTP request and return the body
#         """
# 
#         if 'User-Agent' not in headers:
#             headers['User-Agent'] = ['Ductd/1']
# 
#         return self.request(url, method, headers, data, socket)
# 
#     @defer.inlineCallbacks
#     def getJson(self, url, method='GET', headers={}, data=None, socket=None):
#         """Fetch a JSON result via HTTP
#         """
#         if 'Content-Type' not in headers:
#             headers['Content-Type'] = ['application/json']
# 
#         body = yield self.getBody(url, method, headers, data, socket)
# 
#         try:
#             if not body:
#                 defer.returnValue({})
#             response = json.loads(body)
#         except ValueError:
#             raise ValueError("Response was not JSON: %s" % repr(body))
# 
#         defer.returnValue(response)


import json
import base64
from twisted.internet import defer
from duct.outputs import opentsdb
from duct.utils import HTTPRequest
   :synopsis: Bosun output

.. moduleauthor:: Colin Alston <colin@imcol.in>
"""





class Bosun(opentsdb.OpenTSDB):
    """Bosun HTTP API output

    **Configuration arguments:**

    :param url: URL (default: http://localhost:4242)
    :type url: str.
    :param maxsize: Maximum queue backlog size (default: 250000, 0 disables)
    :type maxsize: int.
    :param maxrate: Maximum rate of documents added to index (default: 100)
    :type maxrate: int.
    :param interval: Queue check interval in seconds (default: 1.0)
    :type interval: int.
    :param user: Optional basic auth username
    :type user: str.
    :param password: Optional basic auth password
    :type password: str.
    :param debug: Log tracebacks from OpenTSDB
    :type debug: bool.
    """
    def __init__(self, *a):

# Path: duct/outputs/opentsdb.py
# class OpenTSDB(Output):
#     def __init__(self, *a):
#     def createClient(self):
#     def stop(self):
#     def transformEvent(self, ev):
#     def sendEvents(self, events):
#     def tick(self):
# 
# Path: duct/utils.py
# class HTTPRequest(object):
#     """Helper class for creating HTTP requests.
#        Accepts a `timeout` to cancel requests which take too long
#     """
#     def __init__(self, timeout=120):
#         self.timeout = timeout
#         self.timedout = None
# 
#     def abort_request(self, request):
#         """Called to abort request on timeout"""
#         self.timedout = True
#         if not request.called:
#             try:
#                 request.cancel()
#             except error.AlreadyCancelled:
#                 return
# 
#     @defer.inlineCallbacks
#     def response(self, request):
#         """Response received
#         """
#         if request.length:
#             de = defer.Deferred()
#             request.deliverBody(BodyReceiver(de))
#             body = yield de
#             body = body.read()
#         else:
#             body = ""
# 
#         if (request.code < 200) or (request.code > 299):
#             raise Exception((request.code, body))
# 
#         defer.returnValue(body)
# 
#     def request(self, url, method='GET', headers={}, data=None, socket=None,
#                 follow_redirect=False):
#         """Perform an HTTP request
#         """
#         self.timedout = False
# 
#         if socket:
#             agent = SocketyAgent(reactor, socket)
#         else:
#             if url[:5] == 'https':
#                 if SSL:
#                     agent = Agent(reactor, WebClientContextFactory())
#                 else:
#                     raise Exception('HTTPS requested but not supported')
#             else:
#                 agent = Agent(reactor)
# 
#         request = agent.request(method.encode(), url.encode(),
#                                 Headers(headers),
#                                 StringProducer(data) if data else None)
# 
#         if self.timeout:
#             timer = reactor.callLater(self.timeout, self.abort_request,
#                                       request)
# 
#             def timeoutProxy(request):
#                 """Wrapper function to time-out requests
#                 """
#                 if timer.active():
#                     timer.cancel()
# 
#                 if follow_redirect and (request.code in (301, 302,)):
#                     location = request.headers.getRawHeaders('location')
#                     url = request.request.absoluteURI
#                     if location:
#                         if not location[0].startswith("http"):
#                             # Well this isn't really allowed
#                             if location[0].startswith("/"):
#                                 hp = '/'.join(url.split('/')[:3])
#                                 url = hp + location[0]
#                             else:
#                                 url = url.rstrip('/') + '/' + location[0]
#                         else:
#                             url = location[0]
# 
#                         log.msg("Redirecting to %s" % url)
# 
#                         return self.request(url, method=method, headers=headers,
#                                             data=data, socket=socket,
#                                             follow_redirect=follow_redirect)
#                     else:
#                         raise Exception("Server responded with %s code but no"
#                                         " location header" % request.code)
# 
#                 return self.response(request)
# 
#             def requestAborted(failure):
#                 """Request was aborted due to timeout
#                 """
#                 if timer.active():
#                     timer.cancel()
# 
#                 failure.trap(defer.CancelledError,
#                              error.ConnectingCancelledError)
# 
#                 raise Timeout(
#                     "Request took longer than %s seconds" % self.timeout)
# 
#             request.addCallback(timeoutProxy).addErrback(requestAborted)
#         else:
#             request.addCallback(self.response)
# 
#         return request
# 
# 
#     def getBody(self, url, method='GET', headers={}, data=None, socket=None):
#         """Make an HTTP request and return the body
#         """
# 
#         if 'User-Agent' not in headers:
#             headers['User-Agent'] = ['Ductd/1']
# 
#         return self.request(url, method, headers, data, socket)
# 
#     @defer.inlineCallbacks
#     def getJson(self, url, method='GET', headers={}, data=None, socket=None):
#         """Fetch a JSON result via HTTP
#         """
#         if 'Content-Type' not in headers:
#             headers['Content-Type'] = ['application/json']
# 
#         body = yield self.getBody(url, method, headers, data, socket)
# 
#         try:
#             if not body:
#                 defer.returnValue({})
#             response = json.loads(body)
#         except ValueError:
#             raise ValueError("Response was not JSON: %s" % repr(body))
# 
#         defer.returnValue(response)


# Path: duct/outputs/bosun.py
import json
import base64
from twisted.internet import defer
from duct.outputs import opentsdb
from duct.utils import HTTPRequest

   :synopsis: Bosun output

.. moduleauthor:: Colin Alston <colin@imcol.in>
"""





class Bosun(opentsdb.OpenTSDB):
    """Bosun HTTP API output

    **Configuration arguments:**

    :param url: URL (default: http://localhost:4242)
    :type url: str.
    :param maxsize: Maximum queue backlog size (default: 250000, 0 disables)
    :type maxsize: int.
    :param maxrate: Maximum rate of documents added to index (default: 100)
    :type maxrate: int.
    :param interval: Queue check interval in seconds (default: 1.0)
    :type interval: int.
    :param user: Optional basic auth username
    :type user: str.
    :param password: Optional basic auth password
    :type password: str.
    :param debug: Log tracebacks from OpenTSDB
    :type debug: bool.
    """
    def __init__(self, *a):

        opentsdb.OpenTSDB.__init__(self, *a)