Skip to content

Instantly share code, notes, and snippets.

@DavidGoodwin
Forked from wryfi/lxc_load.py
Last active April 9, 2017 22:08
Show Gist options
  • Save DavidGoodwin/61b5f644b868ecd484c5 to your computer and use it in GitHub Desktop.
Save DavidGoodwin/61b5f644b868ecd484c5 to your computer and use it in GitHub Desktop.
simple python script to check cpu utilization of lxc containers and print percentage
#!/usr/bin/python
# See https://gist.github.com/wryfi/3902757
# Crude CPU usage thing for container(s).
import multiprocessing, os, re, sys, time
import getopt
cgroup_dir = '/sys/fs/cgroup/lxc/'
# some sort of regexp to match container names you want to report on.
node_rgx = u'[a-z0-9]{3,}'
def main(interval, show_all = False):
cpus = multiprocessing.cpu_count()
startval = get_values()
time.sleep(interval)
endval = get_values()
for key, value in startval.iteritems():
if key in endval:
delta = int(endval[key]) - int(startval[key])
dpns = float(delta / interval)
dps = dpns / 1000000000
percent = dps / cpus
if show_all == False and percent <= 0.1 : # ignore < 0.1%
continue
print key + ':' + '{percent:.2%}'.format(percent=percent)
def get_values():
values = {}
# read the 'parent' cgroup for total figures.
if os.path.exists('%s/cpuacct.usage' % cgroup_dir):
with open('%s/cpuacct.usage' % cgroup_dir, 'rb') as tobj:
values['total'] = tobj.read()
else:
print "cpuacct.usage doesn't exist for cgroup_dir (%s) - invalid cgroup config?" % cgroup_dir
sys.exit(1)
# no go through each cgroup(note: node_rgx) , and find usage from it
for fd in os.listdir(cgroup_dir):
if os.path.isdir('%s/%s' % (cgroup_dir, fd)) and re.match(node_rgx, fd):
acctf = '%s/%s/cpuacct.usage' % (cgroup_dir, fd)
if os.path.isfile(acctf):
with open(acctf, 'rb') as accto:
values[fd] = accto.read()
return values
def usage() :
print "Usage: -i <interval> -a (show all, regardless of usage) or -h (show help). "
if __name__ == "__main__":
interval = 1
show_all = False
try :
opts, args = getopt.getopt(sys.argv[1:], 'hai:', ['help', 'all', 'interval='])
except getopt.GetoptError as err:
print str(err);
usage()
sys.exit(1)
for o, a in opts:
if o in ( '-i', '--interval') :
interval = int(a)
elif o in ( '-a', '--all' ):
show_all = True
elif o in ( '-h', '--help' ):
usage()
sys.exit(0)
else:
assert False, "Invalid option."
main(interval, show_all)
@DavidGoodwin
Copy link
Author

Changes: added some getopt fun (-a for all instances otherwise we omit those which have less than 0.1% of cpu time, and -i to change the interval we record over.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment