Created
May 6, 2015 21:08
-
-
Save willkelly/1a7acaa1d97d4340277d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# apt-get install python-pip cgroup-bin | |
# pip install cgroups | |
import cgroups | |
import os | |
import time | |
import subprocess | |
def in_my_cgroup(cg): | |
def f(): | |
pid = os.getpid() | |
cg.add(pid) | |
return f | |
def init_cgroup(name): | |
cg = cgroups.Cgroup(name) | |
try: | |
cg.delete() | |
except: | |
pass | |
return cgroups.Cgroup(name) | |
def do_not_kill_on_oom(user, cg_name): | |
with open("/sys/fs/cgroup/memory/%s/%s/memory.oom_control" % (user, cg_name), "a") as f: | |
f.write("1\n") | |
def is_under_oom(user, cg_name): | |
with open("/sys/fs/cgroup/memory/%s/%s/memory.oom_control" % (user, cg_name), "r") as f: | |
for line in f: | |
if line.find("under_oom") == 0: | |
key, value = line.strip().split(" ") | |
return value == "1" | |
return False | |
def run_processes(cg1, cg2): | |
command=["./use_more_than_10_mb.py"] | |
p1 = subprocess.Popen(command, preexec_fn=in_my_cgroup(cg1), | |
stdout=subprocess.PIPE, | |
stderr=subprocess.PIPE) | |
p2 = subprocess.Popen(command, preexec_fn=in_my_cgroup(cg2), | |
stdout=subprocess.PIPE, | |
stderr=subprocess.PIPE) | |
return p1, p2 | |
def main(): | |
cg1 = init_cgroup('cg1') | |
cg2 = init_cgroup('cg2') | |
cg1.set_memory_limit(1) # limit = 1 MB | |
p1, p2 = run_processes(cg1, cg2) | |
p2.wait() | |
time.sleep(0.5) | |
print "p1 is under oom: %s" % is_under_oom("root", "cg1") | |
p1.wait() | |
assert(p1.returncode != 0) | |
assert(p2.returncode == 0) | |
print "p1 oomed, p2 succeeded with memory limit on p1" | |
cg1.set_memory_limit() | |
p1, p2 = run_processes(cg1, cg2) | |
p2.wait() | |
time.sleep(0.5) | |
print "p1 is under oom: %s" % is_under_oom("root", "cg1") | |
p1.wait() | |
assert(p1.returncode == 0) | |
assert(p2.returncode == 0) | |
print "p1 and p2 succeeded with no memory limit." | |
cg1.set_memory_limit(1) | |
do_not_kill_on_oom("root", "cg1") | |
p1, p2 = run_processes(cg1, cg2) | |
p2.wait() | |
time.sleep(0.5) | |
print "p1 is under oom: %s" % is_under_oom("root", "cg1") | |
cg1.set_memory_limit() # comment this out to hang forever | |
p1.wait() | |
print "p1 and p2 succeeded" | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment