Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Send Windows perf counters to Graphite
import time
import socket
import pywintypes
import win32pdh
class Win32Performance:
def __init__( self ):
self.counters = []
self.hq = win32pdh.OpenQuery()
def addCounter( self, object, counter, instance=None ):
try:
wcounter = Win32Counter( object, counter, instance )
wcounter.open( self.hq )
except pywintypes.error:
pass
self.counters.append(wcounter)
def get( self, pause=None ):
win32pdh.CollectQueryData( self.hq )
if pause:
time.sleep( pause )
win32pdh.CollectQueryData( self.hq )
perfvals = {}
for c in self.counters:
val = c.getValue()
perfvals[c.name] = val
return perfvals
def close( self ):
win32pdh.CloseQuery( self.hq )
class Win32Counter:
def __init__( self, object, counter, instance=None, machine=None ):
self.object = object
self.counter = counter
self.instance = instance
self.machine = machine
self.inum = -1
self.path = None
self.hc = None
self.name = "%s %s" %(object, counter)
if instance:
self.name = self.name + " %s" %(instance)
def open( self, hq ):
self.path = win32pdh.MakeCounterPath( (self.machine, self.object, self.instance, None, self.inum, self.counter) )
self.hc = win32pdh.AddCounter( hq, self.path )
def close( self ):
win32pdh.RemoveCounter( self.hc )
def getValue( self, format=win32pdh.PDH_FMT_LONG ):
try:
type, val = win32pdh.GetFormattedCounterValue(self.hc, format)
except pywintypes.error:
type = None
val = None
return val
def getCounters( object ):
counters, instances = win32pdh.EnumObjectItems(None, None, object, win32pdh.PERF_DETAIL_WIZARD)
return counters
def getInstances( object ):
counters, instances = win32pdh.EnumObjectItems(None, None, object, win32pdh.PERF_DETAIL_WIZARD)
return instances
if __name__ == "__main__":
CARBON_SERVER = 'graphite.dataloop.io'
CARBON_PORT = 2003
PREFIX = '72ec61f4-3c8d-4f7b-aea9-5065e6843c24vb181782f-23be-4ce1-82f5-de332553e3c7.'
sock = socket.socket()
sock.connect((CARBON_SERVER, CARBON_PORT))
p = Win32Performance()
objects = win32pdh.EnumObjects(None, None, -1, 0)
for object in objects:
(counters, instances) = win32pdh.EnumObjectItems(None, None, object, -1, 0)
for counter in counters:
try:
p.addCounter(object, counter)
except:
pass
p.get()
result = p.get()
for k in result:
if isinstance(result[k], (int, long, float, complex)):
message = '%s%s %s %s' % (PREFIX, k.replace(' ', '_').replace('/', '_per_').lower(), result[k], int(time.time()))
print message
sock.sendall(message)
sock.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment