Last active
March 4, 2020 14:01
-
-
Save shubham1172/7c53130e6e0258f998f331955564dc4c to your computer and use it in GitHub Desktop.
HydPy February Container Snippet
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
import os | |
import sys | |
import unshare | |
import random | |
import string | |
import cgroups | |
if len(sys.argv) == 1: | |
print(f"Usage {sys.argv[0]} cmd args") | |
sys.exit(1) | |
cmd = sys.argv[1] | |
args = sys.argv[1:] | |
container_id = ''.join([random.choice(string.ascii_lowercase + string.digits) for _ in range(12)]) | |
BASE_PATH = "/home/shubham1172/Workspace/rootfs" | |
cg = cgroups.Cgroup(container_id) | |
cg.set_memory_limit(10) | |
cg.set_cpu_limit(0.2) | |
unshare.unshare(unshare.CLONE_NEWUTS | unshare.CLONE_NEWPID) | |
pid = os.fork() | |
if pid == 0: | |
# child process | |
os.system(f'hostname {container_id}') | |
cg.add(os.getpid()) | |
os.chroot(BASE_PATH) | |
os.chdir('/') | |
os.system('mount -t proc proc /proc') | |
print(f"(pid {os.getpid()}) executing {cmd} with args: {args}") | |
os.execv(cmd, args) | |
else: | |
# parent process | |
os.waitpid(pid, 0) | |
os.system(f'umount {BASE_PATH}/proc') | |
cg.delete() | |
print(f"(pid {os.getpid()}) child terminated") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment