Skip to content

Instantly share code, notes, and snippets.

@overplumbum
Last active December 12, 2015 00:48
Show Gist options
  • Save overplumbum/4685975 to your computer and use it in GitHub Desktop.
Save overplumbum/4685975 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# by denis@
import os
from subprocess import check_output as co, call
import time
def submit(value):
call("echo -n 'statsd.custom.cpuusage:{}|g' | nc -w 1 -u localhost 8125".format(value), shell=True)
if __name__ == '__main__':
HZ = os.sysconf(os.sysconf_names['SC_CLK_TCK'])
while True:
try:
pid = str(int(co(['pidof', '/usr/bin/node', '/usr/share/statsd/stats.js', '/etc/statsd/localConfig.js']).rstrip()))
except:
print "statsd not found"
time.sleep(10)
continue
prev_proc_utime = None
prev_real_utime = None
while True:
try:
s = open('/proc/' + pid + '/stat').read().split(' ')
except:
print "proc is dead, looking for new one"
break
proc_utime = int(s[13]) + int(s[14])
real_utime = int(HZ * time.time())
if prev_proc_utime:
proc_dt = proc_utime - prev_proc_utime
real_dt = real_utime - prev_real_utime
if real_dt > 0:
usage = int(100.0 * proc_dt / real_dt)
submit(usage)
prev_proc_utime = proc_utime
prev_real_utime = real_utime
time.sleep(60)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment