Skip to content

Instantly share code, notes, and snippets.

@cobusc
Created June 17, 2014 06:19
Show Gist options
  • Save cobusc/d5023f65ca37210549da to your computer and use it in GitHub Desktop.
Save cobusc/d5023f65ca37210549da to your computer and use it in GitHub Desktop.
Publishing to graphite/carbon via HTTP
<?php
#
# This script provides an HTTP interface to carbon/graphite.
# The intention is that this script will
# [1] allow for easy integration with core apps,
# [2] can provide access control via Apache's authentication mechanisms.
#
function publish_data($path, $value, $timestamp)
{
$row = sprintf("%s %s %d\n", $path, $value, $timestamp);
/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (FALSE === $socket)
trigger_error("socket_create() failed: reason: " . socket_strerror(socket_last_error()));
if (FALSE === socket_connect($socket, "127.0.0.1", 2003))
trigger_error("socket_connect() failed.\nReason: " . socket_strerror(socket_last_error($socket)));
if (FALSE === socket_write($socket, $row))
trigger_error("socket_write() failed.\nReason: " . socket_strerror(socket_last_error($socket)));
# Carbon does not give any response. No use to try and read anything.
# $response = socket_read($socket, 4096);
# if (FALSE === $response)
# trigger_error("socket_read() failed.\nReason: " . socket_strerror(socket_last_error($socket)));
socket_close($socket);
}
function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars)
{
header("HTTP/1.1 400");
die ($errmsg);
}
set_error_handler("userErrorHandler", E_ALL);
error_reporting(E_ALL);
if (isset($_REQUEST['path']))
$path = $_REQUEST['path'];
else
trigger_error("Path not specified");
if (isset($_REQUEST['value']))
{
if (is_numeric($_REQUEST['value']))
$value = $_REQUEST['value'];
else
trigger_error("Value must be numeric");
}
else
trigger_error("Value not specified");
if (isset($_REQUEST['timestamp']))
{
if (ctype_digit($_REQUEST['timestamp']))
$timestamp = (int)$_REQUEST['timestamp'];
else
trigger_error("Timestamp must be an integer");
}
else
trigger_error("timestamp");
publish_data($path, $value, $timestamp);
$result = array("success" => TRUE);
echo json_encode($result);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment