Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enter process ns utility #259

Merged
merged 7 commits into from
Aug 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 28 additions & 15 deletions granulate_utils/linux/ns.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,27 +246,13 @@ def run_in_ns(

for ns in nstypes:
assert_ns_str(ns)
# make sure "mnt" is last, once we change it our /proc is gone
nstypes = sorted(nstypes, key=lambda ns: 1 if ns == "mnt" else 0)

ret: Union[T, _Sentinel] = _SENTINEL
exc: Optional[BaseException] = None

def _switch_and_run():
try:
global libc
if libc is None:
libc = ctypes.CDLL("libc.so.6")

for nstype in nstypes:
if not is_same_ns(target_pid, nstype):
flag = NsType[nstype].value
if libc.unshare(flag) != 0:
raise ValueError(f"Failed to unshare({nstype})")

with open(f"/proc/{target_pid}/ns/{nstype}", "r") as nsf:
if libc.setns(nsf.fileno(), flag) != 0:
raise ValueError(f"Failed to setns({nstype}) (to pid {target_pid})")
enter_process_ns(nstypes, target_pid)

nonlocal ret
ret = callback()
Expand Down Expand Up @@ -363,3 +349,30 @@ def get_host_pid(nspid: int, container_id: str) -> Optional[int]:
continue

return None


def enter_process_ns(
nstypes: List[str],
target_pid: int = 1,
) -> None:
"""
Swaps to a set of the namespaces of a target process.
"""
for ns in nstypes:
assert_ns_str(ns)
# make sure "mnt" is last, once we change it our /proc is gone
nstypes = sorted(nstypes, key=lambda ns: 1 if ns == "mnt" else 0)

global libc
if libc is None:
libc = ctypes.CDLL("libc.so.6")

for nstype in nstypes:
if not is_same_ns(target_pid, nstype):
flag = NsType[nstype].value
if libc.unshare(flag) != 0:
raise ValueError(f"Failed to unshare({nstype})")

with open(f"/proc/{target_pid}/ns/{nstype}", "r") as nsf:
if libc.setns(nsf.fileno(), flag) != 0:
raise ValueError(f"Failed to setns({nstype}) (to pid {target_pid})")
Loading