Windows + Powershell + Graphite = Awesomeness
Anyone that knows or works with me is very much aware of my love and excitement for Graphite. At work we made the decision to use Graphite as our primary metrics solution moving away from a few paid and open-source solutions that weren’t scaling well. Our environment consists of both Windows and Linux based OS’s. Unfortunately most people end up sending metrics to Graphite from Linux based machines using tools like Collectd (another great tool!) and Windows is more or less forgotten. So I set out to figure out how we could collect system metrics in Windows and then send them over to Graphite. The solution: Powershell. Powershell which is Microsoft’s premier scripting language can leverage almost any .net object to accomplish almost any task. Here is a very simple example that can be leveraged to send almost anything from your windows box to a Graphite instance in your enviornment:
#Set the Graphite carbon server location and port number
$carbonServer = "graphitebox.mydomain.com"
$carbonServerPort = 2003
#Get Unix epoch Time
$epochTime=[int](Get-Date -UFormat "%s")
#Putting some value here that I want to send
$value = 1234
#Build our metric string in the format required by Graphite's carbon-cache service.
$metric = ("servers.mymachine.somemetric " + $value + " " + $epochTime)
#Stream results to the Carbon server
$socket = New-Object System.Net.Sockets.TCPClient
$socket.connect($carbonServer, $carbonServerPort)
$stream = $socket.GetStream()
$writer = new-object System.IO.StreamWriter($stream)
#Write out metric to the stream.
$writer.WriteLine($metric)
$writer.Flush() #Flush and write our metrics.
$writer.Close()
$stream.Close()