Last active
December 19, 2015 00:29
-
-
Save bcap/5868937 to your computer and use it in GitHub Desktop.
Python HTTP proxy (mod_python) for graphite-carbon
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# apache2 virtual host configuration | |
<VirtualHost *:80> | |
ServerName graphite | |
DocumentRoot "/opt/graphite/webapp" | |
ErrorLog "/var/log/graphite/error.log" | |
CustomLog "/var/log/graphite/access.log" common | |
<Location "/carbon-web-proxy/v1.0/"> | |
SetHandler python-program | |
PythonPath "['/opt/carbon/web-proxy/v1.0'] + sys.path" | |
PythonHandler web-proxy | |
PythonDebug Off | |
PythonAutoReload Off | |
</Location> | |
</VirtualHost> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: UTF-8 -*- | |
# this file resides at /opt/carbon/web-proxy/v1.0 | |
import settings | |
import re | |
import time | |
from mod_python import apache | |
from socket import socket | |
LINE_PATTERN = re.compile('\n') | |
WHITESPACE_PATTERN = re.compile('\s+') | |
def metrics_uri_handler(req): | |
if req.method != 'POST': | |
return apache.HTTP_METHOD_NOT_ALLOWED | |
data = req.read().strip() | |
lines = [] | |
for line in LINE_PATTERN.split(data): | |
line = line.strip() | |
fields = WHITESPACE_PATTERN.split(line) | |
if len(fields) == 2: | |
fields.append(str(long(time.time()))) | |
elif len(fields) != 3: | |
return apache.HTTP_BAD_REQUEST | |
lines.append(' '.join(fields)) | |
message = '\n'.join(lines) + '\n' | |
try : | |
sock = socket() | |
sock.connect((settings.carbon_host, settings.carbon_port)) | |
sock.sendall(message) | |
# echo the written data back to the client | |
req.write(message) | |
return apache.OK | |
except Exception, e: | |
return apache.HTTP_BAD_GATEWAY | |
def default_uri_handler(req): | |
return apache.HTTP_NOT_FOUND | |
uri_handlers = { | |
'/v1.0/metrics': metrics_uri_handler | |
} | |
def handler(req): | |
req.content_type = "text/plain" | |
return uri_handlers.get(req.path_info, default_uri_handler)(req) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# this file resides at /opt/carbon/web-proxy/v1.0 | |
carbon_host = "127.0.0.1" | |
carbon_port = 2003 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment