Write uid_map and gid_map in /proc to create a user mapping
    that maps our user from outside the container to the same user inside the container
    (and no other users are mapped).
    @see: http://man7.org/linux/man-pages/man7/user_namespaces.7.html
    @param pid: The PID of the process in the container.

def setup_user_mapping(pid, uid=os.getuid(), gid=os.getgid()):
    """Write uid_map and gid_map in /proc to create a user mapping
    that maps our user from outside the container to the same user inside the container
    (and no other users are mapped).
    @see: http://man7.org/linux/man-pages/man7/user_namespaces.7.html
    @param pid: The PID of the process in the container.
    """
    proc_child = os.path.join("/proc", str(pid))
    try:
        uid_map = "{0} {1} 1".format(uid, os.getuid()) # map uid internally to our uid externally
        util.write_file(uid_map, proc_child, "uid_map")
    except IOError as e:
        logging.warning("Creating UID mapping into container failed: %s", e)

    try:
        util.write_file("deny", proc_child, "setgroups")
    except IOError as e:
        # Not all systems have this file (depends on the kernel version),
        # but if it does not exist, we do not need to write to it.
        if e.errno != errno.ENOENT:
            logging.warning("Could not write to setgroups file in /proc: %s", e)

    try:
        gid_map = "{0} {1} 1".format(gid, os.getgid()) # map gid internally to our gid externally
        util.write_file(gid_map, proc_child, "gid_map")
    except IOError as e:
        logging.warning("Creating GID mapping into container failed: %s", e)