Skip to content

Instantly share code, notes, and snippets.

@shubham1172
Last active March 4, 2020 14:01
Show Gist options
  • Save shubham1172/7c53130e6e0258f998f331955564dc4c to your computer and use it in GitHub Desktop.
Save shubham1172/7c53130e6e0258f998f331955564dc4c to your computer and use it in GitHub Desktop.
HydPy February Container Snippet
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