Skip to content

Instantly share code, notes, and snippets.

@shubham1172
Last active March 4, 2020 14:01

Revisions

  1. shubham1172 revised this gist Mar 3, 2020. No changes.
  2. shubham1172 revised this gist Mar 3, 2020. 1 changed file with 39 additions and 1 deletion.
    40 changes: 39 additions & 1 deletion container.py
    Original file line number Diff line number Diff line change
    @@ -1 +1,39 @@
    #test code
    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")
  3. shubham1172 created this gist Mar 3, 2020.
    1 change: 1 addition & 0 deletions container.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    #test code