Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
show memory usage in memcg.
#!/usr/bin/env python3
import argparse
import os
import sys
import time
import signal
def sigint_handler(signalnum, handler):
sys.exit(0)
def show_header():
print("%s %s %s %s %s %s %s" % ('memory.usage', 'memsw.usage', 'kmem.usage', 'rss', 'rss(huge)', 'cache', 'swap'))
def read_memory_stat_file(hierarchy):
filename = "/sys/fs/cgroup/memory/%s/memory.stat" % (hierarchy)
stat = {}
with open(filename, mode='r') as f:
lines = f.readlines()
for line in lines:
data = line.split(' ')
stat[data[0]] = data[1].strip()
return stat
def read_cgroup_file(hierarchy, filename):
fullpath = "/sys/fs/cgroup/memory/%s/%s" % (hierarchy, filename)
with open(fullpath, mode='r') as f:
return f.read().strip()
def show_mem_stat(args):
usage = read_cgroup_file(args['mem_hierarchy'], 'memory.usage_in_bytes')
memsw_usage = read_cgroup_file(args['mem_hierarchy'],'memory.memsw.usage_in_bytes' )
kmem_usage = read_cgroup_file(args['mem_hierarchy'],'memory.kmem.usage_in_bytes' )
stat = read_memory_stat_file(args['mem_hierarchy'])
rss = stat['rss']
rss_huge = stat['rss_huge']
cache = stat['cache']
swap = stat['swap']
msg = "%s %s %s %s %s %s %s" % (usage, memsw_usage, kmem_usage, rss, rss_huge, cache, swap)
print(msg)
def hierarchy(pid, subsys):
filename = "/proc/%d/cgroup" % pid
keyword = ":%s:" % subsys
with open(filename, mode='r') as f:
lines = f.readlines()
for line in lines:
if line.find(keyword) >= 0:
arr = line.split(':')
return arr[2].strip()
sys.stderr.write("Couldn't find memory cgroup for pid %d\n" % (pid))
sys.exit(-1)
def memcg_hierarchy(pid):
return hierarchy(pid, 'memory')
def parse_argument():
parser = argparse.ArgumentParser(description = 'vmstat like tool for memory cgroup')
parser.add_argument('-c', '--count', type=int, default=1, metavar='COUNT', help='count')
parser.add_argument('-d', '--delay',help='delay second', type=int, metavar='SECOND', default=1)
parser.add_argument('-p', '--pid', help='pid', metavar='PID', type=int, default=os.getpid())
args = parser.parse_args()
vmstat_args = {}
vmstat_args['pid'] = args.pid
vmstat_args['count'] = args.count
vmstat_args['delay'] = args.delay
return vmstat_args
if __name__ == "__main__":
signal.signal(signal.SIGINT, sigint_handler)
memcg_stat_args = parse_argument()
memcg_stat_args['mem_hierarchy'] = memcg_hierarchy(memcg_stat_args['pid'])
for i in range(memcg_stat_args['count']):
if i % 10 == 0:
show_header()
show_mem_stat(memcg_stat_args)
time.sleep(memcg_stat_args['delay'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment